]> git.mjollnir.org Git - moodle.git/commitdiff
Latest version of ADOdb. Now compatible with PHP5
authormoodler <moodler>
Tue, 13 Jul 2004 03:13:35 +0000 (03:13 +0000)
committermoodler <moodler>
Tue, 13 Jul 2004 03:13:35 +0000 (03:13 +0000)
99 files changed:
lib/adodb/adodb-csvlib.inc.php
lib/adodb/adodb-datadict.inc.php
lib/adodb/adodb-error.inc.php
lib/adodb/adodb-errorhandler.inc.php
lib/adodb/adodb-errorpear.inc.php
lib/adodb/adodb-exceptions.inc.php
lib/adodb/adodb-iterator.inc.php
lib/adodb/adodb-lib.inc.php
lib/adodb/adodb-pager.inc.php
lib/adodb/adodb-pear.inc.php
lib/adodb/adodb-perf.inc.php
lib/adodb/adodb-php4.inc.php
lib/adodb/adodb-time.inc.php
lib/adodb/adodb-time.zip
lib/adodb/adodb.inc.php
lib/adodb/datadict/datadict-access.inc.php
lib/adodb/datadict/datadict-db2.inc.php
lib/adodb/datadict/datadict-firebird.inc.php [new file with mode: 0644]
lib/adodb/datadict/datadict-generic.inc.php
lib/adodb/datadict/datadict-ibase.inc.php
lib/adodb/datadict/datadict-informix.inc.php
lib/adodb/datadict/datadict-mssql.inc.php
lib/adodb/datadict/datadict-mysql.inc.php
lib/adodb/datadict/datadict-oci8.inc.php
lib/adodb/datadict/datadict-postgres.inc.php
lib/adodb/datadict/datadict-sybase.inc.php
lib/adodb/drivers/adodb-access.inc.php
lib/adodb/drivers/adodb-ado.inc.php
lib/adodb/drivers/adodb-ado_access.inc.php
lib/adodb/drivers/adodb-ado_mssql.inc.php
lib/adodb/drivers/adodb-borland_ibase.inc.php
lib/adodb/drivers/adodb-csv.inc.php
lib/adodb/drivers/adodb-db2.inc.php
lib/adodb/drivers/adodb-fbsql.inc.php
lib/adodb/drivers/adodb-firebird.inc.php
lib/adodb/drivers/adodb-ibase.inc.php
lib/adodb/drivers/adodb-informix.inc.php
lib/adodb/drivers/adodb-informix72.inc.php
lib/adodb/drivers/adodb-ldap.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-mssql.inc.php
lib/adodb/drivers/adodb-mssqlpo.inc.php
lib/adodb/drivers/adodb-mysql.inc.php
lib/adodb/drivers/adodb-mysqli.inc.php
lib/adodb/drivers/adodb-mysqlt.inc.php
lib/adodb/drivers/adodb-netezza.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-oci8.inc.php
lib/adodb/drivers/adodb-oci805.inc.php
lib/adodb/drivers/adodb-oci8po.inc.php
lib/adodb/drivers/adodb-odbc.inc.php
lib/adodb/drivers/adodb-odbc_mssql.inc.php
lib/adodb/drivers/adodb-odbc_oracle.inc.php
lib/adodb/drivers/adodb-odbtp.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-odbtp_unicode.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-oracle.inc.php
lib/adodb/drivers/adodb-pdo.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-postgres.inc.php
lib/adodb/drivers/adodb-postgres64.inc.php
lib/adodb/drivers/adodb-postgres7.inc.php
lib/adodb/drivers/adodb-proxy.inc.php
lib/adodb/drivers/adodb-sapdb.inc.php
lib/adodb/drivers/adodb-sqlanywhere.inc.php
lib/adodb/drivers/adodb-sqlite.inc.php
lib/adodb/drivers/adodb-sqlitepo.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-sybase.inc.php
lib/adodb/drivers/adodb-vfp.inc.php
lib/adodb/license.txt
lib/adodb/perf/perf-db2.inc.php
lib/adodb/perf/perf-informix.inc.php
lib/adodb/perf/perf-mssql.inc.php
lib/adodb/perf/perf-mysql.inc.php
lib/adodb/perf/perf-oci8.inc.php
lib/adodb/perf/perf-postgres.inc.php
lib/adodb/pivottable.inc.php
lib/adodb/readme.txt
lib/adodb/rsfilter.inc.php
lib/adodb/server.php
lib/adodb/session/adodb-encrypt-md5.php
lib/adodb/session/adodb-session.php
lib/adodb/tests/benchmark.php
lib/adodb/tests/client.php
lib/adodb/tests/test-datadict.php
lib/adodb/tests/test-php5.php
lib/adodb/tests/test-xmlschema.php
lib/adodb/tests/test.php
lib/adodb/tests/test2.php
lib/adodb/tests/test3.php
lib/adodb/tests/test4.php
lib/adodb/tests/test5.php
lib/adodb/tests/testcache.php
lib/adodb/tests/testdatabases.inc.php
lib/adodb/tests/testgenid.php
lib/adodb/tests/testmssql.php
lib/adodb/tests/testoci8.php
lib/adodb/tests/testoci8cursor.php
lib/adodb/tests/testpaging.php
lib/adodb/tests/testpear.php
lib/adodb/tests/testsessions.php
lib/adodb/toexport.inc.php
lib/adodb/tohtml.inc.php

index ba0697ab83e20add813b76e8a553a56d1a5f8cd4..05f90291fde5caa43f4b44d645d7b4755e37d223 100644 (file)
-<?php
-global $ADODB_INCLUDED_CSV;
-$ADODB_INCLUDED_CSV = 1;
-
-/* 
-  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for CSV serialization. This is used by the csv/proxy driver and is the 
-  CacheExecute() serialization format. 
-  
-  ==== NOTE ====
-  Format documented at http://php.weblogs.com/ADODB_CSV
-  ==============
-*/
-
-       /**
-        * convert a recordset into special format
-        *
-        * @param rs    the recordset
-        *
-        * @return      the CSV formated data
-        */
-       function _rs2serialize(&$rs,$conn=false,$sql='')
-       {
-               $max = ($rs) ? $rs->FieldCount() : 0;
-               
-               if ($sql) $sql = urlencode($sql);
-               // metadata setup
-               
-               if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
-                       if (is_object($conn)) {
-                               $sql .= ','.$conn->Affected_Rows();
-                               $sql .= ','.$conn->Insert_ID();
-                       } else
-                               $sql .= ',,';
-                       
-                       $text = "====-1,0,$sql\n";
-                       return $text;
-               } else {
-                       $tt = ($rs->timeCreated) ? $rs->timeCreated : time();
-                       $line = "====0,$tt,$sql\n";
-               }
-               // column definitions
-               for($i=0; $i < $max; $i++) {
-                       $o = $rs->FetchField($i);
-                       $line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length,$o).":$o->max_length,";
-               }
-               $text = substr($line,0,strlen($line)-1)."\n";
-               
-               
-               // get data
-               if ($rs->databaseType == 'array') {
-                       $text .= serialize($rs->_array);
-               } else {
-                       $rows = array();
-                       while (!$rs->EOF) {     
-                               $rows[] = $rs->fields;
-                               $rs->MoveNext();
-                       } 
-                       $text .= serialize($rows);
-               }
-               $rs->MoveFirst();
-               return $text;
-       }
-
-       
-/**
-* Open CSV file and convert it into Data. 
-*
-* @param url           file/ftp/http url
-* @param err           returns the error message
-* @param timeout       dispose if recordset has been alive for $timeout secs
-*
-* @return              recordset, or false if error occured. If no
-*                      error occurred in sql INSERT/UPDATE/DELETE, 
-*                      empty recordset is returned
-*/
-       function &csv2rs($url,&$err,$timeout=0)
-       {
-               $err = false;
-               $fp = @fopen($url,'r');
-               if (!$fp) {
-                       $err = $url.' file/URL not found';
-                       return false;
-               }
-               flock($fp, LOCK_SH);
-               $arr = array();
-               $ttl = 0;
-               
-               if ($meta = fgetcsv ($fp, 32000, ",")) {
-                       // check if error message
-                       if (substr($meta[0],0,4) === '****') {
-                               $err = trim(substr($meta[0],4,1024));
-                               fclose($fp);
-                               return false;
-                       }
-                       // check for meta data
-                       // $meta[0] is -1 means return an empty recordset
-                       // $meta[1] contains a time 
-       
-                       if (substr($meta[0],0,4) ===  '====') {
-                       
-                               if ($meta[0] == "====-1") {
-                                       if (sizeof($meta) < 5) {
-                                               $err = "Corrupt first line for format -1";
-                                               fclose($fp);
-                                               return false;
-                                       }
-                                       fclose($fp);
-                                       
-                                       if ($timeout > 0) {
-                                               $err = " Illegal Timeout $timeout ";
-                                               return false;
-                                       }
-                                       $rs->fields = array();
-                                       $rs->timeCreated = $meta[1];
-                                       $rs = new ADORecordSet($val=true);
-                                       $rs->EOF = true;
-                                       $rs->_numOfFields=0;
-                                       $rs->sql = urldecode($meta[2]);
-                                       $rs->affectedrows = (integer)$meta[3];
-                                       $rs->insertid = $meta[4];       
-                                       return $rs;
-                               }
-                       # Under high volume loads, we want only 1 thread/process to _write_file
-                       # so that we don't have 50 processes queueing to write the same data.
-                       # Would require probabilistic blocking write 
-                       #
-                       # -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io
-                       # -1 sec after timeout give processes 1/4 chance of writing with blocking
-                       # +0 sec after timeout, give processes 100% chance writing with blocking
-                               if (sizeof($meta) > 1) {
-                                       if($timeout >0){ 
-                                               $tdiff = $meta[1]+$timeout - time();
-                                               if ($tdiff <= 2) {
-                                                       switch($tdiff) {
-                                                       case 2: 
-                                                               if ((rand() & 15) == 0) {
-                                                                       fclose($fp);
-                                                                       $err = "Timeout 2";
-                                                                       return false;
-                                                               }
-                                                               break;
-                                                       case 1:
-                                                               if ((rand() & 3) == 0) {
-                                                                       fclose($fp);
-                                                                       $err = "Timeout 1";
-                                                                       return false;
-                                                               }
-                                                               break;
-                                                       default: 
-                                                               fclose($fp);
-                                                               $err = "Timeout 0";
-                                                               return false;
-                                                       } // switch
-                                                       
-                                               } // if check flush cache
-                                       }// (timeout>0)
-                                       $ttl = $meta[1];
-                               }
-                               $meta = false;
-                               $meta = fgetcsv($fp, 16000, ",");
-                               if (!$meta) {
-                                       fclose($fp);
-                                       $err = "Unexpected EOF 1";
-                                       return false;
-                               }
-                       }
-
-                       // Get Column definitions
-                       $flds = array();
-                       foreach($meta as $o) {
-                               $o2 = explode(':',$o);
-                               if (sizeof($o2)!=3) {
-                                       $arr[] = $meta;
-                                       $flds = false;
-                                       break;
-                               }
-                               $fld = new ADOFieldObject();
-                               $fld->name = urldecode($o2[0]);
-                               $fld->type = $o2[1];
-                               $fld->max_length = $o2[2];
-                               $flds[] = $fld;
-                       }
-               } else {
-                       fclose($fp);
-                       $err = "Recordset had unexpected EOF 2";
-                       return false;
-               }
-               
-               // slurp in the data
-               $MAXSIZE = 128000;
-               
-               $text = '';
-               while ($txt = fread($fp,$MAXSIZE)) {
-                       $text .= $txt;
-               }
-                       
-               fclose($fp);
-               $arr = @unserialize($text);
-               //var_dump($arr);
-               if (!is_array($arr)) {
-                       $err = "Recordset had unexpected EOF (in serialized recordset)";
-                       if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
-                       return false;
-               }
-               $rs = new ADORecordSet_array();
-               $rs->timeCreated = $ttl;
-               $rs->InitArrayFields($arr,$flds);
-               return $rs;
-       }
+<?php\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+global $ADODB_INCLUDED_CSV;\r
+$ADODB_INCLUDED_CSV = 1;\r
+\r
+/* \r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for CSV serialization. This is used by the csv/proxy driver and is the \r
+  CacheExecute() serialization format. \r
+  \r
+  ==== NOTE ====\r
+  Format documented at http://php.weblogs.com/ADODB_CSV\r
+  ==============\r
+*/\r
+\r
+       /**\r
+        * convert a recordset into special format\r
+        *\r
+        * @param rs    the recordset\r
+        *\r
+        * @return      the CSV formated data\r
+        */\r
+       function _rs2serialize(&$rs,$conn=false,$sql='')\r
+       {\r
+               $max = ($rs) ? $rs->FieldCount() : 0;\r
+               \r
+               if ($sql) $sql = urlencode($sql);\r
+               // metadata setup\r
+               \r
+               if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete\r
+                       if (is_object($conn)) {\r
+                               $sql .= ','.$conn->Affected_Rows();\r
+                               $sql .= ','.$conn->Insert_ID();\r
+                       } else\r
+                               $sql .= ',,';\r
+                       \r
+                       $text = "====-1,0,$sql\n";\r
+                       return $text;\r
+               }\r
+               $tt = ($rs->timeCreated) ? $rs->timeCreated : time();\r
+               \r
+               ## changed format from ====0 to ====1\r
+               $line = "====1,$tt,$sql\n";\r
+               \r
+               if ($rs->databaseType == 'array') {\r
+                       $rows =& $rs->_array;\r
+               } else {\r
+                       $rows = array();\r
+                       while (!$rs->EOF) {     \r
+                               $rows[] = $rs->fields;\r
+                               $rs->MoveNext();\r
+                       } \r
+               }\r
+               \r
+               for($i=0; $i < $max; $i++) {\r
+                       $o =& $rs->FetchField($i);\r
+                       $flds[] = $o;\r
+               }\r
+               \r
+               $rs =& new ADORecordSet_array();\r
+               $rs->InitArrayFields($rows,$flds);\r
+               return $line.serialize($rs);\r
+       }\r
+\r
+       \r
+/**\r
+* Open CSV file and convert it into Data. \r
+*\r
+* @param url           file/ftp/http url\r
+* @param err           returns the error message\r
+* @param timeout       dispose if recordset has been alive for $timeout secs\r
+*\r
+* @return              recordset, or false if error occured. If no\r
+*                      error occurred in sql INSERT/UPDATE/DELETE, \r
+*                      empty recordset is returned\r
+*/\r
+       function &csv2rs($url,&$err,$timeout=0)\r
+       {\r
+               $err = false;\r
+               $fp = @fopen($url,'rb');\r
+               if (!$fp) {\r
+                       $err = $url.' file/URL not found';\r
+                       return false;\r
+               }\r
+               flock($fp, LOCK_SH);\r
+               $arr = array();\r
+               $ttl = 0;\r
+               \r
+               if ($meta = fgetcsv($fp, 32000, ",")) {\r
+                       // check if error message\r
+                       if (strncmp($meta[0],'****',4) === 0) {\r
+                               $err = trim(substr($meta[0],4,1024));\r
+                               fclose($fp);\r
+                               return false;\r
+                       }\r
+                       // check for meta data\r
+                       // $meta[0] is -1 means return an empty recordset\r
+                       // $meta[1] contains a time \r
+       \r
+                       if (strncmp($meta[0], '====',4) === 0) {\r
+                       \r
+                               if ($meta[0] == "====-1") {\r
+                                       if (sizeof($meta) < 5) {\r
+                                               $err = "Corrupt first line for format -1";\r
+                                               fclose($fp);\r
+                                               return false;\r
+                                       }\r
+                                       fclose($fp);\r
+                                       \r
+                                       if ($timeout > 0) {\r
+                                               $err = " Illegal Timeout $timeout ";\r
+                                               return false;\r
+                                       }\r
+                                       $rs->fields = array();\r
+                                       $rs->timeCreated = $meta[1];\r
+                                       $rs =& new ADORecordSet($val=true);\r
+                                       $rs->EOF = true;\r
+                                       $rs->_numOfFields=0;\r
+                                       $rs->sql = urldecode($meta[2]);\r
+                                       $rs->affectedrows = (integer)$meta[3];\r
+                                       $rs->insertid = $meta[4];       \r
+                                       return $rs;\r
+                               } \r
+                       # Under high volume loads, we want only 1 thread/process to _write_file\r
+                       # so that we don't have 50 processes queueing to write the same data.\r
+                       # We use probabilistic timeout, ahead of time.\r
+                       #\r
+                       # -4 sec before timeout, give processes 1/32 chance of timing out\r
+                       # -2 sec before timeout, give processes 1/16 chance of timing out\r
+                       # -1 sec after timeout give processes 1/4 chance of timing out\r
+                       # +0 sec after timeout, give processes 100% chance of timing out\r
+                               if (sizeof($meta) > 1) {\r
+                                       if($timeout >0){ \r
+                                               $tdiff = (integer)( $meta[1]+$timeout - time());\r
+                                               if ($tdiff <= 2) {\r
+                                                       switch($tdiff) {\r
+                                                       case 4:\r
+                                                       case 3:\r
+                                                               if ((rand() & 31) == 0) {\r
+                                                                       fclose($fp);\r
+                                                                       $err = "Timeout 3";\r
+                                                                       return false;\r
+                                                               }\r
+                                                               break;\r
+                                                       case 2: \r
+                                                               if ((rand() & 15) == 0) {\r
+                                                                       fclose($fp);\r
+                                                                       $err = "Timeout 2";\r
+                                                                       return false;\r
+                                                               }\r
+                                                               break;\r
+                                                       case 1:\r
+                                                               if ((rand() & 3) == 0) {\r
+                                                                       fclose($fp);\r
+                                                                       $err = "Timeout 1";\r
+                                                                       return false;\r
+                                                               }\r
+                                                               break;\r
+                                                       default: \r
+                                                               fclose($fp);\r
+                                                               $err = "Timeout 0";\r
+                                                               return false;\r
+                                                       } // switch\r
+                                                       \r
+                                               } // if check flush cache\r
+                                       }// (timeout>0)\r
+                                       $ttl = $meta[1];\r
+                               }\r
+                               //================================================\r
+                               // new cache format - use serialize extensively...\r
+                               if ($meta[0] === '====1') {\r
+                                       // slurp in the data\r
+                                       $MAXSIZE = 128000;\r
+                                       \r
+                                       $text = fread($fp,$MAXSIZE);\r
+                                       if (strlen($text)) {\r
+                                               while ($txt = fread($fp,$MAXSIZE)) {\r
+                                                       $text .= $txt;\r
+                                               }\r
+                                       }\r
+                                       fclose($fp);\r
+                                       $rs = unserialize($text);\r
+                                       if (is_object($rs)) $rs->timeCreated = $ttl;\r
+                                       else {\r
+                                               $err = "Unable to unserialize recordset";\r
+                                               //echo htmlspecialchars($text),' !--END--!<p>';\r
+                                       }\r
+                                       return $rs;\r
+                               }\r
+                               \r
+                               $meta = false;\r
+                               $meta = fgetcsv($fp, 32000, ",");\r
+                               if (!$meta) {\r
+                                       fclose($fp);\r
+                                       $err = "Unexpected EOF 1";\r
+                                       return false;\r
+                               }\r
+                       }\r
+\r
+                       // Get Column definitions\r
+                       $flds = array();\r
+                       foreach($meta as $o) {\r
+                               $o2 = explode(':',$o);\r
+                               if (sizeof($o2)!=3) {\r
+                                       $arr[] = $meta;\r
+                                       $flds = false;\r
+                                       break;\r
+                               }\r
+                               $fld =& new ADOFieldObject();\r
+                               $fld->name = urldecode($o2[0]);\r
+                               $fld->type = $o2[1];\r
+                               $fld->max_length = $o2[2];\r
+                               $flds[] = $fld;\r
+                       }\r
+               } else {\r
+                       fclose($fp);\r
+                       $err = "Recordset had unexpected EOF 2";\r
+                       return false;\r
+               }\r
+               \r
+               // slurp in the data\r
+               $MAXSIZE = 128000;\r
+               \r
+               $text = '';\r
+               while ($txt = fread($fp,$MAXSIZE)) {\r
+                       $text .= $txt;\r
+               }\r
+                       \r
+               fclose($fp);\r
+               @$arr = unserialize($text);\r
+               //var_dump($arr);\r
+               if (!is_array($arr)) {\r
+                       $err = "Recordset had unexpected EOF (in serialized recordset)";\r
+                       if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";\r
+                       return false;\r
+               }\r
+               $rs =& new ADORecordSet_array();\r
+               $rs->timeCreated = $ttl;\r
+               $rs->InitArrayFields($arr,$flds);\r
+               return $rs;\r
+       }\r
 ?>
\ No newline at end of file
index 1959de22f4ebd3bc8170ddfd73010c5c30ce16aa..453eb329be56ccf8f66d1ee0f7fb0504d1e5f3f7 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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
-*/
-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";
-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;
-       
-       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;
-       }
-       
-       return $tokens;
-}
-
-
-class ADODB_DataDict {
-       var $connection;
-       var $debug = false;
-       var $dropTable = 'DROP TABLE %s';
-       var $dropIndex = 'DROP INDEX %s';
-       var $addCol = ' ADD';
-       var $alterCol = ' ALTER COLUMN';
-       var $dropCol = ' DROP COLUMN';
-       var $nameRegex = '\w';
-       var $schema = false;
-       var $serverInfo = array();
-       var $autoIncrement = false;
-       var $dataProvider;
-       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()
-       {
-               return $this->connection->MetaTables();
-       }
-       
-       function &MetaColumns($tab, $upper=true, $schema=false)
-       {
-               return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
-       }
-       
-       function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
-       {
-               return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
-       }
-       
-       function &MetaIndexes($table, $primary = false, $owner = false)
-       {
-               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)
-       {
-               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
-               if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $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 2;
-       }
-       
-       /*
-               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) {
-                       $flds[$key] = $this->NameQuote($fld);
-               }
-               
-               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;
-       }
-       
-       function AlterColumnSQL($tabname, $flds)
-       {
-               $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;
-       }
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               $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)));
-       }
-       
-       /*
-        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);
-               
-               $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)
-       {
-               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 (strlen($fdefault) && !$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);
-                       
-                       $fname = str_pad($fname,16);
-                       $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)
-       {
-               if ( !is_array($cols = &$this->MetaColumns($tablename)) ) {
-                       return $this->CreateTableSQL($tablename, $flds, $tableoptions);
-               }
-               
-               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]) ) {
-                               $sql[] = $alter . $this->alterCol . ' ' . $v;
-                       } else {
-                               $sql[] = $alter . $this->addCol . ' ' . $v;
-                       }
-               }
-               
-               return $sql;
-       }
-} // class
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+       DOCUMENTATION:\r
+       \r
+               See adodb/tests/test-datadict.php for docs and examples.\r
+*/\r
+\r
+/*\r
+       Test script for parser\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+function Lens_ParseTest()\r
+{\r
+$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";\r
+print "<p>$str</p>";\r
+$a= Lens_ParseArgs($str);\r
+print "<pre>";\r
+print_r($a);\r
+print "</pre>";\r
+}\r
+\r
+if (!function_exists('ctype_alnum')) {\r
+       function ctype_alnum($text) {\r
+               return preg_match('/^[a-z0-9]*$/i', $text);\r
+       }\r
+}\r
+\r
+//Lens_ParseTest();\r
+\r
+/**\r
+       Parse arguments, treat "text" (text) and 'text' as quotation marks.\r
+       To escape, use "" or '' or ))\r
+       \r
+       Will read in "abc def" sans quotes, as: abc def\r
+       Same with 'abc def'.\r
+       However if `abc def`, then will read in as `abc def`\r
+       \r
+       @param endstmtchar    Character that indicates end of statement\r
+       @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 \r
+       @returns 2 dimensional array containing parsed tokens.\r
+*/\r
+function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')\r
+{\r
+       $pos = 0;\r
+       $intoken = false;\r
+       $stmtno = 0;\r
+       $endquote = false;\r
+       $tokens = array();\r
+       $tokens[$stmtno] = array();\r
+       $max = strlen($args);\r
+       $quoted = false;\r
+       \r
+       while ($pos < $max) {\r
+               $ch = substr($args,$pos,1);\r
+               switch($ch) {\r
+               case ' ':\r
+               case "\t":\r
+               case "\n":\r
+               case "\r":\r
+                       if (!$quoted) {\r
+                               if ($intoken) {\r
+                                       $intoken = false;\r
+                                       $tokens[$stmtno][] = implode('',$tokarr);\r
+                               }\r
+                               break;\r
+                       }\r
+                       \r
+                       $tokarr[] = $ch;\r
+                       break;\r
+               \r
+               case '`':\r
+                       if ($intoken) $tokarr[] = $ch;\r
+               case '(':\r
+               case ')':       \r
+               case '"':\r
+               case "'":\r
+                       \r
+                       if ($intoken) {\r
+                               if (empty($endquote)) {\r
+                                       $tokens[$stmtno][] = implode('',$tokarr);\r
+                                       if ($ch == '(') $endquote = ')';\r
+                                       else $endquote = $ch;\r
+                                       $quoted = true;\r
+                                       $intoken = true;\r
+                                       $tokarr = array();\r
+                               } else if ($endquote == $ch) {\r
+                                       $ch2 = substr($args,$pos+1,1);\r
+                                       if ($ch2 == $endquote) {\r
+                                               $pos += 1;\r
+                                               $tokarr[] = $ch2;\r
+                                       } else {\r
+                                               $quoted = false;\r
+                                               $intoken = false;\r
+                                               $tokens[$stmtno][] = implode('',$tokarr);\r
+                                               $endquote = '';\r
+                                       }\r
+                               } else\r
+                                       $tokarr[] = $ch;\r
+                                       \r
+                       }else {\r
+                       \r
+                               if ($ch == '(') $endquote = ')';\r
+                               else $endquote = $ch;\r
+                               $quoted = true;\r
+                               $intoken = true;\r
+                               $tokarr = array();\r
+                               if ($ch == '`') $tokarr[] = '`';\r
+                       }\r
+                       break;\r
+                       \r
+               default:\r
+                       \r
+                       if (!$intoken) {\r
+                               if ($ch == $endstmtchar) {\r
+                                       $stmtno += 1;\r
+                                       $tokens[$stmtno] = array();\r
+                                       break;\r
+                               }\r
+                       \r
+                               $intoken = true;\r
+                               $quoted = false;\r
+                               $endquote = false;\r
+                               $tokarr = array();\r
+       \r
+                       }\r
+                       \r
+                       if ($quoted) $tokarr[] = $ch;\r
+                       else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;\r
+                       else {\r
+                               if ($ch == $endstmtchar) {                      \r
+                                       $tokens[$stmtno][] = implode('',$tokarr);\r
+                                       $stmtno += 1;\r
+                                       $tokens[$stmtno] = array();\r
+                                       $intoken = false;\r
+                                       $tokarr = array();\r
+                                       break;\r
+                               }\r
+                               $tokens[$stmtno][] = implode('',$tokarr);\r
+                               $tokens[$stmtno][] = $ch;\r
+                               $intoken = false;\r
+                       }\r
+               }\r
+               $pos += 1;\r
+       }\r
+       \r
+       return $tokens;\r
+}\r
+\r
+\r
+class ADODB_DataDict {\r
+       var $connection;\r
+       var $debug = false;\r
+       var $dropTable = 'DROP TABLE %s';\r
+       var $dropIndex = 'DROP INDEX %s';\r
+       var $addCol = ' ADD';\r
+       var $alterCol = ' ALTER COLUMN';\r
+       var $dropCol = ' DROP COLUMN';\r
+       var $nameRegex = '\w';\r
+       var $schema = false;\r
+       var $serverInfo = array();\r
+       var $autoIncrement = false;\r
+       var $dataProvider;\r
+       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob\r
+                                                       /// in other words, we use a text area for editting.\r
+       \r
+       function GetCommentSQL($table,$col)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function SetCommentSQL($table,$col,$cmt)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function &MetaTables()\r
+       {\r
+               return $this->connection->MetaTables();\r
+       }\r
+       \r
+       function &MetaColumns($tab, $upper=true, $schema=false)\r
+       {\r
+               return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);\r
+       }\r
+       \r
+       function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)\r
+       {\r
+               return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);\r
+       }\r
+       \r
+       function &MetaIndexes($table, $primary = false, $owner = false)\r
+       {\r
+               return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);\r
+       }\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               return ADORecordSet::MetaType($t,$len,$fieldobj);\r
+       }\r
+       \r
+       function NameQuote($name = NULL)\r
+       {\r
+               if (!is_string($name)) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               $name = trim($name);\r
+               \r
+               if ( !is_object($this->connection) ) {\r
+                       return $name;\r
+               }\r
+               \r
+               $quote = $this->connection->nameQuote;\r
+               \r
+               // if name is of the form `name`, quote it\r
+               if ( preg_match('/^`(.+)`$/', $name, $matches) ) {\r
+                       return $quote . $matches[1] . $quote;\r
+               }\r
+               \r
+               // if name contains special characters, quote it\r
+               if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {\r
+                       return $quote . $name . $quote;\r
+               }\r
+               \r
+               return $name;\r
+       }\r
+       \r
+       function TableName($name)\r
+       {\r
+               if ( $this->schema ) {\r
+                       return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);\r
+               }\r
+               return $this->NameQuote($name);\r
+       }\r
+       \r
+       // Executes the sql array returned by GetTableSQL and GetIndexSQL\r
+       function ExecuteSQLArray($sql, $continueOnError = true)\r
+       {\r
+               $rez = 2;\r
+               $conn = &$this->connection;\r
+               $saved = $conn->debug;\r
+               foreach($sql as $line) {\r
+                       \r
+                       if ($this->debug) $conn->debug = true;\r
+                       $ok = $conn->Execute($line);\r
+                       $conn->debug = $saved;\r
+                       if (!$ok) {\r
+                               if ($this->debug) ADOConnection::outp($conn->ErrorMsg());\r
+                               if (!$continueOnError) return 0;\r
+                               $rez = 1;\r
+                       }\r
+               }\r
+               return $rez;\r
+       }\r
+       \r
+       /*\r
+               Returns the actual type given a character code.\r
+               \r
+               C:  varchar\r
+               X:  CLOB (character large object) or largest varchar size if CLOB is not supported\r
+               C2: Multibyte varchar\r
+               X2: Multibyte CLOB\r
+               \r
+               B:  BLOB (binary large object)\r
+               \r
+               D:  Date\r
+               T:  Date-time \r
+               L:  Integer field suitable for storing booleans (0 or 1)\r
+               I:  Integer\r
+               F:  Floating point number\r
+               N:  Numeric or decimal number\r
+       */\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               return $meta;\r
+       }\r
+       \r
+       function CreateDatabase($dbname,$options=false)\r
+       {\r
+               $options = $this->_Options($options);\r
+               $sql = array();\r
+               \r
+               $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);\r
+               if (isset($options[$this->upperName]))\r
+                       $s .= ' '.$options[$this->upperName];\r
+               \r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       /*\r
+        Generates the SQL to create index. Returns an array of sql strings.\r
+       */\r
+       function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)\r
+       {\r
+               if (!is_array($flds)) {\r
+                       $flds = explode(',',$flds);\r
+               }\r
+               \r
+               foreach($flds as $key => $fld) {\r
+                       $flds[$key] = $this->NameQuote($fld);\r
+               }\r
+               \r
+               return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));\r
+       }\r
+       \r
+       function DropIndexSQL ($idxname, $tabname = NULL)\r
+       {\r
+               return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));\r
+       }\r
+       \r
+       function SetSchema($schema)\r
+       {\r
+               $this->schema = $schema;\r
+       }\r
+       \r
+       function AddColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $sql = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';\r
+               foreach($lines as $v) {\r
+                       $sql[] = $alter . $v;\r
+               }\r
+               return $sql;\r
+       }\r
+       \r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $sql = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';\r
+               foreach($lines as $v) {\r
+                       $sql[] = $alter . $v;\r
+               }\r
+               return $sql;\r
+       }\r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               if (!is_array($flds)) $flds = explode(',',$flds);\r
+               $sql = array();\r
+               $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';\r
+               foreach($flds as $v) {\r
+                       $sql[] = $alter . $this->NameQuote($v);\r
+               }\r
+               return $sql;\r
+       }\r
+       \r
+       function DropTableSQL($tabname)\r
+       {\r
+               return array (sprintf($this->dropTable, $this->TableName($tabname)));\r
+       }\r
+       \r
+       /*\r
+        Generate the SQL to create table. Returns an array of sql strings.\r
+       */\r
+       function CreateTableSQL($tabname, $flds, $tableoptions=false)\r
+       {\r
+               if (!$tableoptions) $tableoptions = array();\r
+               \r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               \r
+               $taboptions = $this->_Options($tableoptions);\r
+               $tabname = $this->TableName ($tabname);\r
+               $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);\r
+               \r
+               $tsql = $this->_Triggers($tabname,$taboptions);\r
+               foreach($tsql as $s) $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       function _GenFields($flds)\r
+       {\r
+               if (is_string($flds)) {\r
+                       $padding = '     ';\r
+                       $txt = $flds.$padding;\r
+                       $flds = array();\r
+                       $flds0 = Lens_ParseArgs($txt,',');\r
+                       $hasparam = false;\r
+                       foreach($flds0 as $f0) {\r
+                               $f1 = array();\r
+                               foreach($f0 as $token) {\r
+                                       switch (strtoupper($token)) {\r
+                                       case 'CONSTRAINT':\r
+                                       case 'DEFAULT': \r
+                                               $hasparam = $token;\r
+                                               break;\r
+                                       default:\r
+                                               if ($hasparam) $f1[$hasparam] = $token;\r
+                                               else $f1[] = $token;\r
+                                               $hasparam = false;\r
+                                               break;\r
+                                       }\r
+                               }\r
+                               $flds[] = $f1;\r
+                               \r
+                       }\r
+               }\r
+               $this->autoIncrement = false;\r
+               $lines = array();\r
+               $pkey = array();\r
+               foreach($flds as $fld) {\r
+                       $fld = _array_change_key_case($fld);\r
+               \r
+                       $fname = false;\r
+                       $fdefault = false;\r
+                       $fautoinc = false;\r
+                       $ftype = false;\r
+                       $fsize = false;\r
+                       $fprec = false;\r
+                       $fprimary = false;\r
+                       $fnoquote = false;\r
+                       $fdefts = false;\r
+                       $fdefdate = false;\r
+                       $fconstraint = false;\r
+                       $fnotnull = false;\r
+                       $funsigned = false;\r
+                       \r
+                       //-----------------\r
+                       // Parse attributes\r
+                       foreach($fld as $attr => $v) {\r
+                               if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';\r
+                               else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);\r
+                               \r
+                               switch($attr) {\r
+                               case '0':\r
+                               case 'NAME':    $fname = $v; break;\r
+                               case '1':\r
+                               case 'TYPE':    $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;\r
+                               \r
+                               case 'SIZE':    \r
+                                                               $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');\r
+                                                               if ($dotat === false) $fsize = $v;\r
+                                                               else {\r
+                                                                       $fsize = substr($v,0,$dotat);\r
+                                                                       $fprec = substr($v,$dotat+1);\r
+                                                               }\r
+                                                               break;\r
+                               case 'UNSIGNED': $funsigned = true; break;\r
+                               case 'AUTOINCREMENT':\r
+                               case 'AUTO':    $fautoinc = true; $fnotnull = true; break;\r
+                               case 'KEY':\r
+                               case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;\r
+                               case 'DEF':\r
+                               case 'DEFAULT': $fdefault = $v; break;\r
+                               case 'NOTNULL': $fnotnull = $v; break;\r
+                               case 'NOQUOTE': $fnoquote = $v; break;\r
+                               case 'DEFDATE': $fdefdate = $v; break;\r
+                               case 'DEFTIMESTAMP': $fdefts = $v; break;\r
+                               case 'CONSTRAINT': $fconstraint = $v; break;\r
+                               } //switch\r
+                       } // foreach $fld\r
+                       \r
+                       //--------------------\r
+                       // VALIDATE FIELD INFO\r
+                       if (!strlen($fname)) {\r
+                               if ($this->debug) ADOConnection::outp("Undefined NAME");\r
+                               return false;\r
+                       }\r
+                       \r
+                       $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));\r
+                       $fname = $this->NameQuote($fname);\r
+                       \r
+                       if (!strlen($ftype)) {\r
+                               if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");\r
+                               return false;\r
+                       } else {\r
+                               $ftype = strtoupper($ftype);\r
+                       }\r
+                       \r
+                       $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);\r
+                       \r
+                       if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls\r
+                       \r
+                       if ($fprimary) $pkey[] = $fname;\r
+                       \r
+                       // some databases do not allow blobs to have defaults\r
+                       if ($ty == 'X') $fdefault = false;\r
+                       \r
+                       //--------------------\r
+                       // CONSTRUCT FIELD SQL\r
+                       if ($fdefts) {\r
+                               if (substr($this->connection->databaseType,0,5) == 'mysql') {\r
+                                       $ftype = 'TIMESTAMP';\r
+                               } else {\r
+                                       $fdefault = $this->connection->sysTimeStamp;\r
+                               }\r
+                       } else if ($fdefdate) {\r
+                               if (substr($this->connection->databaseType,0,5) == 'mysql') {\r
+                                       $ftype = 'TIMESTAMP';\r
+                               } else {\r
+                                       $fdefault = $this->connection->sysDate;\r
+                               }\r
+                       } else if (strlen($fdefault) && !$fnoquote)\r
+                               if ($ty == 'C' or $ty == 'X' or \r
+                                       ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))\r
+                                       if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') \r
+                                               $fdefault = trim($fdefault);\r
+                                       else if (strtolower($fdefault) != 'null')\r
+                                               $fdefault = $this->connection->qstr($fdefault);\r
+                       $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);\r
+                       \r
+                       $fname = str_pad($fname,16);\r
+                       $lines[$fid] = $fname.' '.$ftype.$suffix;\r
+                       \r
+                       if ($fautoinc) $this->autoIncrement = true;\r
+               } // foreach $flds\r
+               \r
+               return array($lines,$pkey);\r
+       }\r
+       /*\r
+                GENERATE THE SIZE PART OF THE DATATYPE\r
+                       $ftype is the actual type\r
+                       $ty is the type defined originally in the DDL\r
+       */\r
+       function _GetSize($ftype, $ty, $fsize, $fprec)\r
+       {\r
+               if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {\r
+                       $ftype .= "(".$fsize;\r
+                       if (strlen($fprec)) $ftype .= ",".$fprec;\r
+                       $ftype .= ')';\r
+               }\r
+               return $ftype;\r
+       }\r
+       \r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {       \r
+               $suffix = '';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       $sql[] = sprintf ($this->dropIndex, $idxname);\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
+       \r
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+               \r
+               if ( is_array($flds) )\r
+                       $flds = implode(', ',$flds);\r
+               $s .= '(' . $flds . ')';\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       function _DropAutoIncrement($tabname)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function _TableSQL($tabname,$lines,$pkey,$tableoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {\r
+                       $sql[] = sprintf($this->dropTable,$tabname);\r
+                       if ($this->autoIncrement) {\r
+                               $sInc = $this->_DropAutoIncrement($tabname);\r
+                               if ($sInc) $sql[] = $sInc;\r
+                       }\r
+                       if ( isset ($tableoptions['DROP']) ) {\r
+                               return $sql;\r
+                       }\r
+               }\r
+               $s = "CREATE TABLE $tabname (\n";\r
+               $s .= implode(",\n", $lines);\r
+               if (sizeof($pkey)>0) {\r
+                       $s .= ",\n                 PRIMARY KEY (";\r
+                       $s .= implode(", ",$pkey).")";\r
+               }\r
+               if (isset($tableoptions['CONSTRAINTS'])) \r
+                       $s .= "\n".$tableoptions['CONSTRAINTS'];\r
+               \r
+               if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) \r
+                       $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];\r
+               \r
+               $s .= "\n)";\r
+               if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       /*\r
+               GENERATE TRIGGERS IF NEEDED\r
+               used when table has auto-incrementing field that is emulated using triggers\r
+       */\r
+       function _Triggers($tabname,$taboptions)\r
+       {\r
+               return array();\r
+       }\r
+       \r
+       /*\r
+               Sanitize options, so that array elements with no keys are promoted to keys\r
+       */\r
+       function _Options($opts)\r
+       {\r
+               if (!is_array($opts)) return array();\r
+               $newopts = array();\r
+               foreach($opts as $k => $v) {\r
+                       if (is_numeric($k)) $newopts[strtoupper($v)] = $v;\r
+                       else $newopts[strtoupper($k)] = $v;\r
+               }\r
+               return $newopts;\r
+       }\r
+       \r
+       /*\r
+       "Florian Buzin [ easywe ]" <florian.buzin@easywe.de>\r
+       \r
+       This function changes/adds new fields to your table. You don't\r
+       have to know if the col is new or not. It will check on its own.\r
+       */\r
+       function ChangeTableSQL($tablename, $flds, $tableoptions = false)\r
+       {\r
+               // check table exists\r
+               $cols = &$this->MetaColumns($tablename);\r
+               if ( empty($cols)) { \r
+                       return $this->CreateTableSQL($tablename, $flds, $tableoptions);\r
+               }\r
+               \r
+               // already exists, alter table instead\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $alter = 'ALTER TABLE ' . $this->TableName($tablename);\r
+               $sql = array();\r
+               \r
+               foreach ( $lines as $id => $v ) {\r
+                       if ( isset($cols[$id]) && is_object($cols[$id]) ) {\r
+                               $sql[] = $alter . $this->alterCol . ' ' . $v;\r
+                       } else {\r
+                               $sql[] = $alter . $this->addCol . ' ' . $v;\r
+                       }\r
+               }\r
+               \r
+               return $sql;\r
+       }\r
+} // class\r
 ?>
\ No newline at end of file
index b21f809e53c093601a6fbe5aa26b4ad72f0b058d..c595d3b0ec73f8b8c8e4df2c9fca318ef54fd296 100644 (file)
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 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.
- * 
- * The following code is adapted from the PEAR DB error handling code.
- * Portions (c)1997-2002 The PHP Group.
- */
-
-if (!defined("DB_ERROR")) define("DB_ERROR",-1);
-
-if (!defined("DB_ERROR_SYNTAX")) {
-       define("DB_ERROR_SYNTAX",              -2);
-       define("DB_ERROR_CONSTRAINT",          -3);
-       define("DB_ERROR_NOT_FOUND",           -4);
-       define("DB_ERROR_ALREADY_EXISTS",      -5);
-       define("DB_ERROR_UNSUPPORTED",         -6);
-       define("DB_ERROR_MISMATCH",            -7);
-       define("DB_ERROR_INVALID",             -8);
-       define("DB_ERROR_NOT_CAPABLE",         -9);
-       define("DB_ERROR_TRUNCATED",          -10);
-       define("DB_ERROR_INVALID_NUMBER",     -11);
-       define("DB_ERROR_INVALID_DATE",       -12);
-       define("DB_ERROR_DIVZERO",            -13);
-       define("DB_ERROR_NODBSELECTED",       -14);
-       define("DB_ERROR_CANNOT_CREATE",      -15);
-       define("DB_ERROR_CANNOT_DELETE",      -16);
-       define("DB_ERROR_CANNOT_DROP",        -17);
-       define("DB_ERROR_NOSUCHTABLE",        -18);
-       define("DB_ERROR_NOSUCHFIELD",        -19);
-       define("DB_ERROR_NEED_MORE_DATA",     -20);
-       define("DB_ERROR_NOT_LOCKED",         -21);
-       define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
-       define("DB_ERROR_INVALID_DSN",        -23);
-       define("DB_ERROR_CONNECT_FAILED",     -24);
-       define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
-       define("DB_ERROR_NOSUCHDB",           -25);
-       define("DB_ERROR_ACCESS_VIOLATION",   -26);
-}
-
-function adodb_errormsg($value)
-{
-global $ADODB_LANG,$ADODB_LANG_ARRAY;
-
-       if (empty($ADODB_LANG)) $ADODB_LANG = 'en';
-       if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;
-       else {
-               include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");
-    }
-       return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];
-}
-
-function adodb_error($provider,$dbType,$errno)
-{
-       //var_dump($errno);
-       if (is_numeric($errno) && $errno == 0) return 0;
-       switch($provider) { 
-       case 'mysql': $map = adodb_error_mysql(); break;
-       
-       case 'oracle':
-       case 'oci8': $map = adodb_error_oci8(); break;
-       
-       case 'ibase': $map = adodb_error_ibase(); break;
-       
-       case 'odbc': $map = adodb_error_odbc(); break;
-       
-       case 'mssql':
-       case 'sybase': $map = adodb_error_mssql(); break;
-       
-       case 'informix': $map = adodb_error_ifx(); break;
-       
-       case 'postgres': return adodb_error_pg($errno); break;
-       
-       case 'sqlite': return $map = adodb_error_sqlite(); break;
-       default:
-               return DB_ERROR;
-       }       
-       //print_r($map);
-       //var_dump($errno);
-       if (isset($map[$errno])) return $map[$errno];
-       return DB_ERROR;
-}
-
-//**************************************************************************************
-
-function adodb_error_pg($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
-        );
-       reset($error_regexps);
-    while (list($regexp,$code) = each($error_regexps)) {
-        if (preg_match($regexp, $errormsg)) {
-            return $code;
-        }
-    }
-    // Fall back to DB_ERROR if there was no mapping.
-    return DB_ERROR;
-}
-       
-function adodb_error_odbc()
-{
-static $MAP = array(
-            '01004' => DB_ERROR_TRUNCATED,
-            '07001' => DB_ERROR_MISMATCH,
-            '21S01' => DB_ERROR_MISMATCH,
-            '21S02' => DB_ERROR_MISMATCH,
-            '22003' => DB_ERROR_INVALID_NUMBER,
-            '22008' => DB_ERROR_INVALID_DATE,
-            '22012' => DB_ERROR_DIVZERO,
-            '23000' => DB_ERROR_CONSTRAINT,
-            '24000' => DB_ERROR_INVALID,
-            '34000' => DB_ERROR_INVALID,
-            '37000' => DB_ERROR_SYNTAX,
-            '42000' => DB_ERROR_SYNTAX,
-            'IM001' => DB_ERROR_UNSUPPORTED,
-            'S0000' => DB_ERROR_NOSUCHTABLE,
-            'S0001' => DB_ERROR_NOT_FOUND,
-            'S0002' => DB_ERROR_NOSUCHTABLE,
-            'S0011' => DB_ERROR_ALREADY_EXISTS,
-            'S0012' => DB_ERROR_NOT_FOUND,
-            'S0021' => DB_ERROR_ALREADY_EXISTS,
-            'S0022' => DB_ERROR_NOT_FOUND,
-                       'S1000' => DB_ERROR_NOSUCHTABLE,
-            'S1009' => DB_ERROR_INVALID,
-            'S1090' => DB_ERROR_INVALID,
-            'S1C00' => DB_ERROR_NOT_CAPABLE
-        );
-               return $MAP;
-}
-
-function adodb_error_ibase()
-{
-static $MAP = array(
-            -104 => DB_ERROR_SYNTAX,
-            -150 => DB_ERROR_ACCESS_VIOLATION,
-            -151 => DB_ERROR_ACCESS_VIOLATION,
-            -155 => DB_ERROR_NOSUCHTABLE,
-            -157 => DB_ERROR_NOSUCHFIELD,
-            -158 => DB_ERROR_VALUE_COUNT_ON_ROW,
-            -170 => DB_ERROR_MISMATCH,
-            -171 => DB_ERROR_MISMATCH,
-            -172 => DB_ERROR_INVALID,
-            -204 => DB_ERROR_INVALID,
-            -205 => DB_ERROR_NOSUCHFIELD,
-            -206 => DB_ERROR_NOSUCHFIELD,
-            -208 => DB_ERROR_INVALID,
-            -219 => DB_ERROR_NOSUCHTABLE,
-            -297 => DB_ERROR_CONSTRAINT,
-            -530 => DB_ERROR_CONSTRAINT,
-            -803 => DB_ERROR_CONSTRAINT,
-            -551 => DB_ERROR_ACCESS_VIOLATION,
-            -552 => DB_ERROR_ACCESS_VIOLATION,
-            -922 => DB_ERROR_NOSUCHDB,
-            -923 => DB_ERROR_CONNECT_FAILED,
-            -924 => DB_ERROR_CONNECT_FAILED
-        );
-               
-               return $MAP;
-}
-
-function adodb_error_ifx()
-{
-static $MAP = array(
-            '-201'    => DB_ERROR_SYNTAX,
-            '-206'    => DB_ERROR_NOSUCHTABLE,
-            '-217'    => DB_ERROR_NOSUCHFIELD,
-            '-329'    => DB_ERROR_NODBSELECTED,
-            '-1204'   => DB_ERROR_INVALID_DATE,
-            '-1205'   => DB_ERROR_INVALID_DATE,
-            '-1206'   => DB_ERROR_INVALID_DATE,
-            '-1209'   => DB_ERROR_INVALID_DATE,
-            '-1210'   => DB_ERROR_INVALID_DATE,
-            '-1212'   => DB_ERROR_INVALID_DATE
-       );
-          
-          return $MAP;
-}
-
-function adodb_error_oci8()
-{
-static $MAP = array(
-                        1 => DB_ERROR_ALREADY_EXISTS,
-            900 => DB_ERROR_SYNTAX,
-            904 => DB_ERROR_NOSUCHFIELD,
-            923 => DB_ERROR_SYNTAX,
-            942 => DB_ERROR_NOSUCHTABLE,
-            955 => DB_ERROR_ALREADY_EXISTS,
-            1476 => DB_ERROR_DIVZERO,
-            1722 => DB_ERROR_INVALID_NUMBER,
-            2289 => DB_ERROR_NOSUCHTABLE,
-            2291 => DB_ERROR_CONSTRAINT,
-            2449 => DB_ERROR_CONSTRAINT
-        );
-          
-       return $MAP;
-}
-
-function adodb_error_mssql()
-{
-static $MAP = array(
-                 208 => DB_ERROR_NOSUCHTABLE,
-          2601 => DB_ERROR_ALREADY_EXISTS
-       );
-          
-       return $MAP;
-}
-
-function adodb_error_sqlite()
-{
-static $MAP = array(
-                 1 => DB_ERROR_SYNTAX
-       );
-          
-       return $MAP;
-}
-
-function adodb_error_mysql()
-{
-static $MAP = array(
-           1004 => DB_ERROR_CANNOT_CREATE,
-           1005 => DB_ERROR_CANNOT_CREATE,
-           1006 => DB_ERROR_CANNOT_CREATE,
-           1007 => DB_ERROR_ALREADY_EXISTS,
-           1008 => DB_ERROR_CANNOT_DROP,
-                  1045 => DB_ERROR_ACCESS_VIOLATION,
-           1046 => DB_ERROR_NODBSELECTED,
-                  1049 => DB_ERROR_NOSUCHDB,
-           1050 => DB_ERROR_ALREADY_EXISTS,
-           1051 => DB_ERROR_NOSUCHTABLE,
-           1054 => DB_ERROR_NOSUCHFIELD,
-           1062 => DB_ERROR_ALREADY_EXISTS,
-           1064 => DB_ERROR_SYNTAX,
-           1100 => DB_ERROR_NOT_LOCKED,
-           1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
-           1146 => DB_ERROR_NOSUCHTABLE,
-           1048 => DB_ERROR_CONSTRAINT,
-                   2002 => DB_ERROR_CONNECT_FAILED
-       );
-          
-       return $MAP;
-}
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * The following code is adapted from the PEAR DB error handling code.\r
+ * Portions (c)1997-2002 The PHP Group.\r
+ */\r
+\r
+\r
+if (!defined("DB_ERROR")) define("DB_ERROR",-1);\r
+\r
+if (!defined("DB_ERROR_SYNTAX")) {\r
+       define("DB_ERROR_SYNTAX",              -2);\r
+       define("DB_ERROR_CONSTRAINT",          -3);\r
+       define("DB_ERROR_NOT_FOUND",           -4);\r
+       define("DB_ERROR_ALREADY_EXISTS",      -5);\r
+       define("DB_ERROR_UNSUPPORTED",         -6);\r
+       define("DB_ERROR_MISMATCH",            -7);\r
+       define("DB_ERROR_INVALID",             -8);\r
+       define("DB_ERROR_NOT_CAPABLE",         -9);\r
+       define("DB_ERROR_TRUNCATED",          -10);\r
+       define("DB_ERROR_INVALID_NUMBER",     -11);\r
+       define("DB_ERROR_INVALID_DATE",       -12);\r
+       define("DB_ERROR_DIVZERO",            -13);\r
+       define("DB_ERROR_NODBSELECTED",       -14);\r
+       define("DB_ERROR_CANNOT_CREATE",      -15);\r
+       define("DB_ERROR_CANNOT_DELETE",      -16);\r
+       define("DB_ERROR_CANNOT_DROP",        -17);\r
+       define("DB_ERROR_NOSUCHTABLE",        -18);\r
+       define("DB_ERROR_NOSUCHFIELD",        -19);\r
+       define("DB_ERROR_NEED_MORE_DATA",     -20);\r
+       define("DB_ERROR_NOT_LOCKED",         -21);\r
+       define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);\r
+       define("DB_ERROR_INVALID_DSN",        -23);\r
+       define("DB_ERROR_CONNECT_FAILED",     -24);\r
+       define("DB_ERROR_EXTENSION_NOT_FOUND",-25);\r
+       define("DB_ERROR_NOSUCHDB",           -25);\r
+       define("DB_ERROR_ACCESS_VIOLATION",   -26);\r
+}\r
+\r
+function adodb_errormsg($value)\r
+{\r
+global $ADODB_LANG,$ADODB_LANG_ARRAY;\r
+\r
+       if (empty($ADODB_LANG)) $ADODB_LANG = 'en';\r
+       if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;\r
+       else {\r
+               include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");\r
+    }\r
+       return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];\r
+}\r
+\r
+function adodb_error($provider,$dbType,$errno)\r
+{\r
+       //var_dump($errno);\r
+       if (is_numeric($errno) && $errno == 0) return 0;\r
+       switch($provider) { \r
+       case 'mysql': $map = adodb_error_mysql(); break;\r
+       \r
+       case 'oracle':\r
+       case 'oci8': $map = adodb_error_oci8(); break;\r
+       \r
+       case 'ibase': $map = adodb_error_ibase(); break;\r
+       \r
+       case 'odbc': $map = adodb_error_odbc(); break;\r
+       \r
+       case 'mssql':\r
+       case 'sybase': $map = adodb_error_mssql(); break;\r
+       \r
+       case 'informix': $map = adodb_error_ifx(); break;\r
+       \r
+       case 'postgres': return adodb_error_pg($errno); break;\r
+       \r
+       case 'sqlite': return $map = adodb_error_sqlite(); break;\r
+       default:\r
+               return DB_ERROR;\r
+       }       \r
+       //print_r($map);\r
+       //var_dump($errno);\r
+       if (isset($map[$errno])) return $map[$errno];\r
+       return DB_ERROR;\r
+}\r
+\r
+//**************************************************************************************\r
+\r
+function adodb_error_pg($errormsg)\r
+{\r
+       if (is_numeric($errormsg)) return (integer) $errormsg;\r
+    static $error_regexps = array(\r
+            '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,\r
+            '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => DB_ERROR_ALREADY_EXISTS,\r
+            '/divide by zero$/'                     => DB_ERROR_DIVZERO,\r
+            '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,\r
+            '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,\r
+            '/parser: parse error at or near \"/'   => DB_ERROR_SYNTAX,\r
+            '/referential integrity violation/'     => DB_ERROR_CONSTRAINT,\r
+                       '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/'     \r
+                                => DB_ERROR_ALREADY_EXISTS\r
+        );\r
+       reset($error_regexps);\r
+    while (list($regexp,$code) = each($error_regexps)) {\r
+        if (preg_match($regexp, $errormsg)) {\r
+            return $code;\r
+        }\r
+    }\r
+    // Fall back to DB_ERROR if there was no mapping.\r
+    return DB_ERROR;\r
+}\r
+       \r
+function adodb_error_odbc()\r
+{\r
+static $MAP = array(\r
+            '01004' => DB_ERROR_TRUNCATED,\r
+            '07001' => DB_ERROR_MISMATCH,\r
+            '21S01' => DB_ERROR_MISMATCH,\r
+            '21S02' => DB_ERROR_MISMATCH,\r
+            '22003' => DB_ERROR_INVALID_NUMBER,\r
+            '22008' => DB_ERROR_INVALID_DATE,\r
+            '22012' => DB_ERROR_DIVZERO,\r
+            '23000' => DB_ERROR_CONSTRAINT,\r
+            '24000' => DB_ERROR_INVALID,\r
+            '34000' => DB_ERROR_INVALID,\r
+            '37000' => DB_ERROR_SYNTAX,\r
+            '42000' => DB_ERROR_SYNTAX,\r
+            'IM001' => DB_ERROR_UNSUPPORTED,\r
+            'S0000' => DB_ERROR_NOSUCHTABLE,\r
+            'S0001' => DB_ERROR_NOT_FOUND,\r
+            'S0002' => DB_ERROR_NOSUCHTABLE,\r
+            'S0011' => DB_ERROR_ALREADY_EXISTS,\r
+            'S0012' => DB_ERROR_NOT_FOUND,\r
+            'S0021' => DB_ERROR_ALREADY_EXISTS,\r
+            'S0022' => DB_ERROR_NOT_FOUND,\r
+                       'S1000' => DB_ERROR_NOSUCHTABLE,\r
+            'S1009' => DB_ERROR_INVALID,\r
+            'S1090' => DB_ERROR_INVALID,\r
+            'S1C00' => DB_ERROR_NOT_CAPABLE\r
+        );\r
+               return $MAP;\r
+}\r
+\r
+function adodb_error_ibase()\r
+{\r
+static $MAP = array(\r
+            -104 => DB_ERROR_SYNTAX,\r
+            -150 => DB_ERROR_ACCESS_VIOLATION,\r
+            -151 => DB_ERROR_ACCESS_VIOLATION,\r
+            -155 => DB_ERROR_NOSUCHTABLE,\r
+            -157 => DB_ERROR_NOSUCHFIELD,\r
+            -158 => DB_ERROR_VALUE_COUNT_ON_ROW,\r
+            -170 => DB_ERROR_MISMATCH,\r
+            -171 => DB_ERROR_MISMATCH,\r
+            -172 => DB_ERROR_INVALID,\r
+            -204 => DB_ERROR_INVALID,\r
+            -205 => DB_ERROR_NOSUCHFIELD,\r
+            -206 => DB_ERROR_NOSUCHFIELD,\r
+            -208 => DB_ERROR_INVALID,\r
+            -219 => DB_ERROR_NOSUCHTABLE,\r
+            -297 => DB_ERROR_CONSTRAINT,\r
+            -530 => DB_ERROR_CONSTRAINT,\r
+            -803 => DB_ERROR_CONSTRAINT,\r
+            -551 => DB_ERROR_ACCESS_VIOLATION,\r
+            -552 => DB_ERROR_ACCESS_VIOLATION,\r
+            -922 => DB_ERROR_NOSUCHDB,\r
+            -923 => DB_ERROR_CONNECT_FAILED,\r
+            -924 => DB_ERROR_CONNECT_FAILED\r
+        );\r
+               \r
+               return $MAP;\r
+}\r
+\r
+function adodb_error_ifx()\r
+{\r
+static $MAP = array(\r
+            '-201'    => DB_ERROR_SYNTAX,\r
+            '-206'    => DB_ERROR_NOSUCHTABLE,\r
+            '-217'    => DB_ERROR_NOSUCHFIELD,\r
+            '-329'    => DB_ERROR_NODBSELECTED,\r
+            '-1204'   => DB_ERROR_INVALID_DATE,\r
+            '-1205'   => DB_ERROR_INVALID_DATE,\r
+            '-1206'   => DB_ERROR_INVALID_DATE,\r
+            '-1209'   => DB_ERROR_INVALID_DATE,\r
+            '-1210'   => DB_ERROR_INVALID_DATE,\r
+            '-1212'   => DB_ERROR_INVALID_DATE\r
+       );\r
+          \r
+          return $MAP;\r
+}\r
+\r
+function adodb_error_oci8()\r
+{\r
+static $MAP = array(\r
+                        1 => DB_ERROR_ALREADY_EXISTS,\r
+            900 => DB_ERROR_SYNTAX,\r
+            904 => DB_ERROR_NOSUCHFIELD,\r
+            923 => DB_ERROR_SYNTAX,\r
+            942 => DB_ERROR_NOSUCHTABLE,\r
+            955 => DB_ERROR_ALREADY_EXISTS,\r
+            1476 => DB_ERROR_DIVZERO,\r
+            1722 => DB_ERROR_INVALID_NUMBER,\r
+            2289 => DB_ERROR_NOSUCHTABLE,\r
+            2291 => DB_ERROR_CONSTRAINT,\r
+            2449 => DB_ERROR_CONSTRAINT\r
+        );\r
+          \r
+       return $MAP;\r
+}\r
+\r
+function adodb_error_mssql()\r
+{\r
+static $MAP = array(\r
+                 208 => DB_ERROR_NOSUCHTABLE,\r
+          2601 => DB_ERROR_ALREADY_EXISTS\r
+       );\r
+          \r
+       return $MAP;\r
+}\r
+\r
+function adodb_error_sqlite()\r
+{\r
+static $MAP = array(\r
+                 1 => DB_ERROR_SYNTAX\r
+       );\r
+          \r
+       return $MAP;\r
+}\r
+\r
+function adodb_error_mysql()\r
+{\r
+static $MAP = array(\r
+           1004 => DB_ERROR_CANNOT_CREATE,\r
+           1005 => DB_ERROR_CANNOT_CREATE,\r
+           1006 => DB_ERROR_CANNOT_CREATE,\r
+           1007 => DB_ERROR_ALREADY_EXISTS,\r
+           1008 => DB_ERROR_CANNOT_DROP,\r
+                  1045 => DB_ERROR_ACCESS_VIOLATION,\r
+           1046 => DB_ERROR_NODBSELECTED,\r
+                  1049 => DB_ERROR_NOSUCHDB,\r
+           1050 => DB_ERROR_ALREADY_EXISTS,\r
+           1051 => DB_ERROR_NOSUCHTABLE,\r
+           1054 => DB_ERROR_NOSUCHFIELD,\r
+           1062 => DB_ERROR_ALREADY_EXISTS,\r
+           1064 => DB_ERROR_SYNTAX,\r
+           1100 => DB_ERROR_NOT_LOCKED,\r
+           1136 => DB_ERROR_VALUE_COUNT_ON_ROW,\r
+           1146 => DB_ERROR_NOSUCHTABLE,\r
+           1048 => DB_ERROR_CONSTRAINT,\r
+                   2002 => DB_ERROR_CONNECT_FAILED\r
+       );\r
+          \r
+       return $MAP;\r
+}\r
 ?>
\ No newline at end of file
index 94b4d4742a4b49699c4ea3fbb7fa8d405e658cda..56ea3d05cf3678d77778e2919c3f3182479233e5 100644 (file)
@@ -1,78 +1,79 @@
-<?php
-/**
- * @version V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license.
- * Whenever there is any discrepancy between the two licenses,
- * the BSD license will take precedence.
- *
- * Set tabs to 4 for best viewing.
- *
- * Latest version is available at http://php.weblogs.com
- *
-*/
-
-// added Claudio Bustos  clbustos#entelchile.net
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
-
-define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
-
-/**
-* Default Error Handler. This will be called with the following params
-*
-* @param $dbms         the RDBMS you are connecting to
-* @param $fn           the name of the calling function (in uppercase)
-* @param $errno                the native error number from the database
-* @param $errmsg       the native error msg from the database
-* @param $p1           $fn specific parameter - see below
-* @param $p2           $fn specific parameter - see below
-* @param $thisConn     $current connection object - can be false if no connection object created
-*/
-function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
-{
-       if (error_reporting() == 0) return; // obey @ protocol
-       switch($fn) {
-       case 'EXECUTE':
-               $sql = $p1;
-               $inputparams = $p2;
-
-               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
-               break;
-
-       case 'PCONNECT':
-       case 'CONNECT':
-               $host = $p1;
-               $database = $p2;
-
-               $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
-               break;
-       default:
-               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
-               break;
-       }
-       /*
-       * Log connection error somewhere
-       *       0 message is sent to PHP's system logger, using the Operating System's system
-       *               logging mechanism or a file, depending on what the error_log configuration
-       *               directive is set to.
-       *       1 message is sent by email to the address in the destination parameter.
-       *               This is the only message type where the fourth parameter, extra_headers is used.
-       *               This message type uses the same internal function as mail() does.
-       *       2 message is sent through the PHP debugging connection.
-       *               This option is only available if remote debugging has been enabled.
-       *               In this case, the destination parameter specifies the host name or IP address
-       *               and optionally, port number, of the socket receiving the debug information.
-       *       3 message is appended to the file destination
-       */
-       if (defined('ADODB_ERROR_LOG_TYPE')) {
-               $t = date('Y-m-d H:i:s');
-               if (defined('ADODB_ERROR_LOG_DEST'))
-                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
-               else
-                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
-       }
-
-
-       //print "<p>$s</p>";
-       trigger_error($s,ADODB_ERROR_HANDLER_TYPE); 
-}
-?>
+<?php\r
+/**\r
+ * @version V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license.\r
+ * Whenever there is any discrepancy between the two licenses,\r
+ * the BSD license will take precedence.\r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ *\r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+*/\r
+\r
+\r
+// added Claudio Bustos  clbustos#entelchile.net\r
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); \r
+\r
+define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');\r
+\r
+/**\r
+* Default Error Handler. This will be called with the following params\r
+*\r
+* @param $dbms         the RDBMS you are connecting to\r
+* @param $fn           the name of the calling function (in uppercase)\r
+* @param $errno                the native error number from the database\r
+* @param $errmsg       the native error msg from the database\r
+* @param $p1           $fn specific parameter - see below\r
+* @param $p2           $fn specific parameter - see below\r
+* @param $thisConn     $current connection object - can be false if no connection object created\r
+*/\r
+function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)\r
+{\r
+       if (error_reporting() == 0) return; // obey @ protocol\r
+       switch($fn) {\r
+       case 'EXECUTE':\r
+               $sql = $p1;\r
+               $inputparams = $p2;\r
+\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";\r
+               break;\r
+\r
+       case 'PCONNECT':\r
+       case 'CONNECT':\r
+               $host = $p1;\r
+               $database = $p2;\r
+\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";\r
+               break;\r
+       default:\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";\r
+               break;\r
+       }\r
+       /*\r
+       * Log connection error somewhere\r
+       *       0 message is sent to PHP's system logger, using the Operating System's system\r
+       *               logging mechanism or a file, depending on what the error_log configuration\r
+       *               directive is set to.\r
+       *       1 message is sent by email to the address in the destination parameter.\r
+       *               This is the only message type where the fourth parameter, extra_headers is used.\r
+       *               This message type uses the same internal function as mail() does.\r
+       *       2 message is sent through the PHP debugging connection.\r
+       *               This option is only available if remote debugging has been enabled.\r
+       *               In this case, the destination parameter specifies the host name or IP address\r
+       *               and optionally, port number, of the socket receiving the debug information.\r
+       *       3 message is appended to the file destination\r
+       */\r
+       if (defined('ADODB_ERROR_LOG_TYPE')) {\r
+               $t = date('Y-m-d H:i:s');\r
+               if (defined('ADODB_ERROR_LOG_DEST'))\r
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);\r
+               else\r
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);\r
+       }\r
+\r
+\r
+       //print "<p>$s</p>";\r
+       trigger_error($s,ADODB_ERROR_HANDLER_TYPE); \r
+}\r
+?>\r
index ddc13aebb393a5d074e4cbaf4d0bd09d275ef9b4..ef2e7daa46dcd9761e0a72e2e87e6fffa1703a33 100644 (file)
@@ -1,88 +1,88 @@
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
- *
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com
- * 
-*/
-include_once('PEAR.php');
-
-define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
-
-/*
-* Enabled the following if you want to terminate scripts when an error occurs
-*/
-//PEAR::setErrorHandling (PEAR_ERROR_DIE);
-
-/*
-* Name of the PEAR_Error derived class to call.
-*/
-if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');
-
-/*
-* Store the last PEAR_Error object here
-*/
-global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
-
-  /**
-* Error Handler with PEAR support. This will be called with the following params
-*
-* @param $dbms         the RDBMS you are connecting to
-* @param $fn           the name of the calling function (in uppercase)
-* @param $errno                the native error number from the database 
-* @param $errmsg       the native error msg from the database
-* @param $p1           $fn specific parameter - see below
-* @param $P2           $fn specific parameter - see below
-       */
-function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
-{
-global $ADODB_Last_PEAR_Error;
-       
-       if (error_reporting() == 0) return; // obey @ protocol
-       switch($fn) {
-       case 'EXECUTE':
-               $sql = $p1;
-               $inputparams = $p2;
-               
-               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
-               break;
-               
-       case 'PCONNECT':
-       case 'CONNECT':
-               $host = $p1;
-               $database = $p2;
-               
-               $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
-               break;
-               
-       default:
-               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
-               break;
-       }
-       
-       $class = ADODB_PEAR_ERROR_CLASS;
-       $ADODB_Last_PEAR_Error = new $class($s, $errno,
-               $GLOBALS['_PEAR_default_error_mode'],
-               $GLOBALS['_PEAR_default_error_options'], 
-               $errmsg);
-               
-       //print "<p>!$s</p>";
-}
-
-/**
-* Returns last PEAR_Error object. This error might be for an error that
-* occured several sql statements ago.
-*/
-function &ADODB_PEAR_Error()
-{
-global $ADODB_Last_PEAR_Error;
-
-       return $ADODB_Last_PEAR_Error;
-}
-               
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ * \r
+*/\r
+include_once('PEAR.php');\r
+\r
+define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');\r
+\r
+/*\r
+* Enabled the following if you want to terminate scripts when an error occurs\r
+*/\r
+//PEAR::setErrorHandling (PEAR_ERROR_DIE);\r
+\r
+/*\r
+* Name of the PEAR_Error derived class to call.\r
+*/\r
+if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');\r
+\r
+/*\r
+* Store the last PEAR_Error object here\r
+*/\r
+global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;\r
+\r
+  /**\r
+* Error Handler with PEAR support. This will be called with the following params\r
+*\r
+* @param $dbms         the RDBMS you are connecting to\r
+* @param $fn           the name of the calling function (in uppercase)\r
+* @param $errno                the native error number from the database \r
+* @param $errmsg       the native error msg from the database\r
+* @param $p1           $fn specific parameter - see below\r
+* @param $P2           $fn specific parameter - see below\r
+       */\r
+function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
+{\r
+global $ADODB_Last_PEAR_Error;\r
+       \r
+       if (error_reporting() == 0) return; // obey @ protocol\r
+       switch($fn) {\r
+       case 'EXECUTE':\r
+               $sql = $p1;\r
+               $inputparams = $p2;\r
+               \r
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";\r
+               break;\r
+               \r
+       case 'PCONNECT':\r
+       case 'CONNECT':\r
+               $host = $p1;\r
+               $database = $p2;\r
+               \r
+               $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";\r
+               break;\r
+               \r
+       default:\r
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";\r
+               break;\r
+       }\r
+       \r
+       $class = ADODB_PEAR_ERROR_CLASS;\r
+       $ADODB_Last_PEAR_Error = new $class($s, $errno,\r
+               $GLOBALS['_PEAR_default_error_mode'],\r
+               $GLOBALS['_PEAR_default_error_options'], \r
+               $errmsg);\r
+               \r
+       //print "<p>!$s</p>";\r
+}\r
+\r
+/**\r
+* Returns last PEAR_Error object. This error might be for an error that\r
+* occured several sql statements ago.\r
+*/\r
+function &ADODB_PEAR_Error()\r
+{\r
+global $ADODB_Last_PEAR_Error;\r
+\r
+       return $ADODB_Last_PEAR_Error;\r
+}\r
+               \r
 ?>
\ No newline at end of file
index e4378e3283a18293cce893ea25a37f137c8e290f..9199bdafc7e1d540ed7dd59cb504328c5fcd2a7e 100644 (file)
@@ -1,78 +1,79 @@
-<?php
-
-/**
- * @version V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license.
- * Whenever there is any discrepancy between the two licenses,
- * the BSD license will take precedence.
- *
- * Set tabs to 4 for best viewing.
- *
- * Latest version is available at http://php.weblogs.com
- *
- * Exception-handling code using PHP5 exceptions (try-catch-throw).
- */
-       
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
-define('ADODB_ERROR_HANDLER','adodb_throw');
-
-class ADODB_Exception extends Exception {
-var $dbms;
-var $fn;
-var $sql = '';
-var $params = '';
-var $host = '';
-var $database = '';
-       
-       function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
-       {
-               switch($fn) {
-               case 'EXECUTE':
-                       $this->sql = $p1;
-                       $this->params = $p2;
-                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
-                       break;
-       
-               case 'PCONNECT':
-               case 'CONNECT':
-                       $user = $thisConnection->user;
-                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";
-                       break;
-               default:
-                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
-                       break;
-               }
-       
-               $this->dbms = $dbms;
-               $this->host = $thisConnection->host;
-               $this->database = $thisConnection->database;
-               $this->fn = $fn;
-               $this->msg = $errmsg;
-                               
-               if (!is_numeric($errno)) $errno = -1;
-               parent::__construct($s,$errno);
-       }
-}
-
-/**
-* Default Error Handler. This will be called with the following params
-*
-* @param $dbms         the RDBMS you are connecting to
-* @param $fn           the name of the calling function (in uppercase)
-* @param $errno                the native error number from the database
-* @param $errmsg       the native error msg from the database
-* @param $p1           $fn specific parameter - see below
-* @param $P2           $fn specific parameter - see below
-*/
-
-function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
-{
-global $ADODB_EXCEPTION;
-
-       if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
-       else $errfn = 'ADODB_EXCEPTION';
-       throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);
-}
-
-
+<?php\r
+\r
+/**\r
+ * @version V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license.\r
+ * Whenever there is any discrepancy between the two licenses,\r
+ * the BSD license will take precedence.\r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ *\r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+ * Exception-handling code using PHP5 exceptions (try-catch-throw).\r
+ */\r
+\r
+\r
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); \r
+define('ADODB_ERROR_HANDLER','adodb_throw');\r
+\r
+class ADODB_Exception extends Exception {\r
+var $dbms;\r
+var $fn;\r
+var $sql = '';\r
+var $params = '';\r
+var $host = '';\r
+var $database = '';\r
+       \r
+       function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)\r
+       {\r
+               switch($fn) {\r
+               case 'EXECUTE':\r
+                       $this->sql = $p1;\r
+                       $this->params = $p2;\r
+                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";\r
+                       break;\r
+       \r
+               case 'PCONNECT':\r
+               case 'CONNECT':\r
+                       $user = $thisConnection->user;\r
+                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";\r
+                       break;\r
+               default:\r
+                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";\r
+                       break;\r
+               }\r
+       \r
+               $this->dbms = $dbms;\r
+               $this->host = $thisConnection->host;\r
+               $this->database = $thisConnection->database;\r
+               $this->fn = $fn;\r
+               $this->msg = $errmsg;\r
+                               \r
+               if (!is_numeric($errno)) $errno = -1;\r
+               parent::__construct($s,$errno);\r
+       }\r
+}\r
+\r
+/**\r
+* Default Error Handler. This will be called with the following params\r
+*\r
+* @param $dbms         the RDBMS you are connecting to\r
+* @param $fn           the name of the calling function (in uppercase)\r
+* @param $errno                the native error number from the database\r
+* @param $errmsg       the native error msg from the database\r
+* @param $p1           $fn specific parameter - see below\r
+* @param $P2           $fn specific parameter - see below\r
+*/\r
+\r
+function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)\r
+{\r
+global $ADODB_EXCEPTION;\r
+\r
+       if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;\r
+       else $errfn = 'ADODB_EXCEPTION';\r
+       throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);\r
+}\r
+\r
+\r
 ?>
\ No newline at end of file
index f1d794f9a44d581ce4f3c35ce8690ead55ff3dd3..4ae6c83b20c61741e36b2a00cb310fac7ff3b4c5 100644 (file)
@@ -1,56 +1,84 @@
-<?php
-
-/*
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-  
-  PHP5 Iterator Class:
-  
-               $rs = $db->Execute("select * from adoxyz");
-               foreach($rs as $k => $v) {
-                       echo $k; print_r($v); echo "<br>";
-               }
- */
-class ADODB_Iterator implements Iterator {
-
-    private $rs;
-
-    function __construct($rs) 
-       {
-        $this->rs = $rs;
-    }
-    function rewind() 
-       {
-        $this->rs->MoveFirst();
-    }
-    function hasMore() 
-       {
-        return !$this->rs->EOF;
-    }
-    function key() 
-       {
-        return $this->rs->_currentRow;
-    }
-    function current() 
-       {
-        return $this->rs->fields;
-    }
-    function next() 
-       {
-        $this->rs->MoveNext();
-    }
-}
-
-
-class ADODB_BASE_RS implements IteratorAggregate {
-    function getIterator() {
-        return new ADODB_Iterator($this);
-    }
-} 
-
+<?php\r
+\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  \r
+  Set tabs to 4.\r
+  \r
+  Declares the ADODB Base Class for PHP5 "ADODB_BASE_RS", and supports iteration with \r
+  the ADODB_Iterator class.\r
+  \r
+               $rs = $db->Execute("select * from adoxyz");\r
+               foreach($rs as $k => $v) {\r
+                       echo $k; print_r($v); echo "<br>";\r
+               }\r
+               \r
+               \r
+       Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2\r
+ */\r
\r
+\r
+ class ADODB_Iterator implements Iterator {\r
+\r
+    private $rs;\r
+\r
+    function __construct($rs) \r
+       {\r
+        $this->rs = $rs;\r
+    }\r
+    function rewind() \r
+       {\r
+        $this->rs->MoveFirst();\r
+    }\r
+\r
+       function valid() \r
+       {\r
+        return !$this->rs->EOF;\r
+    }\r
+       \r
+    function key() \r
+       {\r
+        return $this->rs->_currentRow;\r
+    }\r
+       \r
+    function current() \r
+       {\r
+        return $this->rs->fields;\r
+    }\r
+       \r
+    function next() \r
+       {\r
+        $this->rs->MoveNext();\r
+    }\r
+       \r
+       function __call($func, $params)\r
+       {\r
+               return call_user_func_array(array($this->rs, $func), $params);\r
+       }\r
+       \r
+       function __toString()\r
+       {\r
+               if (isset($rs->databaseType)) $s = ' for '.$rs->databaseType;\r
+               else $s = '';\r
+               \r
+               return 'ADODB Iterator'.$s;\r
+       }\r
+       \r
+       function hasMore()\r
+       {\r
+               return !$this->rs->EOF;\r
+       }\r
+\r
+}\r
+\r
+\r
+class ADODB_BASE_RS implements IteratorAggregate {\r
+    function getIterator() {\r
+        return new ADODB_Iterator($this);\r
+    }\r
+} \r
+\r
 ?>
\ No newline at end of file
index 271de9d1fd21984be01459230e9c21e80a584ab8..2d0a5d6d7d4672b9a730310a007738c4cc37d251 100644 (file)
-<?php
-
-global $ADODB_INCLUDED_LIB;
-$ADODB_INCLUDED_LIB = 1;
-
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Less commonly used functions are placed here to reduce size of adodb.inc.php. 
-*/ 
-
-
-// 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)
-{
-       if (is_array($an_array)) {
-               foreach($an_array as $key=>$value)
-               $new_array[strtoupper($key)] = $value;
-
-               return $new_array;
-   }
-
-       return $an_array;
-}
-
-function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
-{
-               if (count($fieldArray) == 0) return 0;
-               $first = true;
-               $uSet = '';
-               
-               if (!is_array($keyCol)) {
-                       $keyCol = array($keyCol);
-               }
-               foreach($fieldArray as $k => $v) {
-                       if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {
-                               $v = $zthis->qstr($v);
-                               $fieldArray[$k] = $v;
-                       }
-                       if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
-                       
-                       if ($first) {
-                               $first = false;                 
-                               $uSet = "$k=$v";
-                       } else
-                               $uSet .= ",$k=$v";
-               }
-                
-               $where = false;
-               foreach ($keyCol as $v) {
-                       if ($where) $where .= " and $v=$fieldArray[$v]";
-                       else $where = "$v=$fieldArray[$v]";
-               }
-               
-               if ($uSet && $where) {
-                       $update = "UPDATE $table SET $uSet WHERE $where";
-                       
-                       $rs = $zthis->Execute($update);
-                       if ($rs) {
-                               if ($zthis->poorAffectedRows) {
-                               /*
-                                The Select count(*) wipes out any errors that the update would have returned. 
-                               http://phplens.com/lens/lensforum/msgs.php?id=5696
-                               */
-                                       if ($zthis->ErrorNo()<>0) return 0;
-                                       
-                               # affected_rows == 0 if update field values identical to old values
-                               # for mysql - which is silly. 
-                       
-                                       $cnt = $zthis->GetOne("select count(*) from $table where $where");
-                                       if ($cnt > 0) return 1; // record already exists
-                               } else
-                                        if (($zthis->Affected_Rows()>0)) return 1;
-                       }
-               }
-       //      print "<p>Error=".$this->ErrorNo().'<p>';
-               $first = true;
-               foreach($fieldArray as $k => $v) {
-                       if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
-                       
-                       if ($first) {
-                               $first = false;                 
-                               $iCols = "$k";
-                               $iVals = "$v";
-                       } else {
-                               $iCols .= ",$k";
-                               $iVals .= ",$v";
-                       }                               
-               }
-               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; 
-               $rs = $zthis->Execute($insert);
-               return ($rs) ? 2 : 0;
-}
-
-// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
-function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
-                       $size=0, $selectAttr='',$compareFields0=true)
-{
-       $hasvalue = false;
-
-       if ($multiple or is_array($defstr)) {
-               if ($size==0) $size=5;
-               $attr = " multiple size=$size";
-               if (!strpos($name,'[]')) $name .= '[]';
-       } else if ($size) $attr = " size=$size";
-       else $attr ='';
-
-       $s = "<select name=\"$name\"$attr $selectAttr>";
-       if ($blank1stItem) 
-               if (is_string($blank1stItem))  {
-                       $barr = explode(':',$blank1stItem);
-                       if (sizeof($barr) == 1) $barr[] = '';
-                       $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
-               } else $s .= "\n<option></option>";
-
-       if ($zthis->FieldCount() > 1) $hasvalue=true;
-       else $compareFields0 = true;
-       
-       $value = '';
-       while(!$zthis->EOF) {
-               $zval = trim(reset($zthis->fields));
-               if (sizeof($zthis->fields) > 1) {
-                       if (isset($zthis->fields[1]))
-                               $zval2 = trim($zthis->fields[1]);
-                       else
-                               $zval2 = trim(next($zthis->fields));
-               }
-               $selected = ($compareFields0) ? $zval : $zval2;
-               
-               if ($blank1stItem && $zval=="") {
-                       $zthis->MoveNext();
-                       continue;
-               }
-               if ($hasvalue) 
-                       $value = ' value="'.htmlspecialchars($zval2).'"';
-               
-               if (is_array($defstr))  {
-                       
-                       if (in_array($selected,$defstr)) 
-                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
-                       else 
-                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
-               }
-               else {
-                       if (strcasecmp($selected,$defstr)==0) 
-                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
-                       else
-                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
-               }
-               $zthis->MoveNext();
-       } // while
-       
-       return $s ."\n</select>\n";
-}
-
-/*
-       Count the number of records this sql statement will return by using
-       query rewriting techniques...
-       
-       Does not work with UNIONs.
-*/
-function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) 
-{
-       $qryRecs = 0;
-       
-        if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
-               // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
-               // but this is only supported by oracle and postgresql...
-               if ($zthis->dataProvider == 'oci8') {
-                       
-                       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
-                       $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; 
-                       
-               } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7')  {
-                       
-                       $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 { 
-               // now replace SELECT ... FROM with SELECT COUNT(*) FROM
-               
-               $rewritesql = preg_replace(
-                                       '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
-               
-               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails 
-               // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
-               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); 
-       }
-       
-       if (isset($rewritesql) && $rewritesql != $sql) {
-               if ($secs2cache) {
-                       // we only use half the time of secs2cache because the count can quickly
-                       // become inaccurate if new records are added
-                       $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
-                       
-               } else {
-                       $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
-               }
-               if ($qryRecs !== false) return $qryRecs;
-       }
-       
-       //--------------------------------------------
-       // query rewrite failed - so try slower way...
-       
-       // strip off unneeded ORDER BY
-       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); 
-       $rstest = &$zthis->Execute($rewritesql,$inputarr);
-       if ($rstest) {
-               $qryRecs = $rstest->RecordCount();
-               if ($qryRecs == -1) { 
-               global $ADODB_EXTENSION;
-               // some databases will return -1 on MoveLast() - change to MoveNext()
-                       if ($ADODB_EXTENSION) {
-                               while(!$rstest->EOF) {
-                                       adodb_movenext($rstest);
-                               }
-                       } else {
-                               while(!$rstest->EOF) {
-                                       $rstest->MoveNext();
-                               }
-                       }
-                       $qryRecs = $rstest->_currentRow;
-               }
-               $rstest->Close();
-               if ($qryRecs == -1) return 0;
-       }
-
-       return $qryRecs;
-}
-
-/*
-       Code originally from "Cornel G" <conyg@fx.ro>
-
-       This code will not work with SQL that has UNION in it   
-       
-       Also if you are using CachePageExecute(), there is a strong possibility that
-       data will get out of synch. use CachePageExecute() only with tables that
-       rarely change.
-*/
-function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, 
-                                               $inputarr=false, $secs2cache=0) 
-{
-       $atfirstpage = false;
-       $atlastpage = false;
-       $lastpageno=1;
-
-       // If an invalid nrows is supplied, 
-       // we assume a default value of 10 rows per page
-       if (!isset($nrows) || $nrows <= 0) $nrows = 10;
-
-       $qryRecs = false; //count records for no offset
-       
-       $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
-       $lastpageno = (int) ceil($qryRecs / $nrows);
-       $zthis->_maxRecordCount = $qryRecs;
-       
-       // If page number <= 1, then we are at the first page
-       if (!isset($page) || $page <= 1) {      
-               $page = 1;
-               $atfirstpage = true;
-       }
-
-       // ***** Here we check whether $page is the last page or 
-       // whether we are trying to retrieve 
-       // a page number greater than the last page number.
-       if ($page >= $lastpageno) {
-               $page = $lastpageno;
-               $atlastpage = true;
-       }
-       
-       // 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);
-
-       
-       // Before returning the RecordSet, we set the pagination properties we need
-       if ($rsreturn) {
-               $rsreturn->_maxRecordCount = $qryRecs;
-               $rsreturn->rowsPerPage = $nrows;
-               $rsreturn->AbsolutePage($page);
-               $rsreturn->AtFirstPage($atfirstpage);
-               $rsreturn->AtLastPage($atlastpage);
-               $rsreturn->LastPageNo($lastpageno);
-       }
-       return $rsreturn;
-}
-
-// Iván Oliva version
-function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
-{
-
-       $atfirstpage = false;
-       $atlastpage = false;
-       
-       if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page
-               $page = 1;
-               $atfirstpage = true;
-       }
-       if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page
-       
-       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than 
-       // 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 ($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 ($rstest) $rstest->Close();
-       }
-       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it
-               $page = $pagecounter;
-               if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first
-                       //... page, that is, the recordset has only 1 page.
-       }
-       
-       // 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);
-       
-       // Before returning the RecordSet, we set the pagination properties we need
-       if ($rsreturn) {
-               $rsreturn->rowsPerPage = $nrows;
-               $rsreturn->AbsolutePage($page);
-               $rsreturn->AtFirstPage($atfirstpage);
-               $rsreturn->AtLastPage($atlastpage);
-       }
-       return $rsreturn;
-}
-
-function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
-{
-               if (!$rs) {
-                       printf(ADODB_BAD_RS,'GetUpdateSQL');
-                       return false;
-               }
-       
-               $fieldUpdatedCount = 0;
-               $arrFields = _array_change_key_case($arrFields);
-
-               $hasnumeric = isset($rs->fields[0]);
-               $updateSQL = '';
-               
-               // Loop through all of the fields in the recordset
-               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
-               
-                       // Get the field from the recordset
-                       $field = $rs->FetchField($i);
-
-                       // If the recordset field is one
-                       // of the fields passed in then process.
-                       $upperfname = strtoupper($field->name);
-                       if (adodb_key_exists($upperfname,$arrFields)) {
-
-                               // If the existing field value in the recordset
-                               // is different from the value passed in then
-                               // go ahead and append the field name and new value to
-                               // the update query.
-                               
-                               if ($hasnumeric) $val = $rs->fields[$i];
-                               else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
-                               else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];
-                               else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];
-                               else $val = '';
-                               
-                               if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
-                                       // Set the counter for the number of fields that will be updated.
-                                       $fieldUpdatedCount++;
-
-                                       // Based on the datatype of the field
-                                       // Format the value properly for the database
-                                       $mt = $rs->MetaType($field->type);
-                                       
-                                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> 
-                                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
-                                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
-                                       // is_null requires php 4.0.4
-                                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') 
-                                               $updateSQL .= $field->name . " = null, ";
-                                       else            
-                                       switch($mt) {
-                                               case 'null':
-                                               case "C":
-                                               case "X":
-                                               case 'B':
-                                                       $updateSQL .= $field->name . " = " . $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
-                                                       break;
-                                               case "D":
-                                                       $updateSQL .= $field->name . " = " . $zthis->DBDate($arrFields[$upperfname]) . ", ";
-                                                       break;
-                                               case "T":
-                                                       $updateSQL .= $field->name . " = " . $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
-                                                       break;
-                                               default:
-                                                       $val = $arrFields[$upperfname];
-                                                       /*if (!is_numeric($val)) {
-                                                               if (strncmp($val,'=',1) == 0) $val = substr($val,1);
-                                                               else $val = (float) $val;
-                                                       }*/
-                                                       if (empty($val)) $val = '0';
-
-                                                       $updateSQL .= $field->name . " = " . $val  . ", ";
-                                                       break;
-                                       };
-                               };
-                       };
-               };
-
-               // If there were any modified fields then build the rest of the update query.
-               if ($fieldUpdatedCount > 0 || $forceUpdate) {
-               
-                                       // Get the table name from the existing query.
-                       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
-       
-                       // Get the full where clause excluding the word "WHERE" from
-                       // the existing query.
-                       preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
-                       
-                       $discard = false;
-                       // not a good hack, improvements?
-                       if ($whereClause)
-                               preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
-                       else
-                               $whereClause = array(false,false);
-                               
-                       if ($discard)
-                               $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
-                       
-                       // updateSQL will contain the full update query when all
-                       // processing has completed.
-                       $updateSQL = "UPDATE " . $tableName[1] . " SET ".substr($updateSQL, 0, -2);
-
-                       // If the recordset has a where clause then use that same where clause
-                       // for the update.
-                       if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];
-
-                       return $updateSQL;
-               } else {
-                       return false;
-               };
-}
-
-function adodb_key_exists($key, &$arr)
-{
-       if (!defined('ADODB_FORCE_NULLS')) {
-               // the following is the old behaviour where null or empty fields are ignored
-               return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
-       }
-
-       if (isset($arr[$key])) return true;
-       ## null check below
-       if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
-       return false;
-}
-
-function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
-{
-       $values = '';
-       $fields = '';
-       $arrFields = _array_change_key_case($arrFields);
-       
-       if (!$rs) {
-               printf(ADODB_BAD_RS,'GetInsertSQL');
-               return false;
-       }
-
-       $fieldInsertedCount = 0;
-
-       // Loop through all of the fields in the recordset
-       for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
-
-               // Get the field from the recordset
-               $field = $rs->FetchField($i);
-               // If the recordset field is one
-               // of the fields passed in then process.
-               $upperfname = strtoupper($field->name);
-               if (adodb_key_exists($upperfname,$arrFields)) {
-
-                       // Set the counter for the number of fields that will be inserted.
-                       $fieldInsertedCount++;
-
-                       // Get the name of the fields to insert
-                       $fields .= $field->name . ", ";
-                       
-                       $mt = $rs->MetaType($field->type);
-                       
-                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> 
-                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
-                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
-
-                       // Based on the datatype of the field
-                       // Format the value properly for the database
-                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') 
-                                       $values .= "null, ";
-                       else            
-                       switch($mt) {
-                               case "C":
-                               case "X":
-                               case 'B':
-                                       $values .= $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
-                                       break;
-                               case "D":
-                                       $values .= $zthis->DBDate($arrFields[$upperfname]) . ", ";
-                                       break;
-                               case "T":
-                                       $values .= $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
-                                       break;
-                               default:
-                                       $val = $arrFields[$upperfname];
-                                       /*if (!is_numeric($val)) {
-                                               if (strncmp($val,'=',1) == 0) $val = substr($val,1);
-                                               else $val = (float) $val;
-                                       }*/
-                                       if (empty($val)) $val = '0';
-                                       $values .= $val . ", ";
-                                       break;
-                       };
-               };
-       };
-
-       // If there were any inserted fields then build the rest of the insert query.
-       if ($fieldInsertedCount <= 0)  return false;
-       
-       // Get the table name from the existing query.
-       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
-
-       // Strip off the comma and space on the end of both the fields
-       // and their values.
-       $fields = substr($fields, 0, -2);
-       $values = substr($values, 0, -2);
-
-       // Append the fields and their values to the insert query.
-       $insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";
-
-       return $insertSQL;
-}
-
-
+<?php\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+global $ADODB_INCLUDED_LIB;\r
+$ADODB_INCLUDED_LIB = 1;\r
+\r
+/* \r
+ @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Less commonly used functions are placed here to reduce size of adodb.inc.php. \r
+*/ \r
+\r
+\r
+// Force key to upper. \r
+// See also http://www.php.net/manual/en/function.array-change-key-case.php\r
+function _array_change_key_case($an_array)\r
+{\r
+       if (is_array($an_array)) {\r
+               foreach($an_array as $key=>$value)\r
+                       $new_array[strtoupper($key)] = $value;\r
+\r
+               return $new_array;\r
+   }\r
+\r
+       return $an_array;\r
+}\r
+\r
+function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)\r
+{\r
+               if (count($fieldArray) == 0) return 0;\r
+               $first = true;\r
+               $uSet = '';\r
+               \r
+               if (!is_array($keyCol)) {\r
+                       $keyCol = array($keyCol);\r
+               }\r
+               foreach($fieldArray as $k => $v) {\r
+                       if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {\r
+                               $v = $zthis->qstr($v);\r
+                               $fieldArray[$k] = $v;\r
+                       }\r
+                       if (in_array($k,$keyCol)) continue; // skip UPDATE if is key\r
+                       \r
+                       if ($first) {\r
+                               $first = false;                 \r
+                               $uSet = "$k=$v";\r
+                       } else\r
+                               $uSet .= ",$k=$v";\r
+               }\r
+                \r
+               $where = false;\r
+               foreach ($keyCol as $v) {\r
+                       if ($where) $where .= " and $v=$fieldArray[$v]";\r
+                       else $where = "$v=$fieldArray[$v]";\r
+               }\r
+               \r
+               if ($uSet && $where) {\r
+                       $update = "UPDATE $table SET $uSet WHERE $where";\r
+                       \r
+                       $rs = $zthis->Execute($update);\r
+                       if ($rs) {\r
+                               if ($zthis->poorAffectedRows) {\r
+                               /*\r
+                                The Select count(*) wipes out any errors that the update would have returned. \r
+                               http://phplens.com/lens/lensforum/msgs.php?id=5696\r
+                               */\r
+                                       if ($zthis->ErrorNo()<>0) return 0;\r
+                                       \r
+                               # affected_rows == 0 if update field values identical to old values\r
+                               # for mysql - which is silly. \r
+                       \r
+                                       $cnt = $zthis->GetOne("select count(*) from $table where $where");\r
+                                       if ($cnt > 0) return 1; // record already exists\r
+                               } else\r
+                                        if (($zthis->Affected_Rows()>0)) return 1;\r
+                       }\r
+               }\r
+       //      print "<p>Error=".$this->ErrorNo().'<p>';\r
+               $first = true;\r
+               foreach($fieldArray as $k => $v) {\r
+                       if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col\r
+                       \r
+                       if ($first) {\r
+                               $first = false;                 \r
+                               $iCols = "$k";\r
+                               $iVals = "$v";\r
+                       } else {\r
+                               $iCols .= ",$k";\r
+                               $iVals .= ",$v";\r
+                       }                               \r
+               }\r
+               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; \r
+               $rs = $zthis->Execute($insert);\r
+               return ($rs) ? 2 : 0;\r
+}\r
+\r
+// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM\r
+function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,\r
+                       $size=0, $selectAttr='',$compareFields0=true)\r
+{\r
+       $hasvalue = false;\r
+\r
+       if ($multiple or is_array($defstr)) {\r
+               if ($size==0) $size=5;\r
+               $attr = " multiple size=$size";\r
+               if (!strpos($name,'[]')) $name .= '[]';\r
+       } else if ($size) $attr = " size=$size";\r
+       else $attr ='';\r
+\r
+       $s = "<select name=\"$name\"$attr $selectAttr>";\r
+       if ($blank1stItem) \r
+               if (is_string($blank1stItem))  {\r
+                       $barr = explode(':',$blank1stItem);\r
+                       if (sizeof($barr) == 1) $barr[] = '';\r
+                       $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";\r
+               } else $s .= "\n<option></option>";\r
+\r
+       if ($zthis->FieldCount() > 1) $hasvalue=true;\r
+       else $compareFields0 = true;\r
+       \r
+       $value = '';\r
+       while(!$zthis->EOF) {\r
+               $zval = rtrim(reset($zthis->fields));\r
+               if (sizeof($zthis->fields) > 1) {\r
+                       if (isset($zthis->fields[1]))\r
+                               $zval2 = rtrim($zthis->fields[1]);\r
+                       else\r
+                               $zval2 = rtrim(next($zthis->fields));\r
+               }\r
+               $selected = ($compareFields0) ? $zval : $zval2;\r
+               \r
+               if ($blank1stItem && $zval=="") {\r
+                       $zthis->MoveNext();\r
+                       continue;\r
+               }\r
+               if ($hasvalue) \r
+                       $value = " value='".htmlspecialchars($zval2)."'";\r
+               \r
+               if (is_array($defstr))  {\r
+                       \r
+                       if (in_array($selected,$defstr)) \r
+                               $s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';\r
+                       else \r
+                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';\r
+               }\r
+               else {\r
+                       if (strcasecmp($selected,$defstr)==0) \r
+                               $s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';\r
+                       else\r
+                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';\r
+               }\r
+               $zthis->MoveNext();\r
+       } // while\r
+       \r
+       return $s ."\n</select>\n";\r
+}\r
+\r
+/*\r
+       Count the number of records this sql statement will return by using\r
+       query rewriting techniques...\r
+       \r
+       Does not work with UNIONs.\r
+*/\r
+function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) \r
+{\r
+       $qryRecs = 0;\r
+       \r
+        if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {\r
+               // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias\r
+               // but this is only supported by oracle and postgresql...\r
+               if ($zthis->dataProvider == 'oci8') {\r
+                       \r
+                       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);\r
+                       $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; \r
+                       \r
+               } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7')  {\r
+                       \r
+                       $info = $zthis->ServerInfo();\r
+                       if (substr($info['version'],0,3) >= 7.1) { // good till version 999\r
+                               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);\r
+                               $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";\r
+                       }\r
+               }\r
+       } else { \r
+               // now replace SELECT ... FROM with SELECT COUNT(*) FROM\r
+               \r
+               $rewritesql = preg_replace(\r
+                                       '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);\r
+               \r
+               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails \r
+               // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!\r
+               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); \r
+       }\r
+       \r
+       if (isset($rewritesql) && $rewritesql != $sql) {\r
+               if ($secs2cache) {\r
+                       // we only use half the time of secs2cache because the count can quickly\r
+                       // become inaccurate if new records are added\r
+                       $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);\r
+                       \r
+               } else {\r
+                       $qryRecs = $zthis->GetOne($rewritesql,$inputarr);\r
+               }\r
+               if ($qryRecs !== false) return $qryRecs;\r
+       }\r
+       //--------------------------------------------\r
+       // query rewrite failed - so try slower way...\r
+       \r
+       // strip off unneeded ORDER BY if no UNION\r
+       if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;\r
+       else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); \r
+       \r
+       $rstest = &$zthis->Execute($rewritesql,$inputarr);\r
+       if ($rstest) {\r
+                       $qryRecs = $rstest->RecordCount();\r
+               if ($qryRecs == -1) { \r
+               global $ADODB_EXTENSION;\r
+               // some databases will return -1 on MoveLast() - change to MoveNext()\r
+                       if ($ADODB_EXTENSION) {\r
+                               while(!$rstest->EOF) {\r
+                                       adodb_movenext($rstest);\r
+                               }\r
+                       } else {\r
+                               while(!$rstest->EOF) {\r
+                                       $rstest->MoveNext();\r
+                               }\r
+                       }\r
+                       $qryRecs = $rstest->_currentRow;\r
+               }\r
+               $rstest->Close();\r
+               if ($qryRecs == -1) return 0;\r
+       }\r
+       \r
+       return $qryRecs;\r
+}\r
+\r
+/*\r
+       Code originally from "Cornel G" <conyg@fx.ro>\r
+\r
+       This code will not work with SQL that has UNION in it   \r
+       \r
+       Also if you are using CachePageExecute(), there is a strong possibility that\r
+       data will get out of synch. use CachePageExecute() only with tables that\r
+       rarely change.\r
+*/\r
+function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, \r
+                                               $inputarr=false, $secs2cache=0) \r
+{\r
+       $atfirstpage = false;\r
+       $atlastpage = false;\r
+       $lastpageno=1;\r
+\r
+       // If an invalid nrows is supplied, \r
+       // we assume a default value of 10 rows per page\r
+       if (!isset($nrows) || $nrows <= 0) $nrows = 10;\r
+\r
+       $qryRecs = false; //count records for no offset\r
+       \r
+       $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);\r
+       $lastpageno = (int) ceil($qryRecs / $nrows);\r
+       $zthis->_maxRecordCount = $qryRecs;\r
+       \r
+       // If page number <= 1, then we are at the first page\r
+       if (!isset($page) || $page <= 1) {      \r
+               $page = 1;\r
+               $atfirstpage = true;\r
+       }\r
+\r
+       // ***** Here we check whether $page is the last page or \r
+       // whether we are trying to retrieve \r
+       // a page number greater than the last page number.\r
+       if ($page >= $lastpageno) {\r
+               $page = $lastpageno;\r
+               $atlastpage = true;\r
+       }\r
+       \r
+       // We get the data we want\r
+       $offset = $nrows * ($page-1);\r
+       if ($secs2cache > 0) \r
+               $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);\r
+       else \r
+               $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);\r
+\r
+       \r
+       // Before returning the RecordSet, we set the pagination properties we need\r
+       if ($rsreturn) {\r
+               $rsreturn->_maxRecordCount = $qryRecs;\r
+               $rsreturn->rowsPerPage = $nrows;\r
+               $rsreturn->AbsolutePage($page);\r
+               $rsreturn->AtFirstPage($atfirstpage);\r
+               $rsreturn->AtLastPage($atlastpage);\r
+               $rsreturn->LastPageNo($lastpageno);\r
+       }\r
+       return $rsreturn;\r
+}\r
+\r
+// Iván Oliva version\r
+function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) \r
+{\r
+\r
+       $atfirstpage = false;\r
+       $atlastpage = false;\r
+       \r
+       if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page\r
+               $page = 1;\r
+               $atfirstpage = true;\r
+       }\r
+       if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page\r
+       \r
+       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than \r
+       // the last page number.\r
+       $pagecounter = $page + 1;\r
+       $pagecounteroffset = ($pagecounter * $nrows) - $nrows;\r
+       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);\r
+       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);\r
+       if ($rstest) {\r
+               while ($rstest && $rstest->EOF && $pagecounter>0) {\r
+                       $atlastpage = true;\r
+                       $pagecounter--;\r
+                       $pagecounteroffset = $nrows * ($pagecounter - 1);\r
+                       $rstest->Close();\r
+                       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);\r
+                       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);\r
+               }\r
+               if ($rstest) $rstest->Close();\r
+       }\r
+       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it\r
+               $page = $pagecounter;\r
+               if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first\r
+                       //... page, that is, the recordset has only 1 page.\r
+       }\r
+       \r
+       // We get the data we want\r
+       $offset = $nrows * ($page-1);\r
+       if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);\r
+       else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);\r
+       \r
+       // Before returning the RecordSet, we set the pagination properties we need\r
+       if ($rsreturn) {\r
+               $rsreturn->rowsPerPage = $nrows;\r
+               $rsreturn->AbsolutePage($page);\r
+               $rsreturn->AtFirstPage($atfirstpage);\r
+               $rsreturn->AtLastPage($atlastpage);\r
+       }\r
+       return $rsreturn;\r
+}\r
+\r
+function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$forcenulls=false)\r
+{\r
+               if (!$rs) {\r
+                       printf(ADODB_BAD_RS,'GetUpdateSQL');\r
+                       return false;\r
+               }\r
+       \r
+               $fieldUpdatedCount = 0;\r
+               $arrFields = _array_change_key_case($arrFields);\r
+\r
+               $hasnumeric = isset($rs->fields[0]);\r
+               $setFields = '';\r
+               \r
+               // Loop through all of the fields in the recordset\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
+                       // Get the field from the recordset\r
+                       $field = $rs->FetchField($i);\r
+\r
+                       // If the recordset field is one\r
+                       // of the fields passed in then process.\r
+                       $upperfname = strtoupper($field->name);\r
+                       if (adodb_key_exists($upperfname,$arrFields)) {\r
+\r
+                               // If the existing field value in the recordset\r
+                               // is different from the value passed in then\r
+                               // go ahead and append the field name and new value to\r
+                               // the update query.\r
+                               \r
+                               if ($hasnumeric) $val = $rs->fields[$i];\r
+                               else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];\r
+                               else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];\r
+                               else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];\r
+                               else $val = '';\r
+                               \r
+                       \r
+                               if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {\r
+                                       // Set the counter for the number of fields that will be updated.\r
+                                       $fieldUpdatedCount++;\r
+\r
+                                       // Based on the datatype of the field\r
+                                       // Format the value properly for the database\r
+                               $type = $rs->MetaType($field->type);\r
+                                       \r
+                                       // is_null requires php 4.0.4\r
+                               if (($forcenulls && is_null($arrFields[$upperfname])) || \r
+                                       $arrFields[$upperfname] === 'null') {\r
+                                       $setFields .= $field->name . " = null, ";\r
+                               } else {\r
+                                       if ($type == 'null') {\r
+                                               $type = 'C';\r
+                                       }\r
+                                       \r
+                                       if (strpos($upperfname,' ') !== false)\r
+                                               $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;\r
+                                       else\r
+                                               $fnameq = $upperfname;\r
+                                       //we do this so each driver can customize the sql for\r
+                                       //DB specific column types. \r
+                                       //Oracle needs BLOB types to be handled with a returning clause\r
+                                       //postgres has special needs as well\r
+                                       $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,\r
+                                                                                                         $arrFields, $magicq);\r
+                               }\r
+                       }\r
+               }\r
+       }\r
+\r
+               // If there were any modified fields then build the rest of the update query.\r
+               if ($fieldUpdatedCount > 0 || $forceUpdate) {\r
+                                       // Get the table name from the existing query.\r
+                       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);\r
+       \r
+                       // Get the full where clause excluding the word "WHERE" from\r
+                       // the existing query.\r
+                       preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);\r
+                       \r
+                       $discard = false;\r
+                       // not a good hack, improvements?\r
+                       if ($whereClause)\r
+                               preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);\r
+                       else\r
+                               $whereClause = array(false,false);\r
+                               \r
+                       if ($discard)\r
+                               $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));\r
+                       \r
+               $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2);\r
+               if (strlen($whereClause[1]) > 0) \r
+                       $sql .= ' WHERE '.$whereClause[1];\r
+\r
+               return $sql;\r
+\r
+               } else {\r
+                       return false;\r
+       }\r
+}\r
+\r
+function adodb_key_exists($key, &$arr,$forcenulls=false)\r
+{\r
+       if (!$forcenulls) {\r
+               // the following is the old behaviour where null or empty fields are ignored\r
+               return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);\r
+       }\r
+\r
+       if (isset($arr[$key])) return true;\r
+       ## null check below\r
+       if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);\r
+       return false;\r
+}\r
+\r
+/**\r
+ * There is a special case of this function for the oci8 driver.\r
+ * The proper way to handle an insert w/ a blob in oracle requires\r
+ * a returning clause with bind variables and a descriptor blob.\r
+ * \r
+ * \r
+ */\r
+function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$forcenulls=false)\r
+{\r
+       $tableName = '';\r
+       $values = '';\r
+       $fields = '';\r
+       $recordSet = null;\r
+       $arrFields = _array_change_key_case($arrFields);\r
+       $fieldInsertedCount = 0;\r
+       \r
+       if (is_string($rs)) {\r
+               //ok we have a table name\r
+               //try and get the column info ourself.\r
+               $tableName = $rs;                       \r
+       \r
+               //we need an object for the recordSet\r
+               //because we have to call MetaType.\r
+               //php can't do a $rsclass::MetaType()\r
+               $rsclass = $zthis->rsPrefix.$zthis->databaseType;\r
+               $recordSet =& new $rsclass(-1,$zthis->fetchMode);\r
+               $recordSet->connection = &$zthis;\r
+       \r
+               $columns = $zthis->MetaColumns( $tableName );\r
+       } else if (is_subclass_of($rs, 'adorecordset')) {\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) \r
+                       $columns[] = $rs->FetchField($i);\r
+               $recordSet =& $rs;\r
+       \r
+       } else {\r
+               printf(ADODB_BAD_RS,'GetInsertSQL');\r
+               return false;\r
+       }\r
+\r
+       // Loop through all of the fields in the recordset\r
+       foreach( $columns as $field ) { \r
+               $upperfname = strtoupper($field->name);\r
+               if (adodb_key_exists($upperfname,$arrFields)) {\r
+\r
+                       // Set the counter for the number of fields that will be inserted.\r
+                       $fieldInsertedCount++;\r
+                       \r
+                       if (strpos($upperfname,' ') !== false)\r
+                               $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;\r
+                       else\r
+                               $fnameq = $upperfname;\r
+                       \r
+\r
+                       // Get the name of the fields to insert\r
+                       $fields .= $fnameq . ", ";\r
+               \r
+                       $type = $recordSet->MetaType($field->type);\r
+               \r
+                       if (($forcenulls && is_null($arrFields[$upperfname])) || \r
+                               $arrFields[$upperfname] === 'null') {\r
+                               $values  .= "null, ";\r
+                       } else {\r
+                               //we do this so each driver can customize the sql for\r
+                               //DB specific column types. \r
+                               //Oracle needs BLOB types to be handled with a returning clause\r
+                               //postgres has special needs as well\r
+                               $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,\r
+                                                                                          $arrFields, $magicq);\r
+                       }                               \r
+               }\r
+       }\r
+\r
+\r
+       // If there were any inserted fields then build the rest of the insert query.\r
+       if ($fieldInsertedCount <= 0)  return false;\r
+       \r
+       // Get the table name from the existing query.\r
+       if (!$tableName) {\r
+               preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);\r
+                       $tableName = $tableName[1];\r
+       }               \r
+\r
+       // Strip off the comma and space on the end of both the fields\r
+       // and their values.\r
+       $fields = substr($fields, 0, -2);\r
+       $values = substr($values, 0, -2);\r
+\r
+       // Append the fields and their values to the insert query.\r
+       return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';\r
+}\r
+\r
+\r
+/**\r
+ * This private method is used to help construct\r
+ * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.\r
+ * It handles the string construction of 1 column -> sql string based on\r
+ * the column type.  We want to do 'safe' handling of BLOBs\r
+ * \r
+ * @param string the type of sql we are trying to create\r
+ *                'I' or 'U'. \r
+ * @param string column data type from the db::MetaType() method  \r
+ * @param string the column name\r
+ * @param array the column value\r
+ * \r
+ * @return string\r
+ * \r
+ */\r
+function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) \r
+{\r
+    $sql = '';\r
+    \r
+    // Based on the datatype of the field\r
+    // Format the value properly for the database\r
+    switch($type) {\r
+    case 'B':\r
+        //in order to handle Blobs correctly, we need\r
+        //to do some magic for Oracle\r
+\r
+        //we need to create a new descriptor to handle \r
+        //this properly\r
+        if (!empty($zthis->hasReturningInto)) {\r
+            if ($action == 'I') {\r
+                $sql = 'empty_blob(), ';\r
+            } else {\r
+                $sql = $fnameq. '=empty_blob(), ';\r
+            }\r
+            //add the variable to the returning clause array\r
+            //so the user can build this later in\r
+            //case they want to add more to it\r
+            $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';\r
+        } else if (empty($arrFields[$fname])){\r
+            if ($action == 'I') {\r
+                $sql = 'empty_blob(), ';\r
+            } else {\r
+                $sql = $fnameq. '=empty_blob(), ';\r
+            }            \r
+        } else {\r
+            //this is to maintain compatibility\r
+            //with older adodb versions.\r
+            $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);\r
+        }\r
+        break;\r
+\r
+    case "X":\r
+        //we need to do some more magic here for long variables\r
+        //to handle these correctly in oracle.\r
+\r
+        //create a safe bind var name\r
+        //to avoid conflicts w/ dupes.\r
+       if (!empty($zthis->hasReturningInto)) {\r
+            if ($action == 'I') {\r
+                $sql = ':xx'.$fname.'xx, ';                \r
+            } else {\r
+                $sql = $fnameq.'=:xx'.$fname.'xx, ';\r
+            }\r
+            //add the variable to the returning clause array\r
+            //so the user can build this later in\r
+            //case they want to add more to it\r
+            $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';\r
+        } else {\r
+            //this is to maintain compatibility\r
+            //with older adodb versions.\r
+            $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);\r
+        }            \r
+        break;\r
+        \r
+    default:\r
+        $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq,  $arrFields, $magicq,false);\r
+        break;\r
+    }\r
+    \r
+    return $sql;\r
+}    \r
+       \r
+function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) \r
+{\r
+\r
+       if ($recurse) {\r
+               switch($zthis->dataProvider)  {\r
+               case 'postgres':\r
+                       if ($type == 'L') $type = 'C';\r
+                       break;\r
+               case 'oci8':\r
+                       return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);\r
+                       \r
+               }\r
+       }\r
+       \r
+       $sql = '';\r
+               \r
+       switch($type) {\r
+               case "C":\r
+               case "X":\r
+               case 'B':\r
+                       if ($action == 'I') {\r
+                               $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", ";\r
+                       } else {\r
+                               $sql .= $fnameq . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", ";\r
+                       }\r
+                 break;\r
+\r
+               case "D":\r
+                       if ($action == 'I') {\r
+                               $sql = $zthis->DBDate($arrFields[$fname]) . ", ";\r
+                       } else {\r
+                               $sql .= $fnameq . "=" . $zthis->DBDate($arrFields[$fname]) . ", ";\r
+                       }\r
+                       break;\r
+\r
+               case "T":\r
+                       if ($action == 'I') {\r
+                               $sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", ";\r
+                       } else {\r
+                               $sql .= $fnameq . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", ";\r
+                       }\r
+                       break;\r
+\r
+               default:\r
+                       $val = $arrFields[$fname];\r
+                       if (empty($val)) $val = '0';\r
+\r
+\r
+                       if ($action == 'I') {\r
+                               $sql .= $val . ", ";\r
+                       } else {\r
+                               $sql .= $fnameq . "=" . $val  . ", ";\r
+                       }\r
+                       break;\r
+       }\r
+\r
+       return $sql;\r
+}\r
 ?>
\ No newline at end of file
index 037636d7e251e65f08a5dd01d6c20c1e4a241fb8..7250e728addfab5a6de17f7d310a97ca828976a2 100644 (file)
-<?php
-/*
-       V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-       This class provides recordset pagination with 
-       First/Prev/Next/Last links. 
-       
-       Feel free to modify this class for your own use as
-       it is very basic. To learn how to use it, see the 
-       example in adodb/tests/testpaging.php.
-       
-       "Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks().
-       
-       Please note, this class is entirely unsupported, 
-       and no free support requests except for bug reports
-       will be entertained by the author.
-
-*/
-class ADODB_Pager {
-       var $id;        // unique id for pager (defaults to 'adodb')
-       var $db;        // ADODB connection object
-       var $sql;       // sql used
-       var $rs;        // recordset generated
-       var $curr_page; // current page number before Render() called, calculated in constructor
-       var $rows;              // number of rows per page
-    var $linksPerPage=10; // number of links per page in navigation bar
-    var $showPageLinks; 
-
-       var $gridAttributes = 'width=100% border=1 bgcolor=white';
-       
-       // Localize text strings here
-       var $first = '<code>|&lt;</code>';
-       var $prev = '<code>&lt;&lt;</code>';
-       var $next = '<code>>></code>';
-       var $last = '<code>>|</code>';
-       var $moreLinks = '...';
-       var $startLinks = '...';
-       var $gridHeader = false;
-       var $htmlSpecialChars = true;
-       var $page = 'Page';
-       var $linkSelectedColor = 'red';
-       var $cache = 0;  #secs to cache with CachePageExecute()
-       
-       //----------------------------------------------
-       // constructor
-       //
-       // $db  adodb connection object
-       // $sql sql statement
-       // $id  optional id to identify which pager, 
-       //              if you have multiple on 1 page. 
-       //              $id should be only be [a-z0-9]*
-       //
-       function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
-       {
-       global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
-       
-               $curr_page = $id.'_curr_page';
-               if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
-               
-               $this->sql = $sql;
-               $this->id = $id;
-               $this->db = $db;
-               $this->showPageLinks = $showPageLinks;
-               
-               $next_page = $id.'_next_page';  
-               
-               if (isset($HTTP_GET_VARS[$next_page])) {
-                       $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
-               }
-               if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
-               
-               $this->curr_page = $HTTP_SESSION_VARS[$curr_page];
-               
-       }
-       
-       //---------------------------
-       // Display link to first page
-       function Render_First($anchor=true)
-       {
-       global $PHP_SELF;
-               if ($anchor) {
-       ?>
-               <a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; 
-       <?php
-               } else {
-                       print "$this->first &nbsp; ";
-               }
-       }
-       
-       //--------------------------
-       // Display link to next page
-       function render_next($anchor=true)
-       {
-       global $PHP_SELF;
-       
-               if ($anchor) {
-               ?>
-               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; 
-               <?php
-               } else {
-                       print "$this->next &nbsp; ";
-               }
-       }
-       
-       //------------------
-       // Link to last page
-       // 
-       // for better performance with large recordsets, you can set
-       // $this->db->pageExecuteCountRows = false, which disables
-       // last page counting.
-       function render_last($anchor=true)
-       {
-       global $PHP_SELF;
-       
-               if (!$this->db->pageExecuteCountRows) return;
-               
-               if ($anchor) {
-               ?>
-                       <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; 
-               <?php
-               } else {
-                       print "$this->last &nbsp; ";
-               }
-       }
-       
-       //---------------------------------------------------
-       // original code by "Pablo Costa" <pablo@cbsp.com.br> 
-        function render_pagelinks()
-        {
-        global $PHP_SELF;
-            $pages        = $this->rs->LastPageNo();
-            $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;
-            for($i=1; $i <= $pages; $i+=$linksperpage)
-            {
-                if($this->rs->AbsolutePage() >= $i)
-                {
-                    $start = $i;
-                }
-            }
-                       $numbers = '';
-            $end = $start+$linksperpage-1;
-                       $link = $this->id . "_next_page";
-            if($end > $pages) $end = $pages;
-                       
-                       
-                       if ($this->startLinks && $start > 1) {
-                               $pos = $start - 1;
-                               $numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a>  ";
-            } 
-                       
-                       for($i=$start; $i <= $end; $i++) {
-                if ($this->rs->AbsolutePage() == $i)
-                    $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font>  ";
-                else 
-                     $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a>  ";
-            
-            }
-                       if ($this->moreLinks && $end < $pages) 
-                               $numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a>  ";
-            print $numbers . ' &nbsp; ';
-        }
-       // Link to previous page
-       function render_prev($anchor=true)
-       {
-       global $PHP_SELF;
-               if ($anchor) {
-       ?>
-               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; 
-       <?php 
-               } else {
-                       print "$this->prev &nbsp; ";
-               }
-       }
-       
-       //--------------------------------------------------------
-       // Simply rendering of grid. You should override this for
-       // better control over the format of the grid
-       //
-       // We use output buffering to keep code clean and readable.
-       function RenderGrid()
-       {
-       global $gSQLBlockRows; // used by rs2html to indicate how many rows to display
-               include_once(ADODB_DIR.'/tohtml.inc.php');
-               ob_start();
-               $gSQLBlockRows = $this->rows;
-               rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);
-               $s = ob_get_contents();
-               ob_end_clean();
-               return $s;
-       }
-       
-       //-------------------------------------------------------
-       // Navigation bar
-       //
-       // we use output buffering to keep the code easy to read.
-       function RenderNav()
-       {
-               ob_start();
-               if (!$this->rs->AtFirstPage()) {
-                       $this->Render_First();
-                       $this->Render_Prev();
-               } else {
-                       $this->Render_First(false);
-                       $this->Render_Prev(false);
-               }
-        if ($this->showPageLinks){
-            $this->Render_PageLinks();
-        }
-               if (!$this->rs->AtLastPage()) {
-                       $this->Render_Next();
-                       $this->Render_Last();
-               } else {
-                       $this->Render_Next(false);
-                       $this->Render_Last(false);
-               }
-               $s = ob_get_contents();
-               ob_end_clean();
-               return $s;
-       }
-       
-       //-------------------
-       // This is the footer
-       function RenderPageCount()
-       {
-               if (!$this->db->pageExecuteCountRows) return '';
-               $lastPage = $this->rs->LastPageNo();
-               if ($lastPage == -1) $lastPage = 1; // check for empty rs.
-               return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";
-       }
-       
-       //-----------------------------------
-       // Call this class to draw everything.
-       function Render($rows=10)
-       {
-       global $ADODB_COUNTRECS;
-       
-               $this->rows = $rows;
-               
-               $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);
-               else
-                       $rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
-               $ADODB_COUNTRECS = $savec;
-               
-               $this->rs = &$rs;
-               if (!$rs) {
-                       print "<h3>Query failed: $this->sql</h3>";
-                       return;
-               }
-               
-               if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) 
-                       $header = $this->RenderNav();
-               else
-                       $header = "&nbsp;";
-               
-               $grid = $this->RenderGrid();
-               $footer = $this->RenderPageCount();
-               $rs->Close();
-               $this->rs = false;
-               
-               $this->RenderLayout($header,$grid,$footer);
-       }
-       
-       //------------------------------------------------------
-       // override this to control overall layout and formating
-       function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')
-       {
-               echo "<table ".$attributes."><tr><td>",
-                               $header,
-                       "</td></tr><tr><td>",
-                               $grid,
-                       "</td></tr><tr><td>",
-                               $footer,
-                       "</td></tr></table>";
-       }
-}
-
-
+<?php\r
+\r
+/*\r
+       V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+         Released under both BSD license and Lesser GPL library license. \r
+         Whenever there is any discrepancy between the two licenses, \r
+         the BSD license will take precedence. \r
+         Set tabs to 4 for best viewing.\r
+\r
+       This class provides recordset pagination with \r
+       First/Prev/Next/Last links. \r
+       \r
+       Feel free to modify this class for your own use as\r
+       it is very basic. To learn how to use it, see the \r
+       example in adodb/tests/testpaging.php.\r
+       \r
+       "Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks().\r
+       \r
+       Please note, this class is entirely unsupported, \r
+       and no free support requests except for bug reports\r
+       will be entertained by the author.\r
+\r
+*/\r
+class ADODB_Pager {\r
+       var $id;        // unique id for pager (defaults to 'adodb')\r
+       var $db;        // ADODB connection object\r
+       var $sql;       // sql used\r
+       var $rs;        // recordset generated\r
+       var $curr_page; // current page number before Render() called, calculated in constructor\r
+       var $rows;              // number of rows per page\r
+    var $linksPerPage=10; // number of links per page in navigation bar\r
+    var $showPageLinks; \r
+\r
+       var $gridAttributes = 'width=100% border=1 bgcolor=white';\r
+       \r
+       // Localize text strings here\r
+       var $first = '<code>|&lt;</code>';\r
+       var $prev = '<code>&lt;&lt;</code>';\r
+       var $next = '<code>>></code>';\r
+       var $last = '<code>>|</code>';\r
+       var $moreLinks = '...';\r
+       var $startLinks = '...';\r
+       var $gridHeader = false;\r
+       var $htmlSpecialChars = true;\r
+       var $page = 'Page';\r
+       var $linkSelectedColor = 'red';\r
+       var $cache = 0;  #secs to cache with CachePageExecute()\r
+       \r
+       //----------------------------------------------\r
+       // constructor\r
+       //\r
+       // $db  adodb connection object\r
+       // $sql sql statement\r
+       // $id  optional id to identify which pager, \r
+       //              if you have multiple on 1 page. \r
+       //              $id should be only be [a-z0-9]*\r
+       //\r
+       function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)\r
+       {\r
+       global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;\r
+       \r
+               $curr_page = $id.'_curr_page';\r
+               if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];\r
+               \r
+               $this->sql = $sql;\r
+               $this->id = $id;\r
+               $this->db = $db;\r
+               $this->showPageLinks = $showPageLinks;\r
+               \r
+               $next_page = $id.'_next_page';  \r
+               \r
+               if (isset($HTTP_GET_VARS[$next_page])) {\r
+                       $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];\r
+               }\r
+               if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page\r
+               \r
+               $this->curr_page = $HTTP_SESSION_VARS[$curr_page];\r
+               \r
+       }\r
+       \r
+       //---------------------------\r
+       // Display link to first page\r
+       function Render_First($anchor=true)\r
+       {\r
+       global $PHP_SELF;\r
+               if ($anchor) {\r
+       ?>\r
+               <a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; \r
+       <?php\r
+               } else {\r
+                       print "$this->first &nbsp; ";\r
+               }\r
+       }\r
+       \r
+       //--------------------------\r
+       // Display link to next page\r
+       function render_next($anchor=true)\r
+       {\r
+       global $PHP_SELF;\r
+       \r
+               if ($anchor) {\r
+               ?>\r
+               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; \r
+               <?php\r
+               } else {\r
+                       print "$this->next &nbsp; ";\r
+               }\r
+       }\r
+       \r
+       //------------------\r
+       // Link to last page\r
+       // \r
+       // for better performance with large recordsets, you can set\r
+       // $this->db->pageExecuteCountRows = false, which disables\r
+       // last page counting.\r
+       function render_last($anchor=true)\r
+       {\r
+       global $PHP_SELF;\r
+       \r
+               if (!$this->db->pageExecuteCountRows) return;\r
+               \r
+               if ($anchor) {\r
+               ?>\r
+                       <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; \r
+               <?php\r
+               } else {\r
+                       print "$this->last &nbsp; ";\r
+               }\r
+       }\r
+       \r
+       //---------------------------------------------------\r
+       // original code by "Pablo Costa" <pablo@cbsp.com.br> \r
+        function render_pagelinks()\r
+        {\r
+        global $PHP_SELF;\r
+            $pages        = $this->rs->LastPageNo();\r
+            $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;\r
+            for($i=1; $i <= $pages; $i+=$linksperpage)\r
+            {\r
+                if($this->rs->AbsolutePage() >= $i)\r
+                {\r
+                    $start = $i;\r
+                }\r
+            }\r
+                       $numbers = '';\r
+            $end = $start+$linksperpage-1;\r
+                       $link = $this->id . "_next_page";\r
+            if($end > $pages) $end = $pages;\r
+                       \r
+                       \r
+                       if ($this->startLinks && $start > 1) {\r
+                               $pos = $start - 1;\r
+                               $numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a>  ";\r
+            } \r
+                       \r
+                       for($i=$start; $i <= $end; $i++) {\r
+                if ($this->rs->AbsolutePage() == $i)\r
+                    $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font>  ";\r
+                else \r
+                     $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a>  ";\r
+            \r
+            }\r
+                       if ($this->moreLinks && $end < $pages) \r
+                               $numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a>  ";\r
+            print $numbers . ' &nbsp; ';\r
+        }\r
+       // Link to previous page\r
+       function render_prev($anchor=true)\r
+       {\r
+       global $PHP_SELF;\r
+               if ($anchor) {\r
+       ?>\r
+               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; \r
+       <?php \r
+               } else {\r
+                       print "$this->prev &nbsp; ";\r
+               }\r
+       }\r
+       \r
+       //--------------------------------------------------------\r
+       // Simply rendering of grid. You should override this for\r
+       // better control over the format of the grid\r
+       //\r
+       // We use output buffering to keep code clean and readable.\r
+       function RenderGrid()\r
+       {\r
+       global $gSQLBlockRows; // used by rs2html to indicate how many rows to display\r
+               include_once(ADODB_DIR.'/tohtml.inc.php');\r
+               ob_start();\r
+               $gSQLBlockRows = $this->rows;\r
+               rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);\r
+               $s = ob_get_contents();\r
+               ob_end_clean();\r
+               return $s;\r
+       }\r
+       \r
+       //-------------------------------------------------------\r
+       // Navigation bar\r
+       //\r
+       // we use output buffering to keep the code easy to read.\r
+       function RenderNav()\r
+       {\r
+               ob_start();\r
+               if (!$this->rs->AtFirstPage()) {\r
+                       $this->Render_First();\r
+                       $this->Render_Prev();\r
+               } else {\r
+                       $this->Render_First(false);\r
+                       $this->Render_Prev(false);\r
+               }\r
+        if ($this->showPageLinks){\r
+            $this->Render_PageLinks();\r
+        }\r
+               if (!$this->rs->AtLastPage()) {\r
+                       $this->Render_Next();\r
+                       $this->Render_Last();\r
+               } else {\r
+                       $this->Render_Next(false);\r
+                       $this->Render_Last(false);\r
+               }\r
+               $s = ob_get_contents();\r
+               ob_end_clean();\r
+               return $s;\r
+       }\r
+       \r
+       //-------------------\r
+       // This is the footer\r
+       function RenderPageCount()\r
+       {\r
+               if (!$this->db->pageExecuteCountRows) return '';\r
+               $lastPage = $this->rs->LastPageNo();\r
+               if ($lastPage == -1) $lastPage = 1; // check for empty rs.\r
+               return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";\r
+       }\r
+       \r
+       //-----------------------------------\r
+       // Call this class to draw everything.\r
+       function Render($rows=10)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               $this->rows = $rows;\r
+               \r
+               $savec = $ADODB_COUNTRECS;\r
+               if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;\r
+               if ($this->cache)\r
+                       $rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);\r
+               else\r
+                       $rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);\r
+               $ADODB_COUNTRECS = $savec;\r
+               \r
+               $this->rs = &$rs;\r
+               if (!$rs) {\r
+                       print "<h3>Query failed: $this->sql</h3>";\r
+                       return;\r
+               }\r
+               \r
+               if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) \r
+                       $header = $this->RenderNav();\r
+               else\r
+                       $header = "&nbsp;";\r
+               \r
+               $grid = $this->RenderGrid();\r
+               $footer = $this->RenderPageCount();\r
+               $rs->Close();\r
+               $this->rs = false;\r
+               \r
+               $this->RenderLayout($header,$grid,$footer);\r
+       }\r
+       \r
+       //------------------------------------------------------\r
+       // override this to control overall layout and formating\r
+       function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')\r
+       {\r
+               echo "<table ".$attributes."><tr><td>",\r
+                               $header,\r
+                       "</td></tr><tr><td>",\r
+                               $grid,\r
+                       "</td></tr><tr><td>",\r
+                               $footer,\r
+                       "</td></tr></table>";\r
+       }\r
+}\r
+\r
+\r
 ?>
\ No newline at end of file
index 3894730469cab7d1c0a3755b0d7bc7614e824ac6..69de43966aa2588df4970ca83c17e19a777f5838 100644 (file)
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 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.
- * 
- * PEAR DB Emulation Layer for ADODB.
- *
- * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                                            |
- * and Tomas V.V.Cox <cox@idecnet.com>.        Portions (c)1997-2002 The PHP Group.
- */
-
- /*
- We support:
- DB_Common
- ---------
-       query - returns PEAR_Error on error
-       limitQuery - return PEAR_Error on error
-       prepare - does not return PEAR_Error on error
-       execute - does not return PEAR_Error on error
-       setFetchMode - supports ASSOC and ORDERED
-       errorNative
-       quote
-       nextID
-       disconnect
-       
- DB_Result
- ---------
-       numRows - returns -1 if not supported
-       numCols
-       fetchInto - does not support passing of fetchmode
-       fetchRows - does not support passing of fetchmode
-       free
- */
-define('ADODB_PEAR',dirname(__FILE__));
-include_once "PEAR.php";
-include_once ADODB_PEAR."/adodb-errorpear.inc.php";
-include_once ADODB_PEAR."/adodb.inc.php";
-
-if (!defined('DB_OK')) {
-define("DB_OK",        1);
-define("DB_ERROR",-1);
-/**
- * This is a special constant that tells DB the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-
-define('DB_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-
-define('DB_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-
-define('DB_FETCHMODE_ASSOC', 2);
-
-/* for compatibility */
-
-define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
-define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);
-
-/**
- * these are constants for the tableInfo-function
- * they are bitwised or'ed. so if there are more constants to be defined
- * in the future, adjust DB_TABLEINFO_FULL accordingly
- */
-
-define('DB_TABLEINFO_ORDER', 1);
-define('DB_TABLEINFO_ORDERTABLE', 2);
-define('DB_TABLEINFO_FULL', 3);
-}
-
-/**
- * The main "DB" class is simply a container class with some static
- * methods for creating DB objects as well as some utility functions
- * common to all parts of DB.
- *
- */
-
-class DB
-{
-       /**
-        * Create a new DB object for the specified database type
-        *
-        * @param $type string database type, for example "mysql"
-        *
-        * @return object a newly created DB object, or a DB error code on
-        * error
-        */
-
-       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);
-               return $obj;
-       }
-
-       /**
-        * Create a new DB object and connect to the specified database
-        *
-        * @param $dsn mixed "data source name", see the DB::parseDSN
-        * method for a description of the dsn format.  Can also be
-        * specified as an array of the format returned by DB::parseDSN.
-        *
-        * @param $options mixed if boolean (or scalar), tells whether
-        * this connection should be persistent (for backends that support
-        * this).  This parameter can also be an array of options, see
-        * DB_common::setOption for more information on connection
-        * options.
-        *
-        * @return object a newly created DB connection object, or a DB
-        * error object on error
-        *
-        * @see DB::parseDSN
-        * @see DB::isError
-        */
-       function &connect($dsn, $options = false)
-       {
-               if (is_array($dsn)) {
-                       $dsninfo = $dsn;
-               } else {
-                       $dsninfo = DB::parseDSN($dsn);
-               }
-               switch ($dsninfo["phptype"]) {
-                       case 'pgsql':   $type = 'postgres7'; break;
-                       case 'ifx':             $type = 'informix9'; break;
-                       default:                $type = $dsninfo["phptype"]; break;
-               }
-
-               if (is_array($options) && isset($options["debug"]) &&
-                       $options["debug"] >= 2) {
-                       // expose php errors with sufficient debug level
-                        @include_once("adodb-$type.inc.php");
-               } else {
-                        @include_once("adodb-$type.inc.php");
-               }
-
-               @$obj =& NewADOConnection($type);
-               if (!is_object($obj)) {
-                       $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
-                       return $obj;
-               }
-               if (is_array($options)) {
-                       foreach($options as $k => $v) {
-                               switch(strtolower($k)) {
-                               case 'persistent':      $persist = $v; break;
-                               #ibase
-                               case 'dialect':         $obj->dialect = $v; break;
-                               case 'charset':         $obj->charset = $v; break;
-                               case 'buffers':         $obj->buffers = $v; break;
-                               #ado
-                               case 'charpage':        $obj->charPage = $v; break;
-                               #mysql
-                               case 'clientflags': $obj->clientFlags = $v; break;
-                               }
-                       }
-               } else {
-                       $persist = false;
-               }
-
-               if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
-               else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
-               
-               if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
-               else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
-               
-               if (!$ok) $obj = ADODB_PEAR_Error();
-               return $obj;
-       }
-
-       /**
-        * Return the DB API version
-        *
-        * @return int the DB API version number
-        */
-       function apiVersion()
-       {
-               return 2;
-       }
-
-       /**
-        * Tell whether a result code from a DB method is an error
-        *
-        * @param $value int result code
-        *
-        * @return bool whether $value is an error
-        */
-       function isError($value)
-       {
-               return (is_object($value) &&
-                               (get_class($value) == 'db_error' ||
-                                is_subclass_of($value, 'db_error')));
-       }
-
-
-       /**
-        * Tell whether a result code from a DB method is a warning.
-        * Warnings differ from errors in that they are generated by DB,
-        * and are not fatal.
-        *
-        * @param $value mixed result value
-        *
-        * @return bool whether $value is a warning
-        */
-       function isWarning($value)
-       {
-               return is_object($value) &&
-                       (get_class( $value ) == "db_warning" ||
-                        is_subclass_of($value, "db_warning"));
-       }
-
-       /**
-        * Parse a data source name
-        *
-        * @param $dsn string Data Source Name to be parsed
-        *
-        * @return array an associative array with the following keys:
-        *
-        *  phptype: Database backend used in PHP (mysql, odbc etc.)
-        *  dbsyntax: Database used with regards to SQL syntax etc.
-        *  protocol: Communication protocol to use (tcp, unix etc.)
-        *  hostspec: Host specification (hostname[:port])
-        *  database: Database to use on the DBMS server
-        *  username: User name for login
-        *  password: Password for login
-        *
-        * The format of the supplied DSN is in its fullest form:
-        *
-        *  phptype(dbsyntax)://username:password@protocol+hostspec/database
-        *
-        * Most variations are allowed:
-        *
-        *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
-        *  phptype://username:password@hostspec/database_name
-        *  phptype://username:password@hostspec
-        *  phptype://username@hostspec
-        *  phptype://hostspec/database
-        *  phptype://hostspec
-        *  phptype(dbsyntax)
-        *  phptype
-        *
-        * @author Tomas V.V.Cox <cox@idecnet.com>
-        */
-       function parseDSN($dsn)
-       {
-               if (is_array($dsn)) {
-                       return $dsn;
-               }
-
-               $parsed = array(
-                       'phptype'  => false,
-                       'dbsyntax' => false,
-                       'protocol' => false,
-                       'hostspec' => false,
-                       'database' => false,
-                       'username' => false,
-                       'password' => false
-               );
-
-               // Find phptype and dbsyntax
-               if (($pos = strpos($dsn, '://')) !== false) {
-                       $str = substr($dsn, 0, $pos);
-                       $dsn = substr($dsn, $pos + 3);
-               } else {
-                       $str = $dsn;
-                       $dsn = NULL;
-               }
-
-               // Get phptype and dbsyntax
-               // $str => phptype(dbsyntax)
-               if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
-                       $parsed['phptype'] = $arr[1];
-                       $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
-               } else {
-                       $parsed['phptype'] = $str;
-                       $parsed['dbsyntax'] = $str;
-               }
-
-               if (empty($dsn)) {
-                       return $parsed;
-               }
-
-               // Get (if found): username and password
-               // $dsn => username:password@protocol+hostspec/database
-               if (($at = strpos($dsn,'@')) !== false) {
-                       $str = substr($dsn, 0, $at);
-                       $dsn = substr($dsn, $at + 1);
-                       if (($pos = strpos($str, ':')) !== false) {
-                               $parsed['username'] = urldecode(substr($str, 0, $pos));
-                               $parsed['password'] = urldecode(substr($str, $pos + 1));
-                       } else {
-                               $parsed['username'] = urldecode($str);
-                       }
-               }
-
-               // Find protocol and hostspec
-               // $dsn => protocol+hostspec/database
-               if (($pos=strpos($dsn, '/')) !== false) {
-                       $str = substr($dsn, 0, $pos);
-                       $dsn = substr($dsn, $pos + 1);
-               } else {
-                       $str = $dsn;
-                       $dsn = NULL;
-               }
-
-               // Get protocol + hostspec
-               // $str => protocol+hostspec
-               if (($pos=strpos($str, '+')) !== false) {
-                       $parsed['protocol'] = substr($str, 0, $pos);
-                       $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
-               } else {
-                       $parsed['hostspec'] = urldecode($str);
-               }
-
-               // Get dabase if any
-               // $dsn => database
-               if (!empty($dsn)) {
-                       $parsed['database'] = $dsn;
-               }
-
-               return $parsed;
-       }
-
-       /**
-        * Load a PHP database extension if it is not loaded already.
-        *
-        * @access public
-        *
-        * @param $name the base name of the extension (without the .so or
-        * .dll suffix)
-        *
-        * @return bool true if the extension was already or successfully
-        * loaded, false if it could not be loaded
-        */
-       function assertExtension($name)
-       {
-               if (!extension_loaded($name)) {
-                       $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so';
-                       @dl($name . $dlext);
-               }
-               if (!extension_loaded($name)) {
-                       return false;
-               }
-               return true;
-       }
-}
-
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * PEAR DB Emulation Layer for ADODB.\r
+ *\r
+ * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                                            |\r
+ * and Tomas V.V.Cox <cox@idecnet.com>.        Portions (c)1997-2002 The PHP Group.\r
+ */\r
+\r
+ /*\r
+ We support:\r
\r
+ DB_Common\r
+ ---------\r
+       query - returns PEAR_Error on error\r
+       limitQuery - return PEAR_Error on error\r
+       prepare - does not return PEAR_Error on error\r
+       execute - does not return PEAR_Error on error\r
+       setFetchMode - supports ASSOC and ORDERED\r
+       errorNative\r
+       quote\r
+       nextID\r
+       disconnect\r
+       \r
+       getOne\r
+       getAssoc\r
+       getRow\r
+       getCol\r
+       getAll\r
+       \r
+ DB_Result\r
+ ---------\r
+       numRows - returns -1 if not supported\r
+       numCols\r
+       fetchInto - does not support passing of fetchmode\r
+       fetchRows - does not support passing of fetchmode\r
+       free\r
+ */\r
\r
+define('ADODB_PEAR',dirname(__FILE__));\r
+include_once "PEAR.php";\r
+include_once ADODB_PEAR."/adodb-errorpear.inc.php";\r
+include_once ADODB_PEAR."/adodb.inc.php";\r
+\r
+if (!defined('DB_OK')) {\r
+define("DB_OK",        1);\r
+define("DB_ERROR",-1);\r
+/**\r
+ * This is a special constant that tells DB the user hasn't specified\r
+ * any particular get mode, so the default should be used.\r
+ */\r
+\r
+define('DB_FETCHMODE_DEFAULT', 0);\r
+\r
+/**\r
+ * Column data indexed by numbers, ordered from 0 and up\r
+ */\r
+\r
+define('DB_FETCHMODE_ORDERED', 1);\r
+\r
+/**\r
+ * Column data indexed by column names\r
+ */\r
+\r
+define('DB_FETCHMODE_ASSOC', 2);\r
+\r
+/* for compatibility */\r
+\r
+define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);\r
+define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);\r
+\r
+/**\r
+ * these are constants for the tableInfo-function\r
+ * they are bitwised or'ed. so if there are more constants to be defined\r
+ * in the future, adjust DB_TABLEINFO_FULL accordingly\r
+ */\r
+\r
+define('DB_TABLEINFO_ORDER', 1);\r
+define('DB_TABLEINFO_ORDERTABLE', 2);\r
+define('DB_TABLEINFO_FULL', 3);\r
+}\r
+\r
+/**\r
+ * The main "DB" class is simply a container class with some static\r
+ * methods for creating DB objects as well as some utility functions\r
+ * common to all parts of DB.\r
+ *\r
+ */\r
+\r
+class DB\r
+{\r
+       /**\r
+        * Create a new DB object for the specified database type\r
+        *\r
+        * @param $type string database type, for example "mysql"\r
+        *\r
+        * @return object a newly created DB object, or a DB error code on\r
+        * error\r
+        */\r
+\r
+       function &factory($type)\r
+       {\r
+               include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");\r
+               $obj = &NewADOConnection($type);\r
+               if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);\r
+               return $obj;\r
+       }\r
+\r
+       /**\r
+        * Create a new DB object and connect to the specified database\r
+        *\r
+        * @param $dsn mixed "data source name", see the DB::parseDSN\r
+        * method for a description of the dsn format.  Can also be\r
+        * specified as an array of the format returned by DB::parseDSN.\r
+        *\r
+        * @param $options mixed if boolean (or scalar), tells whether\r
+        * this connection should be persistent (for backends that support\r
+        * this).  This parameter can also be an array of options, see\r
+        * DB_common::setOption for more information on connection\r
+        * options.\r
+        *\r
+        * @return object a newly created DB connection object, or a DB\r
+        * error object on error\r
+        *\r
+        * @see DB::parseDSN\r
+        * @see DB::isError\r
+        */\r
+       function &connect($dsn, $options = false)\r
+       {\r
+               if (is_array($dsn)) {\r
+                       $dsninfo = $dsn;\r
+               } else {\r
+                       $dsninfo = DB::parseDSN($dsn);\r
+               }\r
+               switch ($dsninfo["phptype"]) {\r
+                       case 'pgsql':   $type = 'postgres7'; break;\r
+                       case 'ifx':             $type = 'informix9'; break;\r
+                       default:                $type = $dsninfo["phptype"]; break;\r
+               }\r
+\r
+               if (is_array($options) && isset($options["debug"]) &&\r
+                       $options["debug"] >= 2) {\r
+                       // expose php errors with sufficient debug level\r
+                        @include_once("adodb-$type.inc.php");\r
+               } else {\r
+                        @include_once("adodb-$type.inc.php");\r
+               }\r
+\r
+               @$obj =& NewADOConnection($type);\r
+               if (!is_object($obj)) {\r
+                       $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);\r
+                       return $obj;\r
+               }\r
+               if (is_array($options)) {\r
+                       foreach($options as $k => $v) {\r
+                               switch(strtolower($k)) {\r
+                               case 'persistent':      $persist = $v; break;\r
+                               #ibase\r
+                               case 'dialect':         $obj->dialect = $v; break;\r
+                               case 'charset':         $obj->charset = $v; break;\r
+                               case 'buffers':         $obj->buffers = $v; break;\r
+                               #ado\r
+                               case 'charpage':        $obj->charPage = $v; break;\r
+                               #mysql\r
+                               case 'clientflags': $obj->clientFlags = $v; break;\r
+                               }\r
+                       }\r
+               } else {\r
+                       $persist = false;\r
+               }\r
+\r
+               if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];\r
+               else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];\r
+               \r
+               if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
+               else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
+               \r
+               if (!$ok) $obj = ADODB_PEAR_Error();\r
+               return $obj;\r
+       }\r
+\r
+       /**\r
+        * Return the DB API version\r
+        *\r
+        * @return int the DB API version number\r
+        */\r
+       function apiVersion()\r
+       {\r
+               return 2;\r
+       }\r
+\r
+       /**\r
+        * Tell whether a result code from a DB method is an error\r
+        *\r
+        * @param $value int result code\r
+        *\r
+        * @return bool whether $value is an error\r
+        */\r
+       function isError($value)\r
+       {\r
+               return (is_object($value) &&\r
+                               (get_class($value) == 'db_error' ||\r
+                                is_subclass_of($value, 'db_error')));\r
+       }\r
+\r
+\r
+       /**\r
+        * Tell whether a result code from a DB method is a warning.\r
+        * Warnings differ from errors in that they are generated by DB,\r
+        * and are not fatal.\r
+        *\r
+        * @param $value mixed result value\r
+        *\r
+        * @return bool whether $value is a warning\r
+        */\r
+       function isWarning($value)\r
+       {\r
+               return is_object($value) &&\r
+                       (get_class( $value ) == "db_warning" ||\r
+                        is_subclass_of($value, "db_warning"));\r
+       }\r
+\r
+       /**\r
+        * Parse a data source name\r
+        *\r
+        * @param $dsn string Data Source Name to be parsed\r
+        *\r
+        * @return array an associative array with the following keys:\r
+        *\r
+        *  phptype: Database backend used in PHP (mysql, odbc etc.)\r
+        *  dbsyntax: Database used with regards to SQL syntax etc.\r
+        *  protocol: Communication protocol to use (tcp, unix etc.)\r
+        *  hostspec: Host specification (hostname[:port])\r
+        *  database: Database to use on the DBMS server\r
+        *  username: User name for login\r
+        *  password: Password for login\r
+        *\r
+        * The format of the supplied DSN is in its fullest form:\r
+        *\r
+        *  phptype(dbsyntax)://username:password@protocol+hostspec/database\r
+        *\r
+        * Most variations are allowed:\r
+        *\r
+        *  phptype://username:password@protocol+hostspec:110//usr/db_file.db\r
+        *  phptype://username:password@hostspec/database_name\r
+        *  phptype://username:password@hostspec\r
+        *  phptype://username@hostspec\r
+        *  phptype://hostspec/database\r
+        *  phptype://hostspec\r
+        *  phptype(dbsyntax)\r
+        *  phptype\r
+        *\r
+        * @author Tomas V.V.Cox <cox@idecnet.com>\r
+        */\r
+       function parseDSN($dsn)\r
+       {\r
+               if (is_array($dsn)) {\r
+                       return $dsn;\r
+               }\r
+\r
+               $parsed = array(\r
+                       'phptype'  => false,\r
+                       'dbsyntax' => false,\r
+                       'protocol' => false,\r
+                       'hostspec' => false,\r
+                       'database' => false,\r
+                       'username' => false,\r
+                       'password' => false\r
+               );\r
+\r
+               // Find phptype and dbsyntax\r
+               if (($pos = strpos($dsn, '://')) !== false) {\r
+                       $str = substr($dsn, 0, $pos);\r
+                       $dsn = substr($dsn, $pos + 3);\r
+               } else {\r
+                       $str = $dsn;\r
+                       $dsn = NULL;\r
+               }\r
+\r
+               // Get phptype and dbsyntax\r
+               // $str => phptype(dbsyntax)\r
+               if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {\r
+                       $parsed['phptype'] = $arr[1];\r
+                       $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];\r
+               } else {\r
+                       $parsed['phptype'] = $str;\r
+                       $parsed['dbsyntax'] = $str;\r
+               }\r
+\r
+               if (empty($dsn)) {\r
+                       return $parsed;\r
+               }\r
+\r
+               // Get (if found): username and password\r
+               // $dsn => username:password@protocol+hostspec/database\r
+               if (($at = strpos($dsn,'@')) !== false) {\r
+                       $str = substr($dsn, 0, $at);\r
+                       $dsn = substr($dsn, $at + 1);\r
+                       if (($pos = strpos($str, ':')) !== false) {\r
+                               $parsed['username'] = urldecode(substr($str, 0, $pos));\r
+                               $parsed['password'] = urldecode(substr($str, $pos + 1));\r
+                       } else {\r
+                               $parsed['username'] = urldecode($str);\r
+                       }\r
+               }\r
+\r
+               // Find protocol and hostspec\r
+               // $dsn => protocol+hostspec/database\r
+               if (($pos=strpos($dsn, '/')) !== false) {\r
+                       $str = substr($dsn, 0, $pos);\r
+                       $dsn = substr($dsn, $pos + 1);\r
+               } else {\r
+                       $str = $dsn;\r
+                       $dsn = NULL;\r
+               }\r
+\r
+               // Get protocol + hostspec\r
+               // $str => protocol+hostspec\r
+               if (($pos=strpos($str, '+')) !== false) {\r
+                       $parsed['protocol'] = substr($str, 0, $pos);\r
+                       $parsed['hostspec'] = urldecode(substr($str, $pos + 1));\r
+               } else {\r
+                       $parsed['hostspec'] = urldecode($str);\r
+               }\r
+\r
+               // Get dabase if any\r
+               // $dsn => database\r
+               if (!empty($dsn)) {\r
+                       $parsed['database'] = $dsn;\r
+               }\r
+\r
+               return $parsed;\r
+       }\r
+\r
+       /**\r
+        * Load a PHP database extension if it is not loaded already.\r
+        *\r
+        * @access public\r
+        *\r
+        * @param $name the base name of the extension (without the .so or\r
+        * .dll suffix)\r
+        *\r
+        * @return bool true if the extension was already or successfully\r
+        * loaded, false if it could not be loaded\r
+        */\r
+       function assertExtension($name)\r
+       {\r
+               if (!extension_loaded($name)) {\r
+                       $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so';\r
+                       @dl($name . $dlext);\r
+               }\r
+               if (!extension_loaded($name)) {\r
+                       return false;\r
+               }\r
+               return true;\r
+       }\r
+}\r
+\r
 ?>
\ No newline at end of file
index 7444e1d9d8d7ecb808302b52a74bb53c4183542d..5a99d15fc90f9ae8d1b3c6d8f731b14bcdd6774f 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning.
-  
-  My apologies if you see code mixed with presentation. The presentation suits
-  my needs. If you want to separate code from presentation, be my guest. Patches
-  are welcome.
-  
-*/
-
-if (!defined(ADODB_DIR)) include_once(dirname(__FILE__).'/adodb.inc.php');
-include_once(ADODB_DIR.'/tohtml.inc.php');
-
-
-/* return microtime value as a float */
-function adodb_microtime()
-{
-       $t = microtime();
-       $t = explode(' ',$t);
-       return (float)$t[1]+ (float)$t[0];
-}
-
-/* sql code timing */
-function& adodb_log_sql(&$conn,$sql,$inputarr)
-{
-global $HTTP_SERVER_VARS;
-       
-    $perf_table = adodb_perf::table();
-       $conn->fnExecute = false;
-       $t0 = microtime();
-       $rs =& $conn->Execute($sql,$inputarr);
-       $t1 = microtime();
-
-       if (!empty($conn->_logsql)) {
-               $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();
-                       $conn->lastInsID = 0;
-                       $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
-               } else {
-                       $tracer = '';
-                       $errM = '';
-                       $errN = 0;
-                       $dbg = $conn->debug;
-                       $conn->debug = false;
-                       if (!is_object($rs) || $rs->dataProvider == 'empty') 
-                               $conn->_affected = $conn->affected_rows(true);
-                       $conn->lastInsID = @$conn->Insert_ID();
-                       $conn->debug = $dbg;
-               }
-               if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {
-                       $tracer .= '<br>'.$HTTP_SERVER_VARS['HTTP_HOST'];
-                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF'];
-               } else 
-                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '<br>'.$HTTP_SERVER_VARS['PHP_SELF'];
-               //$tracer .= (string) adodb_backtrace(false);
-               
-               $tracer = substr($tracer,0,500);
-               
-               if (is_array($inputarr)) {
-                       if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
-                       else {
-                               $params = '';
-                               $params = implode(', ',$inputarr);
-                               if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
-                       }
-               } else {
-                       $params = '';
-               }
-               
-               if (is_array($sql)) $sql = $sql[0];
-               $arr = array('b'=>trim(substr($sql,0,230)),
-                                       'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>round($time,6));
-
-               $saved = $conn->debug;
-               $conn->debug = 0;
-               
-               if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
-                       $isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)";
-               } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') {
-                       $timer = $arr['f'];
-                       if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
-
-                       $sql1 = $conn->qstr($arr['b']);
-                       $sql2 = $conn->qstr($arr['c']);
-                       $params = $conn->qstr($arr['d']);
-                       $tracer = $conn->qstr($arr['e']);
-                       
-                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)";
-                       if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
-                       $arr = false;
-               } else {
-                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)";
-               }
-               $ok = $conn->Execute($isql,$arr);
-               $conn->debug = $saved;
-               
-               if ($ok) {
-                       $conn->_logsql = true; 
-               } else {
-                       $err2 = $conn->ErrorMsg();
-                       $conn->_logsql = true; // enable logsql error simulation
-                       $perf =& NewPerfMonitor($conn);
-                       if ($perf) {
-                               if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
-                       } else {
-                               $ok = $conn->Execute("create table $perf_table (
-                               created varchar(50),
-                               sql0 varchar(250), 
-                               sql1 varchar(4000),
-                               params varchar(3000),
-                               tracer varchar(500),
-                               timer decimal(16,6))");
-                       }
-                       if (!$ok) {
-                               ADOConnection::outp( "<b>LOGSQL Insert Failed</b>: $isql<br>$err2</br>");
-                               $conn->_logsql = false;
-                       }
-               }
-               $conn->_errorMsg = $errM;
-               $conn->_errorCode = $errN;
-       } 
-       $conn->fnExecute = 'adodb_log_sql';
-       return $rs;
-}
-
-       
-/*
-The settings data structure is an associative array that database parameter per element.
-
-Each database parameter element in the array is itself an array consisting of:
-
-0: category code, used to group related db parameters
-1: either
-       a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", 
-       b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
-       c. a string prefixed by =, then a PHP method of the class is invoked, 
-               e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
-2: description of the database parameter
-*/
-
-class adodb_perf {
-       var $conn;
-       var $color = '#F0F0F0';
-       var $table = '<table border=1 bgcolor=white>';
-       var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
-       var $warnRatio = 90;
-       var $tablesSQL = false;
-       var $cliFormat = "%32s => %s \r\n";
-       var $sql1 = 'sql1';  // used for casting sql1 to text for mssql
-       var $explain = true;
-       var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
-       var $createTableSQL = false;
-       var $maxLength = 2000;
-       
-    // Sets the tablename to be used            
-    function table($newtable = false)
-    {
-        static $_table;
-
-        if (!empty($newtable))  $_table = $newtable;
-               if (empty($_table)) $_table = 'adodb_logsql';
-        return $_table;
-    }
-
-       // returns array with info to calculate CPU Load
-       function _CPULoad()
-       {
-/*
-
-cpu  524152 2662 2515228 336057010
-cpu0 264339 1408 1257951 168025827
-cpu1 259813 1254 1257277 168031181
-page 622307 25475680
-swap 24 1891
-intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
-ctxt 66155838
-btime 1062315585
-processes 69293
-
-*/
-               // Algorithm is taken from
-               // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
-               if (strncmp(PHP_OS,'WIN',3)==0) {
-                       @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
-                       if (!$c) return false;
-                       
-                       $info[0] = $c->PercentProcessorTime;
-                       $info[1] = 0;
-                       $info[2] = 0;
-                       $info[3] = $c->TimeStamp_Sys100NS;
-                       //print_r($info);
-                       return $info;
-               }
-               
-               // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
-               $statfile = '/proc/stat';
-               if (!file_exists($statfile)) return false;
-               
-               $fd = fopen($statfile,"r");
-               if (!$fd) return false;
-               
-               $statinfo = explode("\n",fgets($fd, 1024));
-               fclose($fd);
-               foreach($statinfo as $line) {
-                       $info = explode(" ",$line);
-                       if($info[0]=="cpu") {
-                               array_shift($info);  // pop off "cpu"
-                               if(!$info[0]) array_shift($info); // pop off blank space (if any)
-                               return $info;
-                       }
-               }
-               
-               return false;
-               
-       }
-       
-       /* NOT IMPLEMENTED */
-       function MemInfo()
-       {
-               /*
-
-        total:    used:    free:  shared: buffers:  cached:
-Mem:  1055289344 917299200 137990144        0 165437440 599773184
-Swap: 2146775040 11055104 2135719936
-MemTotal:      1030556 kB
-MemFree:        134756 kB
-MemShared:           0 kB
-Buffers:        161560 kB
-Cached:         581384 kB
-SwapCached:       4332 kB
-Active:         494468 kB
-Inact_dirty:    322856 kB
-Inact_clean:     24256 kB
-Inact_target:   168316 kB
-HighTotal:      131064 kB
-HighFree:         1024 kB
-LowTotal:       899492 kB
-LowFree:        133732 kB
-SwapTotal:     2096460 kB
-SwapFree:      2085664 kB
-Committed_AS:   348732 kB
-               */
-       }
-       
-       
-       /*
-               Remember that this is client load, not db server load!
-       */
-       var $_lastLoad;
-       function CPULoad()
-       {
-               $info = $this->_CPULoad();
-               if (!$info) return false;
-                       
-               if (empty($this->_lastLoad)) {
-                       sleep(1);
-                       $this->_lastLoad = $info;
-                       $info = $this->_CPULoad();
-               }
-               
-               $last = $this->_lastLoad;
-               $this->_lastLoad = $info;
-               
-               $d_user = $info[0] - $last[0];
-               $d_nice = $info[1] - $last[1];
-               $d_system = $info[2] - $last[2];
-               $d_idle = $info[3] - $last[3];
-               
-               //printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
-
-               if (strncmp(PHP_OS,'WIN',3)==0) {
-                       if ($d_idle < 1) $d_idle = 1;
-                       return 100*(1-$d_user/$d_idle);
-               }else {
-                       $total=$d_user+$d_nice+$d_system+$d_idle;
-                       if ($total<1) $total=1;
-                       return 100*($d_user+$d_nice+$d_system)/$total; 
-               }
-       }
-       
-       function Tracer($sql)
-       {
-        $perf_table = adodb_perf::table();
-               $saveE = $this->conn->fnExecute;
-               $this->conn->fnExecute = false;
-                       
-               $sqlq = $this->conn->qstr($sql);
-               $arr = $this->conn->GetArray(
-"select count(*),tracer 
-       from $perf_table where sql1=$sqlq 
-       group by tracer
-       order by 1 desc");
-               $s = '';
-               if ($arr) {
-                       $s .= '<h3>Scripts Affected</h3>';
-                       foreach($arr as $k) {
-                               $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
-                       }
-               }
-               $this->conn->fnExecute = $saveE;
-               return $s;
-       }
-
-       /* 
-               Explain Plan for $sql.
-               If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the 
-                       actual sql.
-       */
-       function Explain($sql,$partial=false)
-       {       
-               return false;
-       }
-       
-       function InvalidSQL($numsql = 10)
-       {
-       global $HTTP_GET_VARS;
-       
-               if (isset($HTTP_GET_VARS['sql'])) return;
-               $s = '<h3>Invalid SQL</h3>';
-               $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);
-               $this->conn->fnExecute = $saveE;
-               if ($rs) {
-                       $s .= rs2html($rs,false,false,false,false);
-               } else
-                       return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
-               
-               return $s;
-       }
-
-       
-       /*
-               This script identifies the longest running SQL
-       */      
-       function _SuspiciousSQL($numsql = 10)
-       {
-               global $ADODB_FETCH_MODE,$HTTP_GET_VARS;
-               
-            $perf_table = adodb_perf::table();
-                       $saveE = $this->conn->fnExecute;
-                       $this->conn->fnExecute = false;
-                       
-                       if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) {
-                               $partial = !empty($HTTP_GET_VARS['part']);
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
-                       }
-                       
-                       if (isset($HTTP_GET_VARS['sql'])) return;
-                       $sql1 = $this->sql1;
-                       
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       //$this->conn->debug=1;
-                       $rs =& $this->conn->SelectLimit(
-                       "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
-                               from $perf_table
-                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
-                               and (tracer is null or tracer not like 'ERROR:%')
-                               group by sql1
-                               order by 1 desc",$numsql);
-                       $ADODB_FETCH_MODE = $save;
-                       $this->conn->fnExecute = $saveE;
-                       
-                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
-                       $s = "<h3>Suspicious SQL</h3>
-<font size=1>The following SQL have high average execution times</font><br>
-<table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
-                       $max = $this->maxLength;
-                       while (!$rs->EOF) {
-                               $sql = $rs->fields[1];
-                               $raw = urlencode($sql);
-                               if (strlen($raw)>$max-100) {
-                                       $sql2 = substr($sql,0,$max-500);
-                                       $raw = urlencode($sql2).'&part='.crc32($sql);
-                               }
-                               $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
-                               $suffix = "</a>";
-                               if ($this->explain == false || strlen($prefix)>$max) {
-                                       $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
-                                       $prefix = '';
-                               }
-                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
-                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
-                               $rs->MoveNext();
-                       }
-                       return $s."</table>";
-               
-       }
-       
-       function CheckMemory()
-       {
-               return '';
-       }
-       
-       
-       function SuspiciousSQL($numsql=10)
-       {
-               return adodb_perf::_SuspiciousSQL($numsql);
-       }
-
-       function ExpensiveSQL($numsql=10)
-       {
-               return adodb_perf::_ExpensiveSQL($numsql);
-       }
-
-       
-       /*
-               This reports the percentage of load on the instance due to the most 
-               expensive few SQL statements. Tuning these statements can often 
-               make huge improvements in overall system performance. 
-       */
-       function _ExpensiveSQL($numsql = 10)
-       {
-               global $HTTP_GET_VARS,$ADODB_FETCH_MODE;
-               
-            $perf_table = adodb_perf::table();
-                       $saveE = $this->conn->fnExecute;
-                       $this->conn->fnExecute = false;
-                       
-                       if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) {
-                               $partial = !empty($HTTP_GET_VARS['part']);
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
-                       }
-                       
-                       if (isset($HTTP_GET_VARS['sql'])) return;
-                       
-                       $sql1 = $this->sql1;
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       $rs =& $this->conn->SelectLimit(
-                       "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
-                               from $perf_table
-                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')
-                               and (tracer is null or tracer not like 'ERROR:%')
-                               group by sql1
-                               order by 1 desc",$numsql);
-                       
-                       $this->conn->fnExecute = $saveE;
-                       $ADODB_FETCH_MODE = $save;
-                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
-                       $s = "<h3>Expensive SQL</h3>
-<font size=1>Tuning the following SQL will reduce the server load substantially</font><br>
-<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
-                       $max = $this->maxLength;
-                       while (!$rs->EOF) {
-                               $sql = $rs->fields[1];
-                               $raw = urlencode($sql);
-                               if (strlen($raw)>$max-100) {
-                                       $sql2 = substr($sql,0,$max-500);
-                                       $raw = urlencode($sql2).'&part='.crc32($sql);
-                               }
-                               $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
-                               $suffix = "</a>";
-                               if($this->explain == false || strlen($prefix>$max)) {
-                                       $prefix = '';
-                                       $suffix = '';
-                               }
-                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
-                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
-                               $rs->MoveNext();
-                       }
-                       return $s."</table>";
-       }
-       
-       /*
-               Raw function to return parameter value from $settings.
-       */
-       function DBParameter($param)
-       {
-               if (empty($this->settings[$param])) return false;
-               $sql = $this->settings[$param][1];
-               return $this->_DBParameter($sql);
-       }
-       
-       /*
-               Raw function returning array of poll paramters
-       */
-       function &PollParameters()
-       {
-               $arr[0] = (float)$this->DBParameter('data cache hit ratio');
-               $arr[1] = (float)$this->DBParameter('data reads');
-               $arr[2] = (float)$this->DBParameter('data writes');
-               $arr[3] = (integer) $this->DBParameter('current connections');
-               return $arr;
-       }
-       
-       /*
-               Low-level Get Database Parameter
-       */
-       function _DBParameter($sql)
-       {
-               $savelog = $this->conn->LogSQL(false);
-               if (is_array($sql)) {
-               global $ADODB_FETCH_MODE;
-               
-                       $sql1 = $sql[0];
-                       $key = $sql[1];
-                       if (sizeof($sql)>2) $pos = $sql[2];
-                       else $pos = 1;
-                       if (sizeof($sql)>3) $coef = $sql[3];
-                       else $coef = false;
-                       $ret = false;
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       $rs = $this->conn->Execute($sql1);
-                       $ADODB_FETCH_MODE = $save;
-                       if ($rs) {
-                               while (!$rs->EOF) {
-                                       $keyf = reset($rs->fields);
-                                       if (trim($keyf) == $key) {
-                                               $ret = $rs->fields[$pos];
-                                               if ($coef) $ret *= $coef;
-                                               break;
-                                       }
-                                       $rs->MoveNext();
-                               }
-                               $rs->Close();
-                       }
-                       $this->conn->LogSQL($savelog);
-                       return $ret;
-               } else {
-                       if (strncmp($sql,'=',1) == 0) {
-                               $fn = substr($sql,1);
-                               return $this->$fn();
-                       }
-                       $sql = str_replace('$DATABASE',$this->conn->database,$sql);
-                       $ret = $this->conn->GetOne($sql);
-                       $this->conn->LogSQL($savelog);
-                       
-                       return $ret;
-               }
-       }
-       
-       /*
-               Warn if cache ratio falls below threshold. Displayed in "Description" column.
-       */
-       function WarnCacheRatio($val)
-       {
-               if ($val < $this->warnRatio) 
-                        return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
-               else return '';
-       }
-       
-       /***********************************************************************************************/
-       //                                    HIGH LEVEL UI FUNCTIONS
-       /***********************************************************************************************/
-
-       
-       function UI($pollsecs=5)
-       {
-       global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS;
-       
-    $perf_table = adodb_perf::table();
-       $conn = $this->conn;
-       
-       $app = $conn->host;
-       if ($conn->host && $conn->database) $app .= ', db=';
-       $app .= $conn->database;
-       
-       if ($app) $app .= ', ';
-       $savelog = $this->conn->LogSQL(false);  
-       $info = $conn->ServerInfo();
-       if (isset($HTTP_GET_VARS['clearsql'])) {
-               $this->conn->Execute("delete from $perf_table");
-       }
-       $this->conn->LogSQL($savelog);
-       
-       // magic quotes
-       
-       if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) {
-               $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']);
-       }
-       
-       if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
-       else  $nsql = $_SESSION['ADODB_PERF_SQL'];
-       
-       $app .= '<font size=-1>'.$info['description'].'</font>';
-       
-       
-       if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do'];
-       else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do'];
-        else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql';
-        else $do = 'stats';
-        
-       if (isset($HTTP_GET_VARS['nsql'])) {
-               if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql'];
-       }
-       echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
-       if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
-       else $form = "<td>&nbsp;</td>";
-       
-       $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
-       
-       if  (empty($HTTP_GET_VARS['hidem']))
-       echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
-       <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance Monitor</b> for $app</tr><tr><td>
-       <a href=?do=stats>Performance Stats</a> &nbsp; <a href=?do=viewsql>View SQL</a>
-        &nbsp; <a href=?do=tables>View Tables</a> &nbsp; <a href=?do=poll>Poll Stats</a>",
-        $allowsql ? ' &nbsp; <a href=?do=dosql>Run SQL</a>' : '',
-        "$form",
-        "</tr></table>";
-
-        
-               switch ($do) {
-               default:
-               case 'stats':
-                       echo $this->HealthCheck();
-                       $this->conn->debug=1;
-                       echo $this->CheckMemory();
-                       break;
-               case 'poll':
-                       echo "<iframe width=720 height=80% 
-                               src=\"{$HTTP_SERVER_VARS['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
-                       break;
-               case 'poll2':
-                       echo "<pre>";
-                       $this->Poll($pollsecs);
-                       break;
-               
-               case 'dosql':
-                       if (!$allowsql) break;
-                       
-                       $this->DoSQLForm();
-                       break;
-               case 'viewsql':
-                       if (empty($HTTP_GET_VARS['hidem']))
-                               echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
-                       echo($this->SuspiciousSQL($nsql));
-                       echo($this->ExpensiveSQL($nsql));
-                       echo($this->InvalidSQL($nsql));
-                       break;
-               case 'tables': 
-                       echo $this->Tables(); break;
-               }
-               global $ADODB_vers;
-               echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
-       }
-       
-       /*
-               Runs in infinite loop, returning real-time statistics
-       */
-       function Poll($secs=5)
-       {
-               $this->conn->fnExecute = false;
-               //$this->conn->debug=1;
-               if ($secs <= 1) $secs = 1;
-               echo "Accumulating statistics, every $secs seconds...\n";flush();
-               $arro =& $this->PollParameters();
-               $cnt = 0;
-               set_time_limit(0);
-               sleep($secs);
-               while (1) {
-                       $arr =& $this->PollParameters();
-                       
-                       $hits   = sprintf('%2.2f',$arr[0]);
-                       $reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
-                       $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
-                       $sess = sprintf('%5d',$arr[3]);
-                       
-                       $load = $this->CPULoad();
-                       if ($load !== false) {
-                               $oslabel = 'WS-CPU%';
-                               $osval = sprintf(" %2.1f  ",(float) $load);
-                       }else {
-                               $oslabel = '';
-                               $osval = '';
-                       }
-                       if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n"; 
-                       $cnt += 1;
-                       echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";
-                       flush();
-                       
-                       sleep($secs);
-                       $arro = $arr;
-               }
-       }
-       
-       /*
-               Returns basic health check in a command line interface
-       */
-       function HealthCheckCLI()
-       {
-               return $this->HealthCheck(true);
-       }
-       
-               
-       /*
-               Returns basic health check as HTML
-       */
-       function HealthCheck($cli=false)
-       {
-               $saveE = $this->conn->fnExecute;
-               $this->conn->fnExecute = false; 
-               if ($cli) $html = '';
-               else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
-               
-               $oldc = false;
-               $bgc = '';
-               foreach($this->settings as $name => $arr) {
-                       if ($arr === false) break;
-                       
-                       if (!is_string($name)) {
-                               if ($cli) $html .= " -- $arr -- \n";
-                               else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
-                               continue;
-                       }
-                       
-                       if (!is_array($arr)) break;
-                       $category = $arr[0];
-                       $how = $arr[1];
-                       if (sizeof($arr)>2) $desc = $arr[2];
-                       else $desc = ' &nbsp; ';
-                       
-                       
-                       if ($category == 'HIDE') continue;
-                       
-                       $val = $this->_DBParameter($how);
-                       
-                       if ($desc && strncmp($desc,"=",1) === 0) {
-                               $fn = substr($desc,1);
-                               $desc = $this->$fn($val);
-                       }
-                       
-                       if ($val === false) {
-                               $m = $this->conn->ErrorMsg();
-                               $val = "Error: $m"; 
-                       } else {
-                               if (is_numeric($val) && $val >= 256*1024) {
-                                       if ($val % (1024*1024) == 0) {
-                                               $val /= (1024*1024);
-                                               $val .= 'M';
-                                       } else if ($val % 1024 == 0) {
-                                               $val /= 1024;
-                                               $val .= 'K';
-                                       }
-                                       //$val = htmlspecialchars($val);
-                               }
-                       }
-                       if ($category != $oldc) {
-                               $oldc = $category;
-                               //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
-                       }
-                       if (strlen($desc)==0) $desc = '&nbsp;';
-                       if (strlen($val)==0) $val = '&nbsp;';
-                       if ($cli) {
-                               $html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
-                               
-                       }else {
-                               $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
-                       }
-               }
-               
-               if (!$cli) $html .= "</table>\n";
-               $this->conn->fnExecute = $saveE;
-                       
-               return $html;   
-       }
-       
-       function Tables($orderby='1')
-       {
-               if (!$this->tablesSQL) return false;
-               
-               $savelog = $this->conn->LogSQL(false);
-               $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
-               $this->conn->LogSQL($savelog);
-               $html = rs2html($rs,false,false,false,false);
-               return $html;
-       }
-       
-
-       function CreateLogTable()
-       {
-               if (!$this->createTableSQL) return false;
-               
-               $savelog = $this->conn->LogSQL(false);
-               $ok = $this->conn->Execute($this->createTableSQL);
-               $this->conn->LogSQL($savelog);
-               return ($ok) ? true : false;
-       }
-       
-       function DoSQLForm()
-       {
-       global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS;
-       
-               $HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS);
-               
-               $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
-               $sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : '';
-
-               if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows'];
-               else $rows = 3;
-               
-               if (isset($HTTP_VARS['SMALLER'])) {
-                       $rows /= 2;
-                       if ($rows < 3) $rows = 3;
-                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
-               }
-               if (isset($HTTP_VARS['BIGGER'])) {
-                       $rows *= 2;
-                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
-               }
-               
-?>
-
-<form method="POST" action="<?php echo $PHP_SELF ?>">
-<table><tr>
-<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
-</td>
-<td align=right>
-<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
-</td></tr>
-  <tr>
-  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
-  </td>
-  </tr>
- </table>
-</form>
-
-<?php
-               if (!isset($HTTP_VARS['sql'])) return;
-               
-               $sql = $this->undomq(trim($sql));
-               if (substr($sql,strlen($sql)-1) === ';') {
-                       $print = true;
-                       $sqla = $this->SplitSQL($sql);
-               } else  {
-                       $print = false;
-                       $sqla = array($sql);
-               }
-               foreach($sqla as $sqls) {
-
-                       if (!$sqls) continue;
-                       
-                       if ($print) {
-                               print "<p>".htmlspecialchars($sqls)."</p>";
-                               flush();
-                       }
-                       $savelog = $this->conn->LogSQL(false);
-                       $rs = $this->conn->Execute($sqls);
-                       $this->conn->LogSQL($savelog);
-                       if ($rs && is_object($rs) && !$rs->EOF) {
-                               rs2html($rs);
-                               while ($rs->NextRecordSet()) {
-                                       print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
-                                       rs2html($rs);
-                               }
-                       } else {
-                               $e1 = (integer) $this->conn->ErrorNo();
-                               $e2 = $this->conn->ErrorMsg();
-                               if (($e1) || ($e2)) {
-                                       if (empty($e1)) $e1 = '-1'; // postgresql fix
-                                       print ' &nbsp; '.$e1.': '.$e2;
-                               } else {
-                                       print "<p>No Recordset returned<br></p>";
-                               }
-                       }
-               } // foreach
-       }
-       
-       function SplitSQL($sql)
-       {
-               $arr = explode(';',$sql);
-               return $arr;
-       }
-       
-       function undomq(&$m) 
-       {
-       if (get_magic_quotes_gpc()) {
-               // undo the damage
-               $m = str_replace('\\\\','\\',$m);
-               $m = str_replace('\"','"',$m);
-               $m = str_replace('\\\'','\'',$m);
-       }
-       return $m;
-}
-}
-
-
-
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning.\r
+  \r
+  My apologies if you see code mixed with presentation. The presentation suits\r
+  my needs. If you want to separate code from presentation, be my guest. Patches\r
+  are welcome.\r
+  \r
+*/\r
+\r
+if (!defined(ADODB_DIR)) include_once(dirname(__FILE__).'/adodb.inc.php');\r
+include_once(ADODB_DIR.'/tohtml.inc.php');\r
+\r
+\r
+// avoids localization problems where , is used instead of .\r
+function adodb_round($n,$prec)\r
+{\r
+       return number_format($n, $prec, '.', '');\r
+}\r
+\r
+/* return microtime value as a float */\r
+function adodb_microtime()\r
+{\r
+       $t = microtime();\r
+       $t = explode(' ',$t);\r
+       return (float)$t[1]+ (float)$t[0];\r
+}\r
+\r
+/* sql code timing */\r
+function& adodb_log_sql(&$conn,$sql,$inputarr)\r
+{\r
+global $HTTP_SERVER_VARS;\r
+       \r
+    $perf_table = adodb_perf::table();\r
+       $conn->fnExecute = false;\r
+       $t0 = microtime();\r
+       $rs =& $conn->Execute($sql,$inputarr);\r
+       $t1 = microtime();\r
+\r
+       if (!empty($conn->_logsql)) {\r
+               $conn->_logsql = false; // disable logsql error simulation\r
+               $dbT = $conn->databaseType;\r
+               \r
+               $a0 = split(' ',$t0);\r
+               $a0 = (float)$a0[1]+(float)$a0[0];\r
+               \r
+               $a1 = split(' ',$t1);\r
+               $a1 = (float)$a1[1]+(float)$a1[0];\r
+               \r
+               $time = $a1 - $a0;\r
+       \r
+               if (!$rs) {\r
+                       $errM = $conn->ErrorMsg();\r
+                       $errN = $conn->ErrorNo();\r
+                       $conn->lastInsID = 0;\r
+                       $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);\r
+               } else {\r
+                       $tracer = '';\r
+                       $errM = '';\r
+                       $errN = 0;\r
+                       $dbg = $conn->debug;\r
+                       $conn->debug = false;\r
+                       if (!is_object($rs) || $rs->dataProvider == 'empty') \r
+                               $conn->_affected = $conn->affected_rows(true);\r
+                       $conn->lastInsID = @$conn->Insert_ID();\r
+                       $conn->debug = $dbg;\r
+               }\r
+               if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {\r
+                       $tracer .= '<br>'.$HTTP_SERVER_VARS['HTTP_HOST'];\r
+                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF'];\r
+               } else \r
+                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '<br>'.$HTTP_SERVER_VARS['PHP_SELF'];\r
+               //$tracer .= (string) adodb_backtrace(false);\r
+               \r
+               $tracer = substr($tracer,0,500);\r
+               \r
+               if (is_array($inputarr)) {\r
+                       if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);\r
+                       else {\r
+                               $params = '';\r
+                               $params = implode(', ',$inputarr);\r
+                               if (strlen($params) >= 3000) $params = substr($params, 0, 3000);\r
+                       }\r
+               } else {\r
+                       $params = '';\r
+               }\r
+               \r
+               if (is_array($sql)) $sql = $sql[0];\r
+               $arr = array('b'=>trim(substr($sql,0,230)),\r
+                                       'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));\r
+               //var_dump($arr);\r
+               $saved = $conn->debug;\r
+               $conn->debug = 0;\r
+               \r
+               if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {\r
+                       $isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)";\r
+               } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') {\r
+                       $timer = $arr['f'];\r
+                       if ($dbT == 'informix') $sql2 = substr($sql2,0,230);\r
+\r
+                       $sql1 = $conn->qstr($arr['b']);\r
+                       $sql2 = $conn->qstr($arr['c']);\r
+                       $params = $conn->qstr($arr['d']);\r
+                       $tracer = $conn->qstr($arr['e']);\r
+                       \r
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)";\r
+                       if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);\r
+                       $arr = false;\r
+               } else {\r
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)";\r
+               }\r
+               $ok = $conn->Execute($isql,$arr);\r
+               $conn->debug = $saved;\r
+               \r
+               if ($ok) {\r
+                       $conn->_logsql = true; \r
+               } else {\r
+                       $err2 = $conn->ErrorMsg();\r
+                       $conn->_logsql = true; // enable logsql error simulation\r
+                       $perf =& NewPerfMonitor($conn);\r
+                       if ($perf) {\r
+                               if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);\r
+                       } else {\r
+                               $ok = $conn->Execute("create table $perf_table (\r
+                               created varchar(50),\r
+                               sql0 varchar(250), \r
+                               sql1 varchar(4000),\r
+                               params varchar(3000),\r
+                               tracer varchar(500),\r
+                               timer decimal(16,6))");\r
+                       }\r
+                       if (!$ok) {\r
+                               ADOConnection::outp( "<b>LOGSQL Insert Failed</b>: $isql<br>$err2</br>");\r
+                               $conn->_logsql = false;\r
+                       }\r
+               }\r
+               $conn->_errorMsg = $errM;\r
+               $conn->_errorCode = $errN;\r
+       } \r
+       $conn->fnExecute = 'adodb_log_sql';\r
+       return $rs;\r
+}\r
+\r
+       \r
+/*\r
+The settings data structure is an associative array that database parameter per element.\r
+\r
+Each database parameter element in the array is itself an array consisting of:\r
+\r
+0: category code, used to group related db parameters\r
+1: either\r
+       a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", \r
+       b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),\r
+       c. a string prefixed by =, then a PHP method of the class is invoked, \r
+               e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',\r
+2: description of the database parameter\r
+*/\r
+\r
+class adodb_perf {\r
+       var $conn;\r
+       var $color = '#F0F0F0';\r
+       var $table = '<table border=1 bgcolor=white>';\r
+       var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';\r
+       var $warnRatio = 90;\r
+       var $tablesSQL = false;\r
+       var $cliFormat = "%32s => %s \r\n";\r
+       var $sql1 = 'sql1';  // used for casting sql1 to text for mssql\r
+       var $explain = true;\r
+       var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";\r
+       var $createTableSQL = false;\r
+       var $maxLength = 2000;\r
+       \r
+    // Sets the tablename to be used            \r
+    function table($newtable = false)\r
+    {\r
+        static $_table;\r
+\r
+        if (!empty($newtable))  $_table = $newtable;\r
+               if (empty($_table)) $_table = 'adodb_logsql';\r
+        return $_table;\r
+    }\r
+\r
+       // returns array with info to calculate CPU Load\r
+       function _CPULoad()\r
+       {\r
+/*\r
+\r
+cpu  524152 2662 2515228 336057010\r
+cpu0 264339 1408 1257951 168025827\r
+cpu1 259813 1254 1257277 168031181\r
+page 622307 25475680\r
+swap 24 1891\r
+intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\r
+disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)\r
+ctxt 66155838\r
+btime 1062315585\r
+processes 69293\r
+\r
+*/\r
+               // Algorithm is taken from\r
+               // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp\r
+               if (strncmp(PHP_OS,'WIN',3)==0) {\r
+                       @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");\r
+                       if (!$c) return false;\r
+                       \r
+                       $info[0] = $c->PercentProcessorTime;\r
+                       $info[1] = 0;\r
+                       $info[2] = 0;\r
+                       $info[3] = $c->TimeStamp_Sys100NS;\r
+                       //print_r($info);\r
+                       return $info;\r
+               }\r
+               \r
+               // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)\r
+               $statfile = '/proc/stat';\r
+               if (!file_exists($statfile)) return false;\r
+               \r
+               $fd = fopen($statfile,"r");\r
+               if (!$fd) return false;\r
+               \r
+               $statinfo = explode("\n",fgets($fd, 1024));\r
+               fclose($fd);\r
+               foreach($statinfo as $line) {\r
+                       $info = explode(" ",$line);\r
+                       if($info[0]=="cpu") {\r
+                               array_shift($info);  // pop off "cpu"\r
+                               if(!$info[0]) array_shift($info); // pop off blank space (if any)\r
+                               return $info;\r
+                       }\r
+               }\r
+               \r
+               return false;\r
+               \r
+       }\r
+       \r
+       /* NOT IMPLEMENTED */\r
+       function MemInfo()\r
+       {\r
+               /*\r
+\r
+        total:    used:    free:  shared: buffers:  cached:\r
+Mem:  1055289344 917299200 137990144        0 165437440 599773184\r
+Swap: 2146775040 11055104 2135719936\r
+MemTotal:      1030556 kB\r
+MemFree:        134756 kB\r
+MemShared:           0 kB\r
+Buffers:        161560 kB\r
+Cached:         581384 kB\r
+SwapCached:       4332 kB\r
+Active:         494468 kB\r
+Inact_dirty:    322856 kB\r
+Inact_clean:     24256 kB\r
+Inact_target:   168316 kB\r
+HighTotal:      131064 kB\r
+HighFree:         1024 kB\r
+LowTotal:       899492 kB\r
+LowFree:        133732 kB\r
+SwapTotal:     2096460 kB\r
+SwapFree:      2085664 kB\r
+Committed_AS:   348732 kB\r
+               */\r
+       }\r
+       \r
+       \r
+       /*\r
+               Remember that this is client load, not db server load!\r
+       */\r
+       var $_lastLoad;\r
+       function CPULoad()\r
+       {\r
+               $info = $this->_CPULoad();\r
+               if (!$info) return false;\r
+                       \r
+               if (empty($this->_lastLoad)) {\r
+                       sleep(1);\r
+                       $this->_lastLoad = $info;\r
+                       $info = $this->_CPULoad();\r
+               }\r
+               \r
+               $last = $this->_lastLoad;\r
+               $this->_lastLoad = $info;\r
+               \r
+               $d_user = $info[0] - $last[0];\r
+               $d_nice = $info[1] - $last[1];\r
+               $d_system = $info[2] - $last[2];\r
+               $d_idle = $info[3] - $last[3];\r
+               \r
+               //printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);\r
+\r
+               if (strncmp(PHP_OS,'WIN',3)==0) {\r
+                       if ($d_idle < 1) $d_idle = 1;\r
+                       return 100*(1-$d_user/$d_idle);\r
+               }else {\r
+                       $total=$d_user+$d_nice+$d_system+$d_idle;\r
+                       if ($total<1) $total=1;\r
+                       return 100*($d_user+$d_nice+$d_system)/$total; \r
+               }\r
+       }\r
+       \r
+       function Tracer($sql)\r
+       {\r
+        $perf_table = adodb_perf::table();\r
+               $saveE = $this->conn->fnExecute;\r
+               $this->conn->fnExecute = false;\r
+                       \r
+               $sqlq = $this->conn->qstr($sql);\r
+               $arr = $this->conn->GetArray(\r
+"select count(*),tracer \r
+       from $perf_table where sql1=$sqlq \r
+       group by tracer\r
+       order by 1 desc");\r
+               $s = '';\r
+               if ($arr) {\r
+                       $s .= '<h3>Scripts Affected</h3>';\r
+                       foreach($arr as $k) {\r
+                               $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';\r
+                       }\r
+               }\r
+               $this->conn->fnExecute = $saveE;\r
+               return $s;\r
+       }\r
+\r
+       /* \r
+               Explain Plan for $sql.\r
+               If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the \r
+                       actual sql.\r
+       */\r
+       function Explain($sql,$partial=false)\r
+       {       \r
+               return false;\r
+       }\r
+       \r
+       function InvalidSQL($numsql = 10)\r
+       {\r
+       global $HTTP_GET_VARS;\r
+       \r
+               if (isset($HTTP_GET_VARS['sql'])) return;\r
+               $s = '<h3>Invalid SQL</h3>';\r
+               $saveE = $this->conn->fnExecute;\r
+               $this->conn->fnExecute = false;\r
+        $perf_table = adodb_perf::table();\r
+               $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);\r
+               $this->conn->fnExecute = $saveE;\r
+               if ($rs) {\r
+                       $s .= rs2html($rs,false,false,false,false);\r
+               } else\r
+                       return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
+               \r
+               return $s;\r
+       }\r
+\r
+       \r
+       /*\r
+               This script identifies the longest running SQL\r
+       */      \r
+       function _SuspiciousSQL($numsql = 10)\r
+       {\r
+               global $ADODB_FETCH_MODE,$HTTP_GET_VARS;\r
+               \r
+            $perf_table = adodb_perf::table();\r
+                       $saveE = $this->conn->fnExecute;\r
+                       $this->conn->fnExecute = false;\r
+                       \r
+                       if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) {\r
+                               $partial = !empty($HTTP_GET_VARS['part']);\r
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
+                       }\r
+                       \r
+                       if (isset($HTTP_GET_VARS['sql'])) return;\r
+                       $sql1 = $this->sql1;\r
+                       \r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       //$this->conn->debug=1;\r
+                       $rs =& $this->conn->SelectLimit(\r
+                       "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer\r
+                               from $perf_table\r
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')\r
+                               and (tracer is null or tracer not like 'ERROR:%')\r
+                               group by sql1\r
+                               order by 1 desc",$numsql);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       $this->conn->fnExecute = $saveE;\r
+                       \r
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
+                       $s = "<h3>Suspicious SQL</h3>\r
+<font size=1>The following SQL have high average execution times</font><br>\r
+<table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";\r
+                       $max = $this->maxLength;\r
+                       while (!$rs->EOF) {\r
+                               $sql = $rs->fields[1];\r
+                               $raw = urlencode($sql);\r
+                               if (strlen($raw)>$max-100) {\r
+                                       $sql2 = substr($sql,0,$max-500);\r
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);\r
+                               }\r
+                               $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";\r
+                               $suffix = "</a>";\r
+                               if ($this->explain == false || strlen($prefix)>$max) {\r
+                                       $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';\r
+                                       $prefix = '';\r
+                               }\r
+                               $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".\r
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";\r
+                               $rs->MoveNext();\r
+                       }\r
+                       return $s."</table>";\r
+               \r
+       }\r
+       \r
+       function CheckMemory()\r
+       {\r
+               return '';\r
+       }\r
+       \r
+       \r
+       function SuspiciousSQL($numsql=10)\r
+       {\r
+               return adodb_perf::_SuspiciousSQL($numsql);\r
+       }\r
+\r
+       function ExpensiveSQL($numsql=10)\r
+       {\r
+               return adodb_perf::_ExpensiveSQL($numsql);\r
+       }\r
+\r
+       \r
+       /*\r
+               This reports the percentage of load on the instance due to the most \r
+               expensive few SQL statements. Tuning these statements can often \r
+               make huge improvements in overall system performance. \r
+       */\r
+       function _ExpensiveSQL($numsql = 10)\r
+       {\r
+               global $HTTP_GET_VARS,$ADODB_FETCH_MODE;\r
+               \r
+            $perf_table = adodb_perf::table();\r
+                       $saveE = $this->conn->fnExecute;\r
+                       $this->conn->fnExecute = false;\r
+                       \r
+                       if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) {\r
+                               $partial = !empty($HTTP_GET_VARS['part']);\r
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
+                       }\r
+                       \r
+                       if (isset($HTTP_GET_VARS['sql'])) return;\r
+                       \r
+                       $sql1 = $this->sql1;\r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       $rs =& $this->conn->SelectLimit(\r
+                       "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer\r
+                               from $perf_table\r
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')\r
+                               and (tracer is null or tracer not like 'ERROR:%')\r
+                               group by sql1\r
+                               order by 1 desc",$numsql);\r
+                       \r
+                       $this->conn->fnExecute = $saveE;\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
+                       $s = "<h3>Expensive SQL</h3>\r
+<font size=1>Tuning the following SQL will reduce the server load substantially</font><br>\r
+<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";\r
+                       $max = $this->maxLength;\r
+                       while (!$rs->EOF) {\r
+                               $sql = $rs->fields[1];\r
+                               $raw = urlencode($sql);\r
+                               if (strlen($raw)>$max-100) {\r
+                                       $sql2 = substr($sql,0,$max-500);\r
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);\r
+                               }\r
+                               $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";\r
+                               $suffix = "</a>";\r
+                               if($this->explain == false || strlen($prefix>$max)) {\r
+                                       $prefix = '';\r
+                                       $suffix = '';\r
+                               }\r
+                               $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".\r
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";\r
+                               $rs->MoveNext();\r
+                       }\r
+                       return $s."</table>";\r
+       }\r
+       \r
+       /*\r
+               Raw function to return parameter value from $settings.\r
+       */\r
+       function DBParameter($param)\r
+       {\r
+               if (empty($this->settings[$param])) return false;\r
+               $sql = $this->settings[$param][1];\r
+               return $this->_DBParameter($sql);\r
+       }\r
+       \r
+       /*\r
+               Raw function returning array of poll paramters\r
+       */\r
+       function &PollParameters()\r
+       {\r
+               $arr[0] = (float)$this->DBParameter('data cache hit ratio');\r
+               $arr[1] = (float)$this->DBParameter('data reads');\r
+               $arr[2] = (float)$this->DBParameter('data writes');\r
+               $arr[3] = (integer) $this->DBParameter('current connections');\r
+               return $arr;\r
+       }\r
+       \r
+       /*\r
+               Low-level Get Database Parameter\r
+       */\r
+       function _DBParameter($sql)\r
+       {\r
+               $savelog = $this->conn->LogSQL(false);\r
+               if (is_array($sql)) {\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+                       $sql1 = $sql[0];\r
+                       $key = $sql[1];\r
+                       if (sizeof($sql)>2) $pos = $sql[2];\r
+                       else $pos = 1;\r
+                       if (sizeof($sql)>3) $coef = $sql[3];\r
+                       else $coef = false;\r
+                       $ret = false;\r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       $rs = $this->conn->Execute($sql1);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       if ($rs) {\r
+                               while (!$rs->EOF) {\r
+                                       $keyf = reset($rs->fields);\r
+                                       if (trim($keyf) == $key) {\r
+                                               $ret = $rs->fields[$pos];\r
+                                               if ($coef) $ret *= $coef;\r
+                                               break;\r
+                                       }\r
+                                       $rs->MoveNext();\r
+                               }\r
+                               $rs->Close();\r
+                       }\r
+                       $this->conn->LogSQL($savelog);\r
+                       return $ret;\r
+               } else {\r
+                       if (strncmp($sql,'=',1) == 0) {\r
+                               $fn = substr($sql,1);\r
+                               return $this->$fn();\r
+                       }\r
+                       $sql = str_replace('$DATABASE',$this->conn->database,$sql);\r
+                       $ret = $this->conn->GetOne($sql);\r
+                       $this->conn->LogSQL($savelog);\r
+                       \r
+                       return $ret;\r
+               }\r
+       }\r
+       \r
+       /*\r
+               Warn if cache ratio falls below threshold. Displayed in "Description" column.\r
+       */\r
+       function WarnCacheRatio($val)\r
+       {\r
+               if ($val < $this->warnRatio) \r
+                        return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';\r
+               else return '';\r
+       }\r
+       \r
+       /***********************************************************************************************/\r
+       //                                    HIGH LEVEL UI FUNCTIONS\r
+       /***********************************************************************************************/\r
+\r
+       \r
+       function UI($pollsecs=5)\r
+       {\r
+       global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS;\r
+       \r
+    $perf_table = adodb_perf::table();\r
+       $conn = $this->conn;\r
+       \r
+       $app = $conn->host;\r
+       if ($conn->host && $conn->database) $app .= ', db=';\r
+       $app .= $conn->database;\r
+       \r
+       if ($app) $app .= ', ';\r
+       $savelog = $this->conn->LogSQL(false);  \r
+       $info = $conn->ServerInfo();\r
+       if (isset($HTTP_GET_VARS['clearsql'])) {\r
+               $this->conn->Execute("delete from $perf_table");\r
+       }\r
+       $this->conn->LogSQL($savelog);\r
+       \r
+       // magic quotes\r
+       \r
+       if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) {\r
+               $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']);\r
+       }\r
+       \r
+       if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;\r
+       else  $nsql = $_SESSION['ADODB_PERF_SQL'];\r
+       \r
+       $app .= $info['description'];\r
+       \r
+       \r
+       if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do'];\r
+       else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do'];\r
+        else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql';\r
+        else $do = 'stats';\r
+        \r
+       if (isset($HTTP_GET_VARS['nsql'])) {\r
+               if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql'];\r
+       }\r
+       echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";\r
+       if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";\r
+       else $form = "<td>&nbsp;</td>";\r
+       \r
+       $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');\r
+       \r
+       if  (empty($HTTP_GET_VARS['hidem']))\r
+       echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>\r
+       <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>\r
+       <a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>\r
+        &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",\r
+        $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',\r
+        "$form",\r
+        "</tr></table>";\r
+\r
+        \r
+               switch ($do) {\r
+               default:\r
+               case 'stats':\r
+                       echo $this->HealthCheck();\r
+                       //$this->conn->debug=1;\r
+                       echo $this->CheckMemory();\r
+                       break;\r
+               case 'poll':\r
+                       echo "<iframe width=720 height=80% \r
+                               src=\"{$HTTP_SERVER_VARS['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";\r
+                       break;\r
+               case 'poll2':\r
+                       echo "<pre>";\r
+                       $this->Poll($pollsecs);\r
+                       break;\r
+               \r
+               case 'dosql':\r
+                       if (!$allowsql) break;\r
+                       \r
+                       $this->DoSQLForm();\r
+                       break;\r
+               case 'viewsql':\r
+                       if (empty($HTTP_GET_VARS['hidem']))\r
+                               echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";\r
+                       echo($this->SuspiciousSQL($nsql));\r
+                       echo($this->ExpensiveSQL($nsql));\r
+                       echo($this->InvalidSQL($nsql));\r
+                       break;\r
+               case 'tables': \r
+                       echo $this->Tables(); break;\r
+               }\r
+               global $ADODB_vers;\r
+               echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";\r
+       }\r
+       \r
+       /*\r
+               Runs in infinite loop, returning real-time statistics\r
+       */\r
+       function Poll($secs=5)\r
+       {\r
+               $this->conn->fnExecute = false;\r
+               //$this->conn->debug=1;\r
+               if ($secs <= 1) $secs = 1;\r
+               echo "Accumulating statistics, every $secs seconds...\n";flush();\r
+               $arro =& $this->PollParameters();\r
+               $cnt = 0;\r
+               set_time_limit(0);\r
+               sleep($secs);\r
+               while (1) {\r
+                       $arr =& $this->PollParameters();\r
+                       \r
+                       $hits   = sprintf('%2.2f',$arr[0]);\r
+                       $reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);\r
+                       $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);\r
+                       $sess = sprintf('%5d',$arr[3]);\r
+                       \r
+                       $load = $this->CPULoad();\r
+                       if ($load !== false) {\r
+                               $oslabel = 'WS-CPU%';\r
+                               $osval = sprintf(" %2.1f  ",(float) $load);\r
+                       }else {\r
+                               $oslabel = '';\r
+                               $osval = '';\r
+                       }\r
+                       if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n"; \r
+                       $cnt += 1;\r
+                       echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";\r
+                       flush();\r
+                       \r
+                       sleep($secs);\r
+                       $arro = $arr;\r
+               }\r
+       }\r
+       \r
+       /*\r
+               Returns basic health check in a command line interface\r
+       */\r
+       function HealthCheckCLI()\r
+       {\r
+               return $this->HealthCheck(true);\r
+       }\r
+       \r
+               \r
+       /*\r
+               Returns basic health check as HTML\r
+       */\r
+       function HealthCheck($cli=false)\r
+       {\r
+               $saveE = $this->conn->fnExecute;\r
+               $this->conn->fnExecute = false; \r
+               if ($cli) $html = '';\r
+               else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;\r
+               \r
+               $oldc = false;\r
+               $bgc = '';\r
+               foreach($this->settings as $name => $arr) {\r
+                       if ($arr === false) break;\r
+                       \r
+                       if (!is_string($name)) {\r
+                               if ($cli) $html .= " -- $arr -- \n";\r
+                               else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";\r
+                               continue;\r
+                       }\r
+                       \r
+                       if (!is_array($arr)) break;\r
+                       $category = $arr[0];\r
+                       $how = $arr[1];\r
+                       if (sizeof($arr)>2) $desc = $arr[2];\r
+                       else $desc = ' &nbsp; ';\r
+                       \r
+                       \r
+                       if ($category == 'HIDE') continue;\r
+                       \r
+                       $val = $this->_DBParameter($how);\r
+                       \r
+                       if ($desc && strncmp($desc,"=",1) === 0) {\r
+                               $fn = substr($desc,1);\r
+                               $desc = $this->$fn($val);\r
+                       }\r
+                       \r
+                       if ($val === false) {\r
+                               $m = $this->conn->ErrorMsg();\r
+                               $val = "Error: $m"; \r
+                       } else {\r
+                               if (is_numeric($val) && $val >= 256*1024) {\r
+                                       if ($val % (1024*1024) == 0) {\r
+                                               $val /= (1024*1024);\r
+                                               $val .= 'M';\r
+                                       } else if ($val % 1024 == 0) {\r
+                                               $val /= 1024;\r
+                                               $val .= 'K';\r
+                                       }\r
+                                       //$val = htmlspecialchars($val);\r
+                               }\r
+                       }\r
+                       if ($category != $oldc) {\r
+                               $oldc = $category;\r
+                               //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;\r
+                       }\r
+                       if (strlen($desc)==0) $desc = '&nbsp;';\r
+                       if (strlen($val)==0) $val = '&nbsp;';\r
+                       if ($cli) {\r
+                               $html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));\r
+                               \r
+                       }else {\r
+                               $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";\r
+                       }\r
+               }\r
+               \r
+               if (!$cli) $html .= "</table>\n";\r
+               $this->conn->fnExecute = $saveE;\r
+                       \r
+               return $html;   \r
+       }\r
+       \r
+       function Tables($orderby='1')\r
+       {\r
+               if (!$this->tablesSQL) return false;\r
+               \r
+               $savelog = $this->conn->LogSQL(false);\r
+               $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);\r
+               $this->conn->LogSQL($savelog);\r
+               $html = rs2html($rs,false,false,false,false);\r
+               return $html;\r
+       }\r
+       \r
+\r
+       function CreateLogTable()\r
+       {\r
+               if (!$this->createTableSQL) return false;\r
+               \r
+               $savelog = $this->conn->LogSQL(false);\r
+               $ok = $this->conn->Execute($this->createTableSQL);\r
+               $this->conn->LogSQL($savelog);\r
+               return ($ok) ? true : false;\r
+       }\r
+       \r
+       function DoSQLForm()\r
+       {\r
+       global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS;\r
+       \r
+               $HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS);\r
+               \r
+               $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];\r
+               $sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : '';\r
+\r
+               if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows'];\r
+               else $rows = 3;\r
+               \r
+               if (isset($HTTP_VARS['SMALLER'])) {\r
+                       $rows /= 2;\r
+                       if ($rows < 3) $rows = 3;\r
+                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;\r
+               }\r
+               if (isset($HTTP_VARS['BIGGER'])) {\r
+                       $rows *= 2;\r
+                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;\r
+               }\r
+               \r
+?>\r
+\r
+<form method="POST" action="<?php echo $PHP_SELF ?>">\r
+<table><tr>\r
+<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">\r
+</td>\r
+<td align=right>\r
+<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>\r
+</td></tr>\r
+  <tr>\r
+  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>\r
+  </td>\r
+  </tr>\r
+ </table>\r
+</form>\r
+\r
+<?php\r
+               if (!isset($HTTP_VARS['sql'])) return;\r
+               \r
+               $sql = $this->undomq(trim($sql));\r
+               if (substr($sql,strlen($sql)-1) === ';') {\r
+                       $print = true;\r
+                       $sqla = $this->SplitSQL($sql);\r
+               } else  {\r
+                       $print = false;\r
+                       $sqla = array($sql);\r
+               }\r
+               foreach($sqla as $sqls) {\r
+\r
+                       if (!$sqls) continue;\r
+                       \r
+                       if ($print) {\r
+                               print "<p>".htmlspecialchars($sqls)."</p>";\r
+                               flush();\r
+                       }\r
+                       $savelog = $this->conn->LogSQL(false);\r
+                       $rs = $this->conn->Execute($sqls);\r
+                       $this->conn->LogSQL($savelog);\r
+                       if ($rs && is_object($rs) && !$rs->EOF) {\r
+                               rs2html($rs);\r
+                               while ($rs->NextRecordSet()) {\r
+                                       print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";\r
+                                       rs2html($rs);\r
+                               }\r
+                       } else {\r
+                               $e1 = (integer) $this->conn->ErrorNo();\r
+                               $e2 = $this->conn->ErrorMsg();\r
+                               if (($e1) || ($e2)) {\r
+                                       if (empty($e1)) $e1 = '-1'; // postgresql fix\r
+                                       print ' &nbsp; '.$e1.': '.$e2;\r
+                               } else {\r
+                                       print "<p>No Recordset returned<br></p>";\r
+                               }\r
+                       }\r
+               } // foreach\r
+       }\r
+       \r
+       function SplitSQL($sql)\r
+       {\r
+               $arr = explode(';',$sql);\r
+               return $arr;\r
+       }\r
+       \r
+       function undomq(&$m) \r
+       {\r
+       if (get_magic_quotes_gpc()) {\r
+               // undo the damage\r
+               $m = str_replace('\\\\','\\',$m);\r
+               $m = str_replace('\"','"',$m);\r
+               $m = str_replace('\\\'','\'',$m);\r
+       }\r
+       return $m;\r
+}\r
+}\r
+\r
+\r
+\r
 ?>
\ No newline at end of file
index 766f00683e914bda03ba0d9a0f6cea9f04e93cf3..1524d4fa026d9ad7accf7892a474884210402a95 100644 (file)
@@ -1,16 +1,16 @@
-<?php
-
-/*
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-
-class ADODB_BASE_RS {
-}
-
+<?php\r
+\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  \r
+  Set tabs to 4.\r
+*/\r
+\r
+\r
+class ADODB_BASE_RS {\r
+}\r
+\r
 ?>
\ No newline at end of file
index 15545f12fe1a6f8997205b0b12e9f02d9855fe50..fd7c1fb0bb15cc0211661f4b307146a6e97092a7 100644 (file)
@@ -174,6 +174,43 @@ c. Implement daylight savings, which looks awfully complicated, see
 \r
 \r
 CHANGELOG\r
+- 23 June 2004 0.14\r
+\r
+Allow you to define your own daylights savings function, adodb_daylight_sv.\r
+If the function is defined (somewhere in an include), then you can correct for daylights savings.\r
+\r
+In this example, we apply daylights savings in June or July, adding one hour. This is extremely\r
+unrealistic as it does not take into account time-zone, geographic location, current year.\r
+\r
+function adodb_daylight_sv(&$arr, $is_gmt)\r
+{\r
+       if ($is_gmt) return;\r
+       $m = $arr['mon'];\r
+       if ($m == 6 || $m == 7) $arr['hours'] += 1;\r
+}\r
+\r
+This is only called by adodb_date() and not by adodb_mktime(). \r
+\r
+The format of $arr is\r
+Array ( \r
+   [seconds] => 0 \r
+   [minutes] => 0 \r
+   [hours] => 0 \r
+   [mday] => 1      # day of month, eg 1st day of the month\r
+   [mon] => 2       # month (eg. Feb)\r
+   [year] => 2102 \r
+   [yday] => 31     # days in current year\r
+   [leap] =>        # true if leap year\r
+   [ndays] => 28    # no of days in current month\r
+   ) \r
+   \r
+\r
+- 28 Apr 2004 0.13\r
+Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov.\r
+\r
+- 20 Mar 2004 0.12\r
+Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32.\r
+\r
 - 26 Oct 2003 0.11\r
 Because of daylight savings problems (some systems apply daylight savings to \r
 January!!!), changed adodb_get_gmt_diff() to ignore daylight savings.\r
@@ -234,7 +271,7 @@ First implementation.
 /*\r
        Version Number\r
 */\r
-define('ADODB_DATE_VERSION',0.11);\r
+define('ADODB_DATE_VERSION',0.14);\r
 \r
 /*\r
        We check for Windows as only +ve ints are accepted as dates on Windows.\r
@@ -270,12 +307,19 @@ function adodb_date_test()
        \r
        error_reporting(E_ALL);\r
        print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION. "</h4>";\r
-       set_time_limit(0);\r
+       @set_time_limit(0);\r
        $fail = false;\r
        \r
        // This flag disables calling of PHP native functions, so we can properly test the code\r
        if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);\r
        \r
+       $t = adodb_mktime(0,0,0,6,1,2102);\r
+       if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';\r
+       \r
+       $t = adodb_mktime(0,0,0,2,1,2102);\r
+       if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';\r
+       \r
+       \r
        print "<p>Testing gregorian <=> julian conversion<p>";\r
        $t = adodb_mktime(0,0,0,10,11,1492);\r
        //http://www.holidayorigins.com/html/columbus_day.html - Friday check\r
@@ -541,6 +585,9 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
        $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);\r
        $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);\r
        \r
+       $d366 = $_day_power * 366;\r
+       $d365 = $_day_power * 365;\r
+       \r
        if ($d < 0) {\r
                $origd = $d;\r
                // The valid range of a 32bit signed timestamp is typically from \r
@@ -548,10 +595,9 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
                for ($a = 1970 ; --$a >= 0;) {\r
                        $lastd = $d;\r
                        \r
-                       if ($leaf = _adodb_is_leap_year($a)) {\r
-                               $d += $_day_power * 366;\r
-                       } else\r
-                               $d += $_day_power * 365;\r
+                       if ($leaf = _adodb_is_leap_year($a)) $d += $d366;\r
+                       else $d += $d365;\r
+                       \r
                        if ($d >= 0) {\r
                                $year = $a;\r
                                break;\r
@@ -579,14 +625,11 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
                $hour = floor($d/$_hour_power);\r
        \r
        } else {\r
-       \r
                for ($a = 1970 ;; $a++) {\r
                        $lastd = $d;\r
                        \r
-                       if ($leaf = _adodb_is_leap_year($a)) {\r
-                               $d -= $_day_power * 366;\r
-                       } else\r
-                               $d -= $_day_power * 365;\r
+                       if ($leaf = _adodb_is_leap_year($a)) $d -= $d366;\r
+                       else $d -= $d365;\r
                        if ($d < 0) {\r
                                $year = $a;\r
                                break;\r
@@ -598,7 +641,7 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
                for ($a = 1 ; $a <= 12; $a++) {\r
                        $lastd = $d;\r
                        $d -= $mtab[$a] * $_day_power;\r
-                       if ($d <= 0) {\r
+                       if ($d < 0) {\r
                                $month = $a;\r
                                $ndays = $mtab[$a];\r
                                break;\r
@@ -650,6 +693,7 @@ function adodb_gmdate($fmt,$d=false)
        return adodb_date($fmt,$d,true);\r
 }\r
 \r
+// accepts unix timestamp and iso date format in $d\r
 function adodb_date2($fmt, $d=false, $is_gmt=false)\r
 {\r
        if ($d !== false) {\r
@@ -667,21 +711,25 @@ function adodb_date2($fmt, $d=false, $is_gmt=false)
        return adodb_date($fmt,$d,$is_gmt);\r
 }\r
 \r
+\r
 /**\r
        Return formatted date based on timestamp $d\r
 */\r
 function adodb_date($fmt,$d=false,$is_gmt=false)\r
 {\r
-       if ($d === false) return date($fmt);\r
+       if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt);\r
        if (!defined('ADODB_TEST_DATES')) {\r
                if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range\r
                        if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer\r
-                               return @date($fmt,$d);\r
+                               return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d);\r
+\r
                }\r
        }\r
        $_day_power = 86400;\r
        \r
        $arr = _adodb_getdate($d,true,$is_gmt);\r
+       if (function_exists('adodb_daylight_sv')) adodb_daylight_sv($arr, $is_gmt);\r
+       \r
        $year = $arr['year'];\r
        $month = $arr['mon'];\r
        $day = $arr['mday'];\r
@@ -812,6 +860,8 @@ function adodb_gmmktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false)
 /**\r
        Return a timestamp given a local time. Originally by jackbbs.\r
        Note that $is_dst is not implemented and is ignored.\r
+       \r
+       Not a very fast algorithm - O(n) operation. Could be optimized to O(1).\r
 */\r
 function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) \r
 {\r
@@ -820,7 +870,9 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false)
                // 1 Jan 1970 could generate negative timestamp, which is illegal\r
                if (!defined('ADODB_NO_NEGATIVE_TS') || ($year >= 1971)) \r
                        if (1901 < $year && $year < 2038)\r
-                               return @mktime($hr,$min,$sec,$mon,$day,$year);\r
+                               return $is_gmt?\r
+                                       @gmmktime($hr,$min,$sec,$mon,$day,$year):\r
+                                       @mktime($hr,$min,$sec,$mon,$day,$year);\r
        }\r
        \r
        $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff();\r
index ac2b4a857de50ef0307f6403e74c29c327a46f5a..d3239dbc32b2687a01b5d322e20b63f24ad33fd4 100644 (file)
Binary files a/lib/adodb/adodb-time.zip and b/lib/adodb/adodb-time.zip differ
index 4a0efd204e95826d4338743f5e0c815a237bfc51..1bcba0126798ec9099847beaae2c36c1621829b2 100644 (file)
-<?php 
-/*
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com/adodb
- * 
- * This is the main include file for ADOdb.
- * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
- *
- * The ADOdb files are formatted so that doxygen can be used to generate documentation.
- * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
- */
-
-/**
-       \mainpage       
-       
-        @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.
-
-       Released under both BSD license and Lesser GPL library license. You can choose which license
-       you prefer.
-       
-       PHP's database access functions are not standardised. This creates a need for a database 
-       class library to hide the differences between the different database API's (encapsulate 
-       the differences) so we can easily switch databases.
-
-       We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
-       Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
-       ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
-       other databases via ODBC. 
-        
-       Latest Download at http://php.weblogs.com/adodb<br>
-       Manual is at http://php.weblogs.com/adodb_manual
-         
- */
- if (!defined('_ADODB_LAYER')) {
-       define('_ADODB_LAYER',1);
-       
-       //==============================================================================================        
-       // CONSTANT DEFINITIONS
-       //==============================================================================================        
-
-
-       /** 
-        * Set ADODB_DIR to the directory where this file resides...
-        * This constant was formerly called $ADODB_RootPath
-        */
-       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
-       
-       //==============================================================================================        
-       // GLOBAL VARIABLES
-       //==============================================================================================        
-
-       GLOBAL 
-               $ADODB_vers,            // database version
-               $ADODB_COUNTRECS,       // count number of records returned - slows down query
-               $ADODB_CACHE_DIR,       // directory to cache recordsets
-               $ADODB_EXTENSION,   // ADODB extension installed
-               $ADODB_COMPAT_PATCH, // 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...
-       
-       //==============================================================================================        
-       // GLOBAL SETUP
-       //==============================================================================================        
-       
-       $ADODB_EXTENSION = defined('ADODB_EXTENSION');
-       if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
-               
-               define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
-       
-       // allow [ ] @ ` " and . in table names
-               define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');
-       
-       // prefetching used by oracle
-               if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
-       
-       
-       /*
-       Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
-       This currently works only with mssql, odbc, oci8po and ibase derived drivers.
-       
-               0 = assoc lowercase field names. $rs->fields['orderid']
-               1 = assoc uppercase field names. $rs->fields['ORDERID']
-               2 = use native-case field names. $rs->fields['OrderID']
-       */
-       
-               define('ADODB_FETCH_DEFAULT',0);
-               define('ADODB_FETCH_NUM',1);
-               define('ADODB_FETCH_ASSOC',2);
-               define('ADODB_FETCH_BOTH',3);
-               
-               if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
-       
-               if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {
-                       define('ADODB_PHPVER',0x4300);
-               } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {
-                       define('ADODB_PHPVER',0x4200);
-               } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
-                       define('ADODB_PHPVER',0x4050);
-               } else {
-                       define('ADODB_PHPVER',0x4000);
-               }
-       }
-       
-       //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
-       
-       
-       /**
-               Accepts $src and $dest arrays, replacing string $data
-       */
-       function ADODB_str_replace($src, $dest, $data)
-       {
-               if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
-               
-               $s = reset($src);
-               $d = reset($dest);
-               while ($s !== false) {
-                       $data = str_replace($s,$d,$data);
-                       $s = next($src);
-                       $d = next($dest);
-               }
-               return $data;
-       }
-       
-       function ADODB_Setup()
-       {
-       GLOBAL 
-               $ADODB_vers,            // database version
-               $ADODB_COUNTRECS,       // count number of records returned - slows down query
-               $ADODB_CACHE_DIR,       // directory to cache recordsets
-               $ADODB_FETCH_MODE;
-               
-               $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
-               
-               if (!isset($ADODB_CACHE_DIR)) {
-                       $ADODB_CACHE_DIR = '/tmp';
-               } else {
-                       // do not accept url based paths, eg. http:/ or ftp:/
-                       if (strpos($ADODB_CACHE_DIR,'://') !== false) 
-                               die("Illegal path http:// or ftp://");
-               }
-               
-                       
-               // Initialize random number generator for randomizing cache flushes
-               srand(((double)microtime())*1000000);
-               
-               /**
-                * ADODB version as a string.
-                */
-               $ADODB_vers = 'V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
-       
-               /**
-                * Determines whether recordset->RecordCount() is used. 
-                * Set to false for highest performance -- RecordCount() will always return -1 then
-                * for databases that provide "virtual" recordcounts...
-                */
-               if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; 
-       }
-       
-       
-       //==============================================================================================        
-       // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
-       //==============================================================================================        
-       
-       ADODB_Setup();
-
-       //==============================================================================================        
-       // CLASS ADOFieldObject
-       //==============================================================================================        
-       /**
-        * Helper class for FetchFields -- holds info on a column
-        */
-       class ADOFieldObject { 
-               var $name = '';
-               var $max_length=0;
-               var $type="";
-
-               // additional fields by dannym... (danny_milo@yahoo.com)
-               var $not_null = false; 
-               // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
-               // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
-
-               var $has_default = false; // this one I have done only in mysql and postgres for now ... 
-                       // others to come (dannym)
-               var $default_value; // default, if any, and supported. Check has_default first.
-       }
-       
-
-       
-       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
-       {
-               //print "Errorno ($fn errno=$errno m=$errmsg) ";
-               $thisConnection->_transOK = false;
-               if ($thisConnection->_oldRaiseFn) {
-                       $fn = $thisConnection->_oldRaiseFn;
-                       $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
-               }
-       }
-       
-       //==============================================================================================        
-       // CLASS ADOConnection
-       //==============================================================================================        
-       
-       /**
-        * Connection object. For connecting to databases, and executing queries.
-        */ 
-       class ADOConnection {
-       //
-       // PUBLIC VARS 
-       //
-       var $dataProvider = 'native';
-       var $databaseType = '';         /// RDBMS currently in use, eg. odbc, mysql, mssql                                      
-       var $database = '';                     /// Name of database to be used.        
-       var $host = '';                         /// The hostname of the database server 
-       var $user = '';                         /// The username which is used to connect to the database server. 
-       var $password = '';             /// Password for the username. For security, we no longer store it.
-       var $debug = false;             /// if set to true will output sql statements
-       var $maxblobsize = 256000;      /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
-       var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase    
-       var $substr = 'substr';         /// substring operator
-       var $length = 'length';         /// string length operator
-       var $random = 'rand()';         /// random function
-       var $upperCase = false;         /// uppercase function
-       var $fmtDate = "'Y-m-d'";       /// used by DBDate() as the default date format used by the database
-       var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
-       var $true = '1';                        /// string that represents TRUE for a database
-       var $false = '0';                       /// string that represents FALSE for a database
-       var $replaceQuote = "\\'";      /// string to use to replace quotes
-       var $nameQuote = '"';           /// string to use to quote identifiers and names
-       var $charSet=false;             /// character set to use - only for interbase
-       var $metaDatabasesSQL = '';
-       var $metaTablesSQL = '';
-       var $uniqueOrderBy = false; /// All order by columns have to be unique
-       var $emptyDate = '&nbsp;';
-       var $emptyTimeStamp = '&nbsp;';
-       var $lastInsID = false;
-       //--
-       var $hasInsertID = false;               /// supports autoincrement ID?
-       var $hasAffectedRows = false;   /// supports affected rows for update/delete?
-       var $hasTop = false;                    /// support mssql/access SELECT TOP 10 * FROM TABLE
-       var $hasLimit = false;                  /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
-       var $readOnly = false;                  /// this is a readonly database - used by phpLens
-       var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards
-       var $hasGenID = false;          /// can generate sequences using GenID();
-       var $hasTransactions = true; /// has transactions
-       //--
-       var $genID = 0;                         /// sequence id used by GenID();
-       var $raiseErrorFn = false;      /// error function to call
-       var $isoDates = false; /// accepts dates in ISO format
-       var $cacheSecs = 3600; /// cache for 1 hour
-       var $sysDate = false; /// name of function that returns the current date
-       var $sysTimeStamp = false; /// name of function that returns the current timestamp
-       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 ' '
-       var $numCacheHits = 0; 
-       var $numCacheMisses = 0;
-       var $pageExecuteCountRows = true;
-       var $uniqueSort = false; /// indicates that all fields in order by must be unique
-       var $leftOuter = false; /// operator to use for left outer join in WHERE clause
-       var $rightOuter = false; /// operator to use for right outer join in WHERE clause
-       var $ansiOuter = false; /// whether ansi outer join syntax supported
-       var $autoRollback = false; // autoRollback on PConnect().
-       var $poorAffectedRows = false; // affectedRows not working or unreliable
-       
-       var $fnExecute = false;
-       var $fnCacheExecute = false;
-       var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
-       var $rsPrefix = "ADORecordSet_";
-       
-       var $autoCommit = true;         /// do not modify this yourself - actually private
-       var $transOff = 0;                      /// temporarily disable transactions
-       var $transCnt = 0;                      /// count of nested transactions
-       
-       var $fetchMode=false;
-        //
-        // PRIVATE VARS
-        //
-       var $_oldRaiseFn =  false;
-       var $_transOK = null;
-       var $_connectionID      = false;        /// The returned link identifier whenever a successful database connection is made.     
-       var $_errorMsg = false;         /// A variable which was used to keep the returned last error message.  The value will
-                                                               /// then returned by the errorMsg() function    
-       var $_errorCode = false;        /// Last error code, not guaranteed to be used - only by oci8                                   
-       var $_queryID = false;          /// This variable keeps the last created result link identifier
-       
-       var $_isPersistentConnection = false;   /// A boolean variable to state whether its a persistent connection or normal connection.       */
-       var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
-       var $_evalAll = false;
-       var $_affected = false;
-       var $_logsql = false;
-       
-
-       
-       /**
-        * Constructor
-        */
-       function ADOConnection()                        
-       {
-               die('Virtual Class -- cannot instantiate');
-       }
-       
-       /**
-               Get server version info...
-               
-               @returns An array with 2 elements: $arr['string'] is the description string, 
-                       and $arr[version] is the version (also a string).
-       */
-       function ServerInfo()
-       {
-               return array('description' => '', 'version' => '');
-       }
-       
-       function _findvers($str)
-       {
-               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
-               else return '';
-       }
-       
-       /**
-       * 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)
-       {
-       global $HTTP_SERVER_VARS,$ADODB_FLUSH;
-       
-               if (defined('ADODB_OUTP')) {
-                       $fn = ADODB_OUTP;
-                       $fn($msg,$newline);
-                       return;
-               }
-               
-               if ($newline) $msg .= "<br>\n";
-               
-               if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;
-               else echo strip_tags($msg);
-               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  dp not flush if output buffering enabled - useless - thx to Jesse Mullan 
-               
-       }
-       
-       /**
-        * Connect to database
-        *
-        * @param [argHostname]         Host to connect to
-        * @param [argUsername]         Userid to login
-        * @param [argPassword]         Associated password
-        * @param [argDatabaseName]     database
-        * @param [forceNew]            force new connection
-        *
-        * @return true or false
-        */       
-       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) 
-       {
-               if ($argHostname != "") $this->host = $argHostname;
-               if ($argUsername != "") $this->user = $argUsername;
-               if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
-               if ($argDatabaseName != "") $this->database = $argDatabaseName;         
-               
-               $this->_isPersistentConnection = false; 
-               if ($fn = $this->raiseErrorFn) {
-                       if ($forceNew) {
-                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
-                       } else {
-                                if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
-                       }
-                       $err = $this->ErrorMsg();
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
-                       $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
-               } else {
-                       if ($forceNew) {
-                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
-                       } else {
-                               if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
-                       }
-               }
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
-               return false;
-       }       
-       
-        function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
-        {
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
-        }
-       
-       
-       /**
-        * Always force a new connection to database - currently only works with oracle
-        *
-        * @param [argHostname]         Host to connect to
-        * @param [argUsername]         Userid to login
-        * @param [argPassword]         Associated password
-        * @param [argDatabaseName]     database
-        *
-        * @return true or false
-        */       
-       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") 
-       {
-               return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
-       }
-       
-       /**
-        * Establish persistent connect to database
-        *
-        * @param [argHostname]         Host to connect to
-        * @param [argUsername]         Userid to login
-        * @param [argPassword]         Associated password
-        * @param [argDatabaseName]     database
-        *
-        * @return return true or false
-        */     
-       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 ($argDatabaseName != "") $this->database = $argDatabaseName;         
-                       
-               $this->_isPersistentConnection = true;  
-               
-               if ($fn = $this->raiseErrorFn) {
-                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
-                       $err = $this->ErrorMsg();
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
-                       $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
-               } else 
-                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
-
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
-               return false;
-       }
-
-       // Format date column in sql string given an input format that understands Y M D
-       function SQLDate($fmt, $col=false)
-       {       
-               if (!$col) $col = $this->sysDate;
-               return $col; // child class implement
-       }
-       
-       /**
-        * Should prepare the sql statement and return the stmt resource.
-        * For databases that do not support this, we return the $sql. To ensure
-        * compatibility with databases that do not support prepare:
-        *
-        *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
-        *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
-        *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
-        *
-        * @param sql   SQL to send to database
-        *
-        * @return return FALSE, or the prepared statement, or the original sql if
-        *                      if the database does not support prepare.
-        *
-        */     
-       function Prepare($sql)
-       {
-               return $sql;
-       }
-
-       /**
-        * Some databases, eg. mssql require a different function for preparing
-        * stored procedures. So we cannot use Prepare().
-        *
-        * Should prepare the stored procedure  and return the stmt resource.
-        * For databases that do not support this, we return the $sql. To ensure
-        * compatibility with databases that do not support prepare:
-        *
-        * @param sql   SQL to send to database
-        *
-        * @return return FALSE, or the prepared statement, or the original sql if
-        *                      if the database does not support prepare.
-        *
-        */     
-       function PrepareSP($sql,$param=false)
-       {
-               return $this->Prepare($sql,$param);
-       }
-       
-       /**
-       * PEAR DB Compat
-       */
-       function Quote($s)
-       {
-               return $this->qstr($s,false);
-       }
-       
-       /**
-        Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
-       */
-       function QMagic($s)
-       {
-               return $this->qstr($s,get_magic_quotes_gpc());
-       }
-
-       function q(&$s)
-       {
-               $s = $this->qstr($s,false);
-       }
-       
-       /**
-       * PEAR DB Compat - do not use internally. 
-       */
-       function ErrorNative()
-       {
-               return $this->ErrorNo();
-       }
-
-       
-   /**
-       * PEAR DB Compat - do not use internally. 
-       */
-       function nextId($seq_name)
-       {
-               return $this->GenID($seq_name);
-       }
-
-       /**
-       *        Lock a row, will escalate and lock the table if row locking not supported
-       *       will normally free the lock at the end of the transaction
-       *
-       *  @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)
-       {
-               return false;
-       }
-       
-       function CommitLock($table)
-       {
-               return $this->CommitTrans();
-       }
-       
-       function RollbackLock($table)
-       {
-               return $this->RollbackTrans();
-       }
-       
-       /**
-       * PEAR DB Compat - do not use internally. 
-       *
-       * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
-       *       for easy porting :-)
-       *
-       * @param mode   The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
-       * @returns              The previous fetch mode
-       */
-       function SetFetchMode($mode)
-       {       
-               $old = $this->fetchMode;
-               $this->fetchMode = $mode;
-               
-               if ($old === false) {
-               global $ADODB_FETCH_MODE;
-                       return $ADODB_FETCH_MODE;
-               }
-               return $old;
-       }
-       
-
-       /**
-       * PEAR DB Compat - do not use internally. 
-       */
-       function &Query($sql, $inputarr=false)
-       {
-               $rs = &$this->Execute($sql, $inputarr);
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
-               return $rs;
-       }
-
-       
-       /**
-       * PEAR DB Compat - do not use internally
-       */
-       function &LimitQuery($sql, $offset, $count, $params=false)
-       {
-               $rs = &$this->SelectLimit($sql, $count, $offset, $params); 
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
-               return $rs;
-       }
-
-       
-       /**
-       * PEAR DB Compat - do not use internally
-       */
-       function Disconnect()
-       {
-               return $this->Close();
-       }
-       
-       /*
-                Returns placeholder for parameter, eg.
-                $DB->Param('a')
-                
-                will return ':a' for Oracle, and '?' for most other databases...
-                
-                For databases that require positioned params, eg $1, $2, $3 for postgresql,
-                       pass in Param(false) before setting the first parameter.
-       */
-       function Param($name)
-       {
-               return '?';
-       }
-       
-       /*
-               InParameter and OutParameter are self-documenting versions of Parameter().
-       */
-       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
-       {
-               return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
-       }
-       
-       /*
-       */
-       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
-       {
-               return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
-       
-       }
-       
-       /* 
-       Usage in oracle
-               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
-               $db->Parameter($stmt,$id,'myid');
-               $db->Parameter($stmt,$group,'group',64);
-               $db->Execute();
-               
-               @param $stmt Statement returned by Prepare() or PrepareSP().
-               @param $var PHP variable to bind to
-               @param $name Name of stored procedure variable name to bind to.
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
-               @param [$maxLen] Holds an maximum length of the variable.
-               @param [$type] The data type of $var. Legal values depend on driver.
-
-       */
-       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
-       {
-               return false;
-       }
-       
-       /**
-               Improved method of initiating a transaction. Used together with CompleteTrans().
-               Advantages include:
-               
-               a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
-                  Only the outermost block is treated as a transaction.<br>
-               b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
-               c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
-                  are disabled, making it backward compatible.
-       */
-       function StartTrans($errfn = 'ADODB_TransMonitor')
-       {
-               if ($this->transOff > 0) {
-                       $this->transOff += 1;
-                       return;
-               }
-               
-               $this->_oldRaiseFn = $this->raiseErrorFn;
-               $this->raiseErrorFn = $errfn;
-               $this->_transOK = true;
-               
-               if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
-               $this->BeginTrans();
-               $this->transOff = 1;
-       }
-       
-       /**
-               Used together with StartTrans() to end a transaction. Monitors connection
-               for sql errors, and will commit or rollback as appropriate.
-               
-               @autoComplete if true, monitor sql errors and commit and rollback as appropriate, 
-               and if set to false force rollback even if no SQL error detected.
-               @returns true on commit, false on rollback.
-       */
-       function CompleteTrans($autoComplete = true)
-       {
-               if ($this->transOff > 1) {
-                       $this->transOff -= 1;
-                       return true;
-               }
-               $this->raiseErrorFn = $this->_oldRaiseFn;
-               
-               $this->transOff = 0;
-               if ($this->_transOK && $autoComplete) {
-                       if (!$this->CommitTrans()) {
-                               $this->_transOK = false;
-                               if ($this->debug) ADOConnection::outp("Smart Commit failed");
-                       } else
-                               if ($this->debug) ADOConnection::outp("Smart Commit occurred");
-               } else {
-                       $this->RollbackTrans();
-                       if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
-               }
-               
-               return $this->_transOK;
-       }
-       
-       /*
-               At the end of a StartTrans/CompleteTrans block, perform a rollback.
-       */
-       function FailTrans()
-       {
-               if ($this->debug) 
-                       if ($this->transOff == 0) {
-                               ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
-                       } else {
-                               ADOConnection::outp("FailTrans was called");
-                               adodb_backtrace();
-                       }
-               $this->_transOK = false;
-       }
-       
-       /**
-               Check if transaction has failed, only for Smart Transactions.
-       */
-       function HasFailedTrans()
-       {
-               if ($this->transOff > 0) return $this->_transOK == false;
-               return false;
-       }
-       
-       /**
-        * Execute SQL 
-        *
-        * @param sql           SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
-        * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.
-        * @return              RecordSet or false
-        */
-       function &Execute($sql,$inputarr=false) 
-       {
-               if ($this->fnExecute) {
-                       $fn = $this->fnExecute;
-                       $ret =& $fn($this,$sql,$inputarr);
-                       if (isset($ret)) return $ret;
-               }
-               if ($inputarr && is_array($inputarr)) {
-                       $element0 = reset($inputarr);
-                       # is_object check is because oci8 descriptors can be passed in
-                       $array_2d = is_array($element0) && !is_object(reset($element0));
-                       
-                       if (!is_array($sql) && !$this->_bindInputArray) {
-                               $sqlarr = explode('?',$sql);
-                                       
-                               if (!$array_2d) $inputarr = array($inputarr);
-                               foreach($inputarr as $arr) {
-                                       $sql = ''; $i = 0;
-                                       foreach($arr as $v) {
-                                               $sql .= $sqlarr[$i];
-                                               // from Ron Baldwin <ron.baldwin@sourceprose.com>
-                                               // Only quote string types      
-                                               if (gettype($v) == 'string')
-                                                       $sql .= $this->qstr($v);
-                                               else if ($v === null)
-                                                       $sql .= 'NULL';
-                                               else
-                                                       $sql .= $v;
-                                               $i += 1;
-                                       }
-                                       $sql .= $sqlarr[$i];
-                                       
-                                       if ($i+1 != sizeof($sqlarr))    
-                                               ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
-               
-                                       $ret =& $this->_Execute($sql,false);
-                                       if (!$ret) return $ret;
-                               }       
-                       } else {
-                               if ($array_2d) {
-                                       $stmt = $this->Prepare($sql);
-                                       foreach($inputarr as $arr) {
-                                               $ret =& $this->_Execute($stmt,$arr);
-                                               if (!$ret) return $ret;
-                                       }
-                               } else
-                                       $ret =& $this->_Execute($sql,$inputarr);
-                       }
-               } else {
-                       $ret =& $this->_Execute($sql,false);
-               }
-
-               return $ret;
-       }
-       
-       function& _Execute($sql,$inputarr=false)
-       {
-               // debug version of query
-               if ($this->debug) {
-               global $HTTP_SERVER_VARS;
-                       $ss = '';
-                       if ($inputarr) {
-                               foreach($inputarr as $kk=>$vv) {
-                                       if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
-                                       $ss .= "($kk=>'$vv') ";
-                               }
-                               $ss = "[ $ss ]";
-                       }
-                       $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
-                       
-                       // check if running from browser or command-line
-                       $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
-                       
-                       if ($inBrowser)
-                               if ($this->debug === -1)
-                               ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
-                               else ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);
-                       else
-                               ADOConnection::outp(  "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
-                       
-                       $this->_queryID = $this->_query($sql,$inputarr);
-                       /* 
-                               Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
-                               because ErrorNo() calls Execute('SELECT @ERROR'), causing recure
-                       */
-                       if ($this->databaseType == 'mssql') { 
-                       // ErrorNo is a slow function call in mssql, and not reliable
-                       // in PHP 4.0.6
-                               if($emsg = $this->ErrorMsg()) {
-                                       $err = $this->ErrorNo();
-                                       if ($err) {
-                                               ADOConnection::outp($err.': '.$emsg);
-                                       }
-                               }
-                       } else 
-                               if (!$this->_queryID) {
-                                       $e = $this->ErrorNo();
-                                       $m = $this->ErrorMsg();
-                                       ADOConnection::outp($e .': '. $m );
-                               }
-               } else {
-                       // non-debug version of query
-                       
-                       $this->_queryID =@$this->_query($sql,$inputarr);
-               }
-               
-               /************************
-                       OK, query executed
-               *************************/
-               // error handling if query fails
-               if ($this->_queryID === false) {
-                       if ($this->debug == 99) adodb_backtrace(true,5);        
-                       $fn = $this->raiseErrorFn;
-                       if ($fn) {
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
-                       } 
-                               
-                       return false;
-               } else if ($this->_queryID === true) {
-               // return simplified empty recordset for inserts/updates/deletes with lower overhead
-                       $rs =& new ADORecordSet_empty();
-                       return $rs;
-               }
-               
-               // return real recordset from select statement
-               $rsclass = $this->rsPrefix.$this->databaseType;
-               $rs =& new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions
-               $rs->connection = &$this; // Pablo suggestion
-               $rs->Init();
-               if (is_array($sql)) $rs->sql = $sql[0];
-               else $rs->sql = $sql;
-               if ($rs->_numOfRows <= 0) {
-               global $ADODB_COUNTRECS;
-       
-                       if ($ADODB_COUNTRECS) {
-                               if (!$rs->EOF){ 
-                                       $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
-                                       $rs->_queryID = $this->_queryID;
-                               } else
-                                       $rs->_numOfRows = 0;
-                       }
-               }
-               return $rs;
-       }
-
-       function CreateSequence($seqname='adodbseq',$startID=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
-               return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
-       }
-
-       function DropSequence($seqname)
-       {
-               if (empty($this->_dropSeqSQL)) return false;
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
-       }
-
-       /**
-        * Generates a sequence id and stores it in $this->genID;
-        * GenID is only available if $this->hasGenID = true;
-        *
-        * @param seqname               name of sequence to use
-        * @param startID               if sequence does not exist, start at this ID
-        * @return              0 if not supported, otherwise a sequence id
-        */
-       function GenID($seqname='adodbseq',$startID=1)
-       {
-               if (!$this->hasGenID) {
-                       return 0; // formerly returns false pre 1.60
-               }
-               
-               $getnext = sprintf($this->_genIDSQL,$seqname);
-               
-               $holdtransOK = $this->_transOK;
-               $rs = @$this->Execute($getnext);
-               if (!$rs) {
-                       $this->_transOK = $holdtransOK; //if the status was ok before reset
-                       $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
-                       $rs = $this->Execute($getnext);
-               }
-               if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
-               else $this->genID = 0; // false
-       
-               if ($rs) $rs->Close();
-
-               return $this->genID;
-       }       
-
-       /**
-        * @return  the last inserted ID. Not all databases support this.
-        */ 
-       function Insert_ID()
-       {
-               if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
-               if ($this->hasInsertID) return $this->_insertid();
-               if ($this->debug) {
-                       ADOConnection::outp( '<p>Insert_ID error</p>');
-                       adodb_backtrace();
-               }
-               return false;
-       }
-
-
-       /**
-        * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
-        *
-        * @return  the last inserted ID. All databases support this. But aware possible
-        * problems in multiuser environments. Heavy test this before deploying.
-        */ 
-       function PO_Insert_ID($table="", $id="") 
-       {
-          if ($this->hasInsertID){
-                  return $this->Insert_ID();
-          } else {
-                  return $this->GetOne("SELECT MAX($id) FROM $table");
-          }
-       }
-
-       /**
-       * @return # rows affected by UPDATE/DELETE
-       */ 
-       function Affected_Rows()
-       {
-               if ($this->hasAffectedRows) {
-                       if ($this->fnExecute === 'adodb_log_sql') {
-                               if ($this->_logsql && $this->_affected !== false) return $this->_affected;
-                       }
-                       $val = $this->_affectedrows();
-                       return ($val < 0) ? false : $val;
-               }
-                                 
-               if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
-               return false;
-       }
-       
-       
-       /**
-        * @return  the last error message
-        */
-       function ErrorMsg()
-       {
-               return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
-       }
-       
-       
-       /**
-        * @return the last error number. Normally 0 means no error.
-        */
-       function ErrorNo() 
-       {
-               return ($this->_errorMsg) ? -1 : 0;
-       }
-       
-       function MetaError($err=false)
-       {
-               include_once(ADODB_DIR."/adodb-error.inc.php");
-               if ($err === false) $err = $this->ErrorNo();
-               return adodb_error($this->dataProvider,$this->databaseType,$err);
-       }
-       
-       function MetaErrorMsg($errno)
-       {
-               include_once(ADODB_DIR."/adodb-error.inc.php");
-               return adodb_errormsg($errno);
-       }
-       
-       /**
-        * @returns an array with the primary key columns in it.
-        */
-       function MetaPrimaryKeys($table, $owner=false)
-       {
-       // owner not used in base class - see oci8
-               $p = array();
-               $objs =& $this->MetaColumns($table);
-               if ($objs) {
-                       foreach($objs as $v) {
-                               if (!empty($v->primary_key))
-                                       $p[] = $v->name;
-                       }
-               }
-               if (sizeof($p)) return $p;
-               if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
-                       return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
-               return false;
-       }
-       
-       /**
-        * @returns assoc array where keys are tables, and values are foreign keys
-        */
-       function MetaForeignKeys($table, $owner=false, $upper=false)
-       {
-               return false;
-       }
-       /**
-        * Choose a database to connect to. Many databases do not support this.
-        *
-        * @param dbName        is the name of the database to select
-        * @return              true or false
-        */
-       function SelectDB($dbName) 
-       {return false;}
-       
-       
-       /**
-       * Will select, getting rows from $offset (1-based), for $nrows. 
-       * This simulates the MySQL "select * from table limit $offset,$nrows" , and
-       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
-       * MySQL and PostgreSQL parameter ordering is the opposite of the other.
-       * eg. 
-       *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
-       *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
-       *
-       * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
-       * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
-       *
-       * @param sql
-       * @param [offset]       is the row to start calculations from (1-based)
-       * @param [nrows]                is the number of rows to get
-       * @param [inputarr]     array of bind variables
-       * @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)
-       {
-               if ($this->hasTop && $nrows > 0) {
-               // suggested by Reinhard Balling. Access requires top after distinct 
-                // Informix requires first before distinct - F Riosa
-                       $ismssql = (strpos($this->databaseType,'mssql') !== false);
-                       if ($ismssql) $isaccess = false;
-                       else $isaccess = (strpos($this->databaseType,'access') !== false);
-                       
-                       if ($offset <= 0) {
-                               
-                                       // access includes ties in result
-                                       if ($isaccess) {
-                                               $sql = preg_replace(
-                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
-
-                                               if ($secs2cache>0) {
-                                                       $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
-                                               } else {
-                                                       $ret =& $this->Execute($sql,$inputarr);
-                                               }
-                                               return $ret; // PHP5 fix
-                                       } else if ($ismssql){
-                                               $sql = preg_replace(
-                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
-                                       } else {
-                                               $sql = preg_replace(
-                                               '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
-                                       }
-                       } else {
-                               $nn = $nrows + $offset;
-                               if ($isaccess || $ismssql) {
-                                       $sql = preg_replace(
-                                       '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
-                               } else {
-                                       $sql = preg_replace(
-                                       '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
-                               }
-                       }
-               }
-               
-               // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows
-               // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
-               global $ADODB_COUNTRECS;
-               
-               $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);
-               }
-               $ADODB_COUNTRECS = $savec;
-               if ($rs && !$rs->EOF) {
-                       $rs =& $this->_rs2rs($rs,$nrows,$offset);
-               }
-               //print_r($rs);
-               return $rs;
-       }
-       
-       /**
-       * Create serializable recordset. Breaks rs link to connection.
-       *
-       * @param rs                     the recordset to serialize
-       */
-       function &SerializableRS(&$rs)
-       {
-               $rs2 =& $this->_rs2rs($rs);
-               $ignore = false;
-               $rs2->connection =& $ignore;
-               
-               return $rs2;
-       }
-       
-       /**
-       * Convert database recordset to an array recordset
-       * input recordset's cursor should be at beginning, and
-       * old $rs will be closed.
-       *
-       * @param rs                     the recordset to copy
-       * @param [nrows]        number of rows to retrieve (optional)
-       * @param [offset]       offset by number of rows (optional)
-       * @return                       the new recordset
-       */
-       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
-       {
-               if (! $rs) return false;
-               
-               $dbtype = $rs->databaseType;
-               if (!$dbtype) {
-                       $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 ?
-                       return $rs;
-               }
-               $flds = array();
-               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
-                       $flds[] = $rs->FetchField($i);
-               }
-               $arr =& $rs->GetArrayLimit($nrows,$offset);
-               //print_r($arr);
-               if ($close) $rs->Close();
-               
-               $arrayClass = $this->arrayClass;
-               
-               $rs2 =& new $arrayClass();
-               $rs2->connection = &$this;
-               $rs2->sql = $rs->sql;
-               $rs2->dataProvider = $this->dataProvider;
-               $rs2->InitArrayFields($arr,$flds);
-               return $rs2;
-       }
-       
-       /*
-       * Return all rows. Compat with PEAR DB
-       */
-       function &GetAll($sql, $inputarr=false)
-       {
-               $arr =& $this->GetArray($sql,$inputarr);
-               return $arr;
-       }
-       
-       function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
-       {
-               $rs =& $this->Execute($sql, $inputarr);
-               if (!$rs) return false;
-               
-               $arr =& $rs->GetAssoc($force_array,$first2cols);
-               return $arr;
-       }
-       
-       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);
-               if (!$rs) return false;
-               
-               $arr =& $rs->GetAssoc($force_array,$first2cols);
-               return $arr;
-       }
-       
-       /**
-       * Return first element of first row of sql statement. Recordset is disposed
-       * for you.
-       *
-       * @param sql                    SQL statement
-       * @param [inputarr]             input bind array
-       */
-       function GetOne($sql,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
-               $crecs = $ADODB_COUNTRECS;
-               $ADODB_COUNTRECS = false;
-               
-               $ret = false;
-               $rs = &$this->Execute($sql,$inputarr);
-               if ($rs) {              
-                       if (!$rs->EOF) $ret = reset($rs->fields);
-                       $rs->Close();
-               } 
-               $ADODB_COUNTRECS = $crecs;
-               return $ret;
-       }
-       
-       function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
-       {
-               $ret = false;
-               $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
-               if ($rs) {              
-                       if (!$rs->EOF) $ret = reset($rs->fields);
-                       $rs->Close();
-               } 
-               
-               return $ret;
-       }
-       
-       function GetCol($sql, $inputarr = false, $trim = false)
-       {
-               $rv = false;
-               $rs = &$this->Execute($sql, $inputarr);
-               if ($rs) {
-                       $rv = array();
-                       if ($trim) {
-                               while (!$rs->EOF) {
-                                       $rv[] = trim(reset($rs->fields));
-                                       $rs->MoveNext();
-                               }
-                       } else {
-                               while (!$rs->EOF) {
-                                       $rv[] = reset($rs->fields);
-                                       $rs->MoveNext();
-                               }
-                       }
-                       $rs->Close();
-               }
-               return $rv;
-       }
-       
-       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
-       {
-               $rv = false;
-               $rs = &$this->CacheExecute($secs, $sql, $inputarr);
-               if ($rs) {
-                       if ($trim) {
-                               while (!$rs->EOF) {
-                                       $rv[] = trim(reset($rs->fields));
-                                       $rs->MoveNext();
-                               }
-                       } else {
-                               while (!$rs->EOF) {
-                                       $rv[] = reset($rs->fields);
-                                       $rs->MoveNext();
-                               }
-                       }
-                       $rs->Close();
-               }
-               return $rv;
-       }
-       /*
-               Calculate the offset of a date for a particular database and generate
-                       appropriate SQL. Useful for calculating future/past dates and storing
-                       in a database.
-                       
-               If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
-       */
-       function OffsetDate($dayFraction,$date=false)
-       {               
-               if (!$date) $date = $this->sysDate;
-               return  '('.$date.'+'.$dayFraction.')';
-       }
-       
-       
-       /**
-       *
-       * @param sql                    SQL statement
-       * @param [inputarr]             input bind array
-       */
-       function &GetArray($sql,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
-               
-               $savec = $ADODB_COUNTRECS;
-               $ADODB_COUNTRECS = false;
-               $rs =& $this->Execute($sql,$inputarr);
-               $ADODB_COUNTRECS = $savec;
-               if (!$rs) 
-                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
-                       else return false;
-               $arr =& $rs->GetArray();
-               $rs->Close();
-               return $arr;
-       }
-       
-       function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
-               
-               $savec = $ADODB_COUNTRECS;
-               $ADODB_COUNTRECS = false;
-               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
-               $ADODB_COUNTRECS = $savec;
-               
-               if (!$rs) 
-                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
-                       else return false;
-               
-               $arr =& $rs->GetArray();
-               $rs->Close();
-               return $arr;
-       }
-       
-       
-       
-       /**
-       * 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)
-       {
-       global $ADODB_COUNTRECS;
-               $crecs = $ADODB_COUNTRECS;
-               $ADODB_COUNTRECS = false;
-               
-               $rs =& $this->Execute($sql,$inputarr);
-               
-               $ADODB_COUNTRECS = $crecs;
-               if ($rs) {
-                       if (!$rs->EOF) $arr = $rs->fields;
-                       else $arr = array();
-                       $rs->Close();
-                       return $arr;
-               }
-               
-               return false;
-       }
-       
-       function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
-       {
-               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
-               if ($rs) {
-                       $arr = false;
-                       if (!$rs->EOF) $arr = $rs->fields;
-                       $rs->Close();
-                       return $arr;
-               }
-               return false;
-       }
-       
-       /**
-       * Insert or replace a single record. Note: this is not the same as MySQL's replace. 
-       * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
-       * Also note that no table locking is done currently, so it is possible that the
-       * record be inserted twice by two programs...
-       *
-       * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
-       *
-       * $table                table name
-       * $fieldArray   associative array of data (you must quote strings yourself).
-       * $keyCol               the primary key field name or if compound key, array of field names
-       * autoQuote             set to true to use a hueristic to quote strings. Works with nulls and numbers
-       *                                       but does not work with dates nor SQL functions.
-       * has_autoinc   the primary key is an auto-inc field, so skip in insert.
-       *
-       * Currently blob replace not supported
-       *
-       * returns 0 = fail, 1 = update, 2 = insert 
-       */
-       
-       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
-       {
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               
-               return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
-       }
-       
-       
-       /**
-       * Will select, getting rows from $offset (1-based), for $nrows. 
-       * This simulates the MySQL "select * from table limit $offset,$nrows" , and
-       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
-       * MySQL and PostgreSQL parameter ordering is the opposite of the other.
-       * eg. 
-       *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
-       *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
-       *
-       * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
-       *
-       * @param [secs2cache]   seconds to cache data, set to 0 to force query. This is optional
-       * @param sql
-       * @param [offset]       is the row to start calculations from (1-based)
-       * @param [nrows]        is the number of rows to get
-       * @param [inputarr]     array of bind variables
-       * @return               the recordset ($rs->databaseType == 'array')
-       */
-       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);
-               } else {
-                       if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
-                       $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-               }
-               return $rs;
-       }
-       
-       /**
-       * Flush cached recordsets that match a particular $sql statement. 
-       * If $sql == false, then we purge all files in the cache.
-       */
-       function CacheFlush($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 = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; 
-                               // 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;
-               } 
-               $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 generate filename for caching.
-       * Filename is generated based on:
-       *
-       *  - sql statement
-       *  - database type (oci8, ibase, ifx, etc)
-       *  - database name
-       *  - userid
-       *
-       * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). 
-       * Assuming that we can have 50,000 files per directory with good performance, 
-       * then we can scale to 12.8 million unique cached recordsets. Wow!
-       */
-       function _gencachename($sql,$createdir)
-       {
-       global $ADODB_CACHE_DIR;
-               
-               $m = md5($sql.$this->databaseType.$this->database.$this->user);
-               $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
-               if ($createdir && !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';
-       }
-       
-       
-       /**
-        * Execute SQL, caching recordsets.
-        *
-        * @param [secs2cache]  seconds to cache data, set to 0 to force query. 
-        *                                        This is an optional parameter.
-        * @param sql           SQL statement to execute
-        * @param [inputarr]    holds the input data  to bind to
-        * @return              RecordSet or false
-        */
-       function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
-       {
-               if (!is_numeric($secs2cache)) {
-                       $inputarr = $sql;
-                       $sql = $secs2cache;
-                       $secs2cache = $this->cacheSecs;
-               }
-               global $ADODB_INCLUDED_CSV;
-               if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
-               
-               if (is_array($sql)) $sql = $sql[0];
-                       
-               $md5file = $this->_gencachename($sql.serialize($inputarr),true);
-               $err = '';
-               
-               if ($secs2cache > 0){
-                       $rs = &csv2rs($md5file,$err,$secs2cache);
-                       $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()) {
-                                       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($sql,$inputarr);
-                       if ($rs) {
-                               $eof = $rs->EOF;
-                               $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
-                               $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);
-                                       }
-                                       if ($this->debug) ADOConnection::outp( " Cache write error");
-                               }
-                               if ($rs->EOF && !$eof) {
-                                       $rs->MoveFirst();
-                                       //$rs = &csv2rs($md5file,$err);         
-                                       $rs->connection = &$this; // Pablo suggestion
-                               }  
-                               
-                       } else
-                               @unlink($md5file);
-               } else {
-                       $this->_errorMsg = '';
-                       $this->_errorCode = 0;
-                       
-                       if ($this->fnCacheExecute) {
-                               $fn = $this->fnCacheExecute;
-                               $fn($this, $secs2cache, $sql, $inputarr);
-                       }
-               // ok, set cached object found
-                       $rs->connection = &$this; // Pablo suggestion
-                       if ($this->debug){ 
-                       global $HTTP_SERVER_VARS;
-                                       
-                               $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
-                               $ttl = $rs->timeCreated + $secs2cache - time();
-                               $s = is_array($sql) ? $sql[0] : $sql;
-                               if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
-                               
-                               ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
-                       }
-               }
-               return $rs;
-       }
-       
-       
-       /**
-        * Generates an Update Query based on an existing recordset.
-        * $arrFields is an associative array of fields with the value
-        * that should be assigned.
-        *
-        * Note: This function should only be used on a recordset
-        *         that is run against a single table and sql should only 
-        *               be a simple select stmt with no groupby/orderby/limit
-        *
-        * "Jonathan Younger" <jyounger@unilab.com>
-        */
-       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
-       {
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
-       }
-
-
-       /**
-        * Generates an Insert Query based on an existing recordset.
-        * $arrFields is an associative array of fields with the value
-        * that should be assigned.
-        *
-        * Note: This function should only be used on a recordset
-        *         that is run against a single table.
-        */
-       function GetInsertSQL(&$rs, $arrFields,$magicq=false)
-       {       
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
-       }
-       
-
-       /**
-       * Update a blob column, given a where clause. There are more sophisticated
-       * blob handling functions that we could have implemented, but all require
-       * a very complex API. Instead we have chosen something that is extremely
-       * simple to understand and use. 
-       *
-       * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
-       *
-       * Usage to update a $blobvalue which has a primary key blob_id=1 into a 
-       * field blobtable.blobcolumn:
-       *
-       *       UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
-       *
-       * Insert example:
-       *
-       *       $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')
-       {
-               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
-       }
-
-       /**
-       * Usage:
-       *       UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
-       *       
-       *       $blobtype supports 'BLOB' and 'CLOB'
-       *
-       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
-       *       $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
-       */
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
-       {
-               $fd = fopen($path,'rb');
-               if ($fd === false) return false;
-               $val = fread($fd,filesize($path));
-               fclose($fd);
-               return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
-       }
-       
-       function BlobDecode($blob)
-       {
-               return $blob;
-       }
-       
-       function BlobEncode($blob)
-       {
-               return $blob;
-       }
-       
-       function SetCharSet($charset)
-       {
-               return false;
-       }
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
-       }
-       
-       function LogSQL($enable=true)
-       {
-               include_once(ADODB_DIR.'/adodb-perf.inc.php');
-               
-               if ($enable) $this->fnExecute = 'adodb_log_sql';
-               else $this->fnExecute = false;
-               
-               $old = $this->_logsql;  
-               $this->_logsql = $enable;
-               if ($enable && !$old) $this->_affected = false;
-               return $old;
-       }
-       
-       function GetCharSet()
-       {
-               return false;
-       }
-       
-       /**
-       * Usage:
-       *       UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
-       *
-       *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
-       *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
-       */
-       function UpdateClob($table,$column,$val,$where)
-       {
-               return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
-       }
-       
-       
-       /**
-       *  Change the SQL connection locale to a specified locale.
-       *  This is used to get the date formats written depending on the client locale.
-       */
-       function SetDateLocale($locale = 'En')
-       {
-               $this->locale = $locale;
-               switch ($locale)
-               {
-                       default:
-                       case 'En':
-                               $this->fmtDate="Y-m-d";
-                               $this->fmtTimeStamp = "Y-m-d H:i:s";
-                               break;
-       
-                       case 'Fr':
-                       case 'Ro':
-                       case 'It':
-                               $this->fmtDate="d-m-Y";
-                               $this->fmtTimeStamp = "d-m-Y H:i:s";
-                               break;
-                               
-                       case 'Ge':
-                               $this->fmtDate="d.m.Y";
-                               $this->fmtTimeStamp = "d.m.Y H:i:s";
-                               break;
-               }
-       }
-       
-       
-       /**
-        *  $meta       contains the desired type, which could be...
-        *      C for character. You will have to define the precision yourself.
-        *      X for teXt. For unlimited character lengths.
-        *      B for Binary
-        *  F for floating point, with no need to define scale and precision
-        *      N for decimal numbers, you will have to define the (scale, precision) yourself
-        *      D for date
-        *      T for timestamp
-        *      L for logical/Boolean
-        *      I for integer
-        *      R for autoincrement counter/integer
-        *  and if you want to use double-byte, add a 2 to the end, like C2 or X2.
-        * 
-        *
-        * @return the actual type of the data or false if no such type available
-       */
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C':
-               case 'X':
-                       return 'VARCHAR';
-               case 'B':
-                       
-               case 'D':
-               case 'T':
-               case 'L':
-               
-               case 'R':
-                       
-               case 'I':
-               case 'N':
-                       return false;
-               }
-       }
-
-       
-       /**
-        * Close Connection
-        */
-       function Close() 
-       {
-               return $this->_close();
-               
-               // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need 
-               // to be closed too!
-               //if ($this->_isPersistentConnection != true) return $this->_close();
-               //else return true;     
-       }
-       
-       /**
-        * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
-        *
-        * @return true if succeeded or false if database does not support transactions
-        */
-       function BeginTrans() {return false;}
-       
-       
-       /**
-        * If database does not support transactions, always return true as data always commited
-        *
-        * @param $ok  set to false to rollback transaction, true to commit
-        *
-        * @return true/false.
-        */
-       function CommitTrans($ok=true) 
-       { return true;}
-       
-       
-       /**
-        * If database does not support transactions, rollbacks always fail, so return false
-        *
-        * @return true/false.
-        */
-       function RollbackTrans() 
-       { return false;}
-
-
-       /**
-        * return the databases that the driver can connect to. 
-        * Some databases will return an empty array.
-        *
-        * @return an array of database names.
-        */
-               function MetaDatabases() 
-               {
-               global $ADODB_FETCH_MODE;
-               
-                       if ($this->metaDatabasesSQL) {
-                               $save = $ADODB_FETCH_MODE; 
-                               $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
-                               
-                               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-                               
-                               $arr = $this->GetCol($this->metaDatabasesSQL);
-                               if (isset($savem)) $this->SetFetchMode($savem);
-                               $ADODB_FETCH_MODE = $save; 
-                       
-                               return $arr;
-                       }
-                       
-                       return false;
-               }
-               
-       /**
-        * @param ttype can either be 'VIEW' or 'TABLE' or false. 
-        *              If false, both views and tables are returned.
-        *              "VIEW" returns only views
-        *              "TABLE" returns only tables
-        * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
-        * @param mask  is the input mask - only supported by oci8 and postgresql
-        *
-        * @return  array of tables for current database.
-        */ 
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
-       {
-       global $ADODB_FETCH_MODE;
-       
-               if ($mask) return false;
-               
-               if ($this->metaTablesSQL) {
-                       // complicated state saving by the need for backward compat
-                       $save = $ADODB_FETCH_MODE; 
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
-                       
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-                       
-                       $rs = $this->Execute($this->metaTablesSQL);
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save; 
-                       
-                       if ($rs === false) return false;
-                       $arr =& $rs->GetArray();
-                       $arr2 = array();
-                       
-                       if ($hast = ($ttype && isset($arr[0][1]))) { 
-                               $showt = strncmp($ttype,'T',1);
-                       }
-                       
-                       for ($i=0; $i < sizeof($arr); $i++) {
-                               if ($hast) {
-                                       if ($showt == 0) {
-                                               if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
-                                       } else {
-                                               if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
-                                       }
-                               } else
-                                       $arr2[] = trim($arr[$i][0]);
-                       }
-                       $rs->Close();
-                       return $arr2;
-               }
-               return false;
-       }
-       
-       
-       function _findschema(&$table,&$schema)
-       {
-               if (!$schema && ($at = strpos($table,'.')) !== false) {
-                       $schema = substr($table,0,$at);
-                       $table = substr($table,$at+1);
-               }
-       }
-       
-       /**
-        * List columns in a database as an array of ADOFieldObjects. 
-        * See top of file for definition of object.
-        *
-        * @param table table name to query
-        * @param upper uppercase table name (required by some databases)
-        * @schema is optional database schema to use - not supported by all databases.
-        *
-        * @return  array of ADOFieldObjects for current table.
-        */
-       function &MetaColumns($table,$upper=true) 
-       {
-       global $ADODB_FETCH_MODE;
-               
-               if (!empty($this->metaColumnsSQL)) {
-               
-                       $schema = false;
-                       $this->_findschema($table,$schema);
-               
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save;
-                       if ($rs === false) return false;
-
-                       $retarr = array();
-                       while (!$rs->EOF) { //print_r($rs->fields);
-                               $fld =& new ADOFieldObject();
-                               $fld->name = $rs->fields[0];
-                               $fld->type = $rs->fields[1];
-                               if (isset($rs->fields[3]) && $rs->fields[3]) {
-                                       if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
-                                       $fld->scale = $rs->fields[4];
-                                       if ($fld->scale>0) $fld->max_length += 1;
-                               } else
-                                       $fld->max_length = $rs->fields[2];
-                                       
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
-                               else $retarr[strtoupper($fld->name)] = $fld;
-                               $rs->MoveNext();
-                       }
-                       $rs->Close();
-                       return $retarr; 
-               }
-               return false;
-       }
-       
-    /**
-      * List indexes on a table as an array.
-      * @param table        table name to query
-      * @param primary include primary keys.
-         *
-      * @return array of indexes on current table.
-      */
-     function &MetaIndexes($table, $primary = false, $owner = false)
-     {
-             return FALSE;
-     }
-
-       /**
-        * List columns names in a table as an array. 
-        * @param table table name to query
-        *
-        * @return  array of column names for current table.
-        */ 
-       function &MetaColumnNames($table) 
-       {
-               $objarr =& $this->MetaColumns($table);
-               if (!is_array($objarr)) return false;
-               
-               $arr = array();
-               foreach($objarr as $v) {
-                       $arr[] = $v->name;
-               }
-               return $arr;
-       }
-                       
-       /**
-        * Different SQL databases used different methods to combine strings together.
-        * This function provides a wrapper. 
-        * 
-        * param s      variable number of string parameters
-        *
-        * Usage: $db->Concat($str1,$str2);
-        * 
-        * @return concatenated string
-        */      
-       function Concat()
-       {       
-               $arr = func_get_args();
-               return implode($this->concat_operator, $arr);
-       }
-       
-       
-       /**
-        * Converts a date "d" to a string that the database can understand.
-        *
-        * @param d     a date in Unix date time format.
-        *
-        * @return  date string in database date format
-        */
-       function DBDate($d)
-       {
-               if (empty($d) && $d !== 0) return 'null';
-
-               if (is_string($d) && !is_numeric($d)) {
-                       if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
-                       if ($this->isoDates) return "'$d'";
-                       $d = ADOConnection::UnixDate($d);
-               }
-
-               return adodb_date($this->fmtDate,$d);
-       }
-       
-       
-       /**
-        * Converts a timestamp "ts" to a string that the database can understand.
-        *
-        * @param ts    a timestamp in Unix date time format.
-        *
-        * @return  timestamp string in database timestamp format
-        */
-       function DBTimeStamp($ts)
-       {
-               if (empty($ts) && $ts !== 0) return 'null';
-
-               # strlen(14) allows YYYYMMDDHHMMSS format
-               if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) 
-                       return adodb_date($this->fmtTimeStamp,$ts);
-               
-               if ($ts === 'null') return $ts;
-               if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
-               
-               $ts = ADOConnection::UnixTimeStamp($ts);
-               return adodb_date($this->fmtTimeStamp,$ts);
-       }
-       
-       /**
-        * Also in ADORecordSet.
-        * @param $v is a date string in YYYY-MM-DD format
-        *
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
-        */
-       function UnixDate($v)
-       {
-               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
-                       ($v), $rr)) return false;
-
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
-               // h-m-s-MM-DD-YY
-               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
-       }
-       
-
-       /**
-        * Also in ADORecordSet.
-        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
-        *
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
-        */
-       function UnixTimeStamp($v)
-       {
-               if (!preg_match( 
-                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
-                       ($v), $rr)) return false;
-                       
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
-       
-               // h-m-s-MM-DD-YY
-               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
-               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
-       }
-       
-       /**
-        * Also in ADORecordSet.
-        *
-        * Format database date based on user defined format.
-        *
-        * @param v     is the character date in YYYY-MM-DD format, returned by database
-        * @param fmt   is the format to apply to it, using date()
-        *
-        * @return a date formated as user desires
-        */
-        
-       function UserDate($v,$fmt='Y-m-d')
-       {
-               $tt = $this->UnixDate($v);
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
-               if (($tt === false || $tt == -1) && $v != false) return $v;
-               else if ($tt == 0) return $this->emptyDate;
-               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
-               }
-               
-               return adodb_date($fmt,$tt);
-       
-       }
-       
-               /**
-        *
-        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format
-        * @param fmt   is the format to apply to it, using date()
-        *
-        * @return a timestamp formated as user desires
-        */
-       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
-       {
-               # strlen(14) allows YYYYMMDDHHMMSS format
-               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
-               $tt = $this->UnixTimeStamp($v);
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
-               if (($tt === false || $tt == -1) && $v != false) return $v;
-               if ($tt == 0) return $this->emptyTimeStamp;
-               return adodb_date($fmt,$tt);
-       }
-       
-       /**
-       * Quotes a string, without prefixing nor appending quotes. 
-       */
-       function addq($s,$magicq=false)
-       {
-               if (!$magic_quotes) {
-               
-                       if ($this->replaceQuote[0] == '\\'){
-                               // only since php 4.0.5
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
-                       }
-                       return  str_replace("'",$this->replaceQuote,$s);
-               }
-               
-               // undo magic quotes for "
-               $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);
-               }
-       }
-       
-       /**
-        * 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) {
-               
-                       if ($this->replaceQuote[0] == '\\'){
-                               // only since php 4.0.5
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
-                       }
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";
-               }
-               
-               // undo magic quotes for "
-               $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)."'";
-               }
-       }
-       
-       
-       /**
-       * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
-       * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
-       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
-       *
-       * See readme.htm#ex8 for an example of usage.
-       *
-       * @param sql
-       * @param nrows          is the number of rows per page to get
-       * @param page           is the page number to get (1-based)
-       * @param [inputarr]     array of bind variables
-       * @param [secs2cache]           is a private parameter only used by jlim
-       * @return               the recordset ($rs->databaseType == 'array')
-       *
-       * NOTE: phpLens uses a different algorithm and does not use PageExecute().
-       *
-       */
-       function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
-       {
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
-               return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
-
-       }
-       
-               
-       /**
-       * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
-       * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
-       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
-       *
-       * @param secs2cache     seconds to cache data, set to 0 to force query
-       * @param sql
-       * @param nrows          is the number of rows per page to get
-       * @param page           is the page number to get (1-based)
-       * @param [inputarr]     array of bind variables
-       * @return               the recordset ($rs->databaseType == 'array')
-       */
-       function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
-       {
-               /*switch($this->dataProvider) {
-               case 'postgres':
-               case 'mysql': 
-                       break;
-               default: $secs2cache = 0; break;
-               }*/
-               $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
-               return $rs;
-       }
-
-} // end class ADOConnection
-       
-       
-       
-       //==============================================================================================        
-       // CLASS ADOFetchObj
-       //==============================================================================================        
-               
-       /**
-       * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
-       */
-       class ADOFetchObj {
-       };
-       
-       //==============================================================================================        
-       // CLASS ADORecordSet_empty
-       //==============================================================================================        
-       
-       /**
-       * Lightweight recordset when there are no records to be returned
-       */
-       class ADORecordSet_empty
-       {
-               var $dataProvider = 'empty';
-               var $databaseType = false;
-               var $EOF = true;
-               var $_numOfRows = 0;
-               var $fields = false;
-               var $connection = false;
-               function RowCount() {return 0;}
-               function RecordCount() {return 0;}
-               function PO_RecordCount(){return 0;}
-               function Close(){return true;}
-               function FetchRow() {return false;}
-               function FieldCount(){ return 0;}
-       }
-       
-       //==============================================================================================        
-       // DATE AND TIME FUNCTIONS
-       //==============================================================================================        
-       include_once(ADODB_DIR.'/adodb-time.inc.php');
-       
-       //==============================================================================================        
-       // CLASS ADORecordSet
-       //==============================================================================================        
-
-       if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
-       else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
-   /**
-        * 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 {
-       /*
-        * public variables     
-        */
-       var $dataProvider = "native";
-       var $fields = false;    /// holds the current row data
-       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 editing.
-       var $canSeek = false;   /// indicates that seek is supported
-       var $sql;                               /// sql text
-       var $EOF = false;               /// Indicates that the current record position is after the last record in a Recordset object. 
-       
-       var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
-       var $emptyDate = '&nbsp;'; /// what to display when $time==0
-       var $debug = false;
-       var $timeCreated=0;     /// datetime in Unix format rs created -- for cached recordsets
-
-       var $bind = false;              /// used by Fields() to hold array - should be private?
-       var $fetchMode;                 /// default fetch mode
-       var $connection = false; /// the parent connection
-       /*
-        *      private variables       
-        */
-       var $_numOfRows = -1;   /** number of rows, or -1 */
-       var $_numOfFields = -1; /** number of fields in recordset */
-       var $_queryID = -1;             /** This variable keeps the result link identifier.     */
-       var $_currentRow = -1;  /** This variable keeps the current row in the Recordset.       */
-       var $_closed = false;   /** has recordset been closed */
-       var $_inited = false;   /** Init() should only be called once */
-       var $_obj;                              /** Used by FetchObj */
-       var $_names;                    /** Used by FetchObj */
-       
-       var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
-       var $_atFirstPage = false;      /** Added by Iván Oliva to implement recordset pagination */
-       var $_atLastPage = false;       /** Added by Iván Oliva to implement recordset pagination */
-       var $_lastPageNo = -1; 
-       var $_maxRecordCount = 0;
-       var $datetime = false;
-       
-       /**
-        * Constructor
-        *
-        * @param queryID       this is the queryID returned by ADOConnection->_query()
-        *
-        */
-       function ADORecordSet($queryID) 
-       {
-               $this->_queryID = $queryID;
-       }
-       
-       
-       
-       function Init()
-       {
-               if ($this->_inited) return;
-               $this->_inited = true;
-               if ($this->_queryID) @$this->_initrs();
-               else {
-                       $this->_numOfRows = 0;
-                       $this->_numOfFields = 0;
-               }
-               if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
-                       
-                       $this->_currentRow = 0;
-                       if ($this->EOF = ($this->_fetch() === false)) {
-                               $this->_numOfRows = 0; // _numOfRows could be -1
-                       }
-               } else {
-                       $this->EOF = true;
-               }
-       }
-       
-       
-       /**
-        * Generate a SELECT tag string from a recordset, and return the string.
-        * If the recordset has 2 cols, we treat the 1st col as the containing 
-        * the text to display to the user, and 2nd col as the return value. Default
-        * strings are compared with the FIRST column.
-        *
-        * @param name                  name of SELECT tag
-        * @param [defstr]              the value to hilite. Use an array for multiple hilites for listbox.
-        * @param [blank1stItem]        true to leave the 1st item in list empty
-        * @param [multiple]            true for listbox, false for popup
-        * @param [size]                #rows to show for listbox. not used by popup
-        * @param [selectAttr]          additional attributes to defined for SELECT tag.
-        *                              useful for holding javascript onChange='...' handlers.
-        & @param [compareFields0]      when we have 2 cols in recordset, we compare the defstr with 
-        *                              column 0 (1st col) if this is true. This is not documented.
-        *
-        * @return HTML
-        *
-        * changes by glen.davies@cce.ac.nz to support multiple hilited items
-        */
-       function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
-                       $size=0, $selectAttr='',$compareFields0=true)
-       {
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
-                       $size, $selectAttr,$compareFields0);
-       }
-       
-       /**
-        * Generate a SELECT tag string from a recordset, and return the string.
-        * If the recordset has 2 cols, we treat the 1st col as the containing 
-        * the text to display to the user, and 2nd col as the return value. Default
-        * strings are compared with the SECOND column.
-        *
-        */
-       function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')  
-       {
-               global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
-                       $size, $selectAttr,false);
-       }
-
-
-       /**
-        * return recordset as a 2-dimensional array.
-        *
-        * @param [nRows]  is the number of rows to return. -1 means every row.
-        *
-        * @return an array indexed by the rows (0-based) from the recordset
-        */
-       function &GetArray($nRows = -1) 
-       {
-       global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
-               
-               $results = array();
-               $cnt = 0;
-               while (!$this->EOF && $nRows != $cnt) {
-                       $results[] = $this->fields;
-                       $this->MoveNext();
-                       $cnt++;
-               }
-               return $results;
-       }
-       
-       function &GetAll($nRows = -1)
-       {
-               $arr =& $this->GetArray($nRows);
-               return $arr;
-       }
-       
-       /*
-       * Some databases allow multiple recordsets to be returned. This function
-       * will return true if there is a next recordset, or false if no more.
-       */
-       function NextRecordSet()
-       {
-               return false;
-       }
-       
-       /**
-        * return recordset as a 2-dimensional array. 
-        * Helper function for ADOConnection->SelectLimit()
-        *
-        * @param offset        is the row to start calculations from (1-based)
-        * @param [nrows]       is the number of rows to return
-        *
-        * @return an array indexed by the rows (0-based) from the recordset
-        */
-       function &GetArrayLimit($nrows,$offset=-1) 
-       {       
-               if ($offset <= 0) {
-                       $arr =& $this->GetArray($nrows);
-                       return $arr;
-               } 
-               
-               $this->Move($offset);
-               
-               $results = array();
-               $cnt = 0;
-               while (!$this->EOF && $nrows != $cnt) {
-                       $results[$cnt++] = $this->fields;
-                       $this->MoveNext();
-               }
-               
-               return $results;
-       }
-       
-       
-       /**
-        * Synonym for GetArray() for compatibility with ADO.
-        *
-        * @param [nRows]  is the number of rows to return. -1 means every row.
-        *
-        * @return an array indexed by the rows (0-based) from the recordset
-        */
-       function &GetRows($nRows = -1) 
-       {
-               $arr =& $this->GetArray($nRows);
-               return $arr;
-       }
-       
-       /**
-        * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. 
-        * The first column is treated as the key and is not included in the array. 
-        * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
-        * $force_array == true.
-        *
-        * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
-        *      array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
-        *      read the source.
-        *
-        * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and 
-        * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
-        *
-        * @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) {
-               $cols = $this->_numOfFields;
-               if ($cols < 2) {
-                       return false;
-               }
-               $numIndex = isset($this->fields[0]);
-               $results = array();
-               
-               if (!$first2cols && ($cols > 2 || $force_array)) {
-                       if ($numIndex) {
-                               while (!$this->EOF) {
-                                       $results[trim($this->fields[0])] = array_slice($this->fields, 1);
-                                       $this->MoveNext();
-                               }
-                       } else {
-                               while (!$this->EOF) {
-                                       $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
-                                       $this->MoveNext();
-                               }
-                       }
-               } else {
-                       // return scalar values
-                       if ($numIndex) {
-                               while (!$this->EOF) {
-                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
-                                       $results[trim(($this->fields[0]))] = $this->fields[1];
-                                       $this->MoveNext();
-                               }
-                       } else {
-                               while (!$this->EOF) {
-                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
-                                       $v1 = trim(reset($this->fields));
-                                       $v2 = ''.next($this->fields); 
-                                       $results[$v1] = $v2;
-                                       $this->MoveNext();
-                               }
-                       }
-               }
-               return $results; 
-       }
-       
-       
-       /**
-        *
-        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format
-        * @param fmt   is the format to apply to it, using date()
-        *
-        * @return a timestamp formated as user desires
-        */
-       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
-       {
-               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
-               $tt = $this->UnixTimeStamp($v);
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
-               if (($tt === false || $tt == -1) && $v != false) return $v;
-               if ($tt === 0) return $this->emptyTimeStamp;
-               return adodb_date($fmt,$tt);
-       }
-       
-       
-       /**
-        * @param v     is the character date in YYYY-MM-DD format, returned by database
-        * @param fmt   is the format to apply to it, using date()
-        *
-        * @return a date formated as user desires
-        */
-       function UserDate($v,$fmt='Y-m-d')
-       {
-               $tt = $this->UnixDate($v);
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
-               if (($tt === false || $tt == -1) && $v != false) return $v;
-               else if ($tt == 0) return $this->emptyDate;
-               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
-               }
-               return adodb_date($fmt,$tt);
-       
-       }
-       
-       
-       /**
-        * @param $v is a date string in YYYY-MM-DD format
-        *
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
-        */
-       function UnixDate($v)
-       {
-               
-               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
-                       ($v), $rr)) return false;
-                       
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
-               // h-m-s-MM-DD-YY
-               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
-       }
-       
-
-       /**
-        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
-        *
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
-        */
-       function UnixTimeStamp($v)
-       {
-               
-               if (!preg_match( 
-                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
-                       ($v), $rr)) return false;
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
-       
-               // h-m-s-MM-DD-YY
-               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
-               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
-       }
-       
-       
-       /**
-       * PEAR DB Compat - do not use internally
-       */
-       function Free()
-       {
-               return $this->Close();
-       }
-       
-       
-       /**
-       * PEAR DB compat, number of rows
-       */
-       function NumRows()
-       {
-               return $this->_numOfRows;
-       }
-       
-       
-       /**
-       * PEAR DB compat, number of cols
-       */
-       function NumCols()
-       {
-               return $this->_numOfFields;
-       }
-       
-       /**
-       * Fetch a row, returning false if no more rows. 
-       * This is PEAR DB compat mode.
-       *
-       * @return false or array containing the current record
-       */
-       function FetchRow()
-       {
-               if ($this->EOF) return false;
-               $arr = $this->fields;
-               $this->_currentRow++;
-               if (!$this->_fetch()) $this->EOF = true;
-               return $arr;
-       }
-       
-       
-       /**
-       * Fetch a row, returning PEAR_Error if no more rows. 
-       * This is PEAR DB compat mode.
-       *
-       * @return DB_OK or error object
-       */
-       function FetchInto(&$arr)
-       {
-               if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
-               $arr = $this->fields;
-               $this->MoveNext();
-               return 1; // DB_OK
-       }
-       
-       
-       /**
-        * Move to the first row in the recordset. Many databases do NOT support this.
-        *
-        * @return true or false
-        */
-       function MoveFirst() 
-       {
-               if ($this->_currentRow == 0) return true;
-               return $this->Move(0);                  
-       }                       
-
-       
-       /**
-        * Move to the last row in the recordset. 
-        *
-        * @return true or false
-        */
-       function MoveLast() 
-       {
-               if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
-               if ($this->EOF) return false;
-               while (!$this->EOF) {
-                       $f = $this->fields;
-                       $this->MoveNext();
-               }
-               $this->fields = $f;
-               $this->EOF = false;
-               return true;
-       }
-       
-       
-       /**
-        * Move to next record in the recordset.
-        *
-        * @return true if there still rows available, or false if there are no more rows (EOF).
-        */
-       function MoveNext() 
-       {
-               if (!$this->EOF) {
-                       $this->_currentRow++;
-                       if ($this->_fetch()) return true;
-               }
-               $this->EOF = true;
-               /* -- tested error handling when scrolling cursor -- seems useless.
-               $conn = $this->connection;
-               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
-                       $fn = $conn->raiseErrorFn;
-                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
-               }
-               */
-               return false;
-       }       
-       
-       /**
-        * Random access to a specific row in the recordset. Some databases do not support
-        * access to previous rows in the databases (no scrolling backwards).
-        *
-        * @param rowNumber is the row to move to (0-based)
-        *
-        * @return true if there still rows available, or false if there are no more rows (EOF).
-        */
-       function Move($rowNumber = 0) 
-       {
-               $this->EOF = false;
-               if ($rowNumber == $this->_currentRow) return true;
-               if ($rowNumber >= $this->_numOfRows)
-                       if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
-                               
-               if ($this->canSeek) { 
-       
-                       if ($this->_seek($rowNumber)) {
-                               $this->_currentRow = $rowNumber;
-                               if ($this->_fetch()) {
-                                       return true;
-                               }
-                       } else {
-                               $this->EOF = true;
-                               return false;
-                       }
-               } else {
-                       if ($rowNumber < $this->_currentRow) return false;
-                       global $ADODB_EXTENSION;
-                       if ($ADODB_EXTENSION) {
-                               while (!$this->EOF && $this->_currentRow < $rowNumber) {
-                                       adodb_movenext($this);
-                               }
-                       } else {
-                       
-                               while (! $this->EOF && $this->_currentRow < $rowNumber) {
-                                       $this->_currentRow++;
-                                       
-                                       if (!$this->_fetch()) $this->EOF = true;
-                               }
-                       }
-                       return !($this->EOF);
-               }
-               
-               $this->fields = false;  
-               $this->EOF = true;
-               return false;
-       }
-       
-               
-       /**
-        * Get the value of a field in the current row by column name.
-        * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
-        * 
-        * @param colname  is the field to access
-        *
-        * @return the value of $colname column
-        */
-       function Fields($colname)
-       {
-               return $this->fields[$colname];
-       }
-       
-       function GetAssocKeys($upper=true)
-       {
-               $this->bind = array();
-               for ($i=0; $i < $this->_numOfFields; $i++) {
-                       $o =& $this->FetchField($i);
-                       if ($upper === 2) $this->bind[$o->name] = $i;
-                       else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
-               }
-       }
-       
-  /**
-   * Use associative array to get fields array for databases that do not support
-   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
-   *
-   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
-   * before you execute your SQL statement, and access $rs->fields['col'] directly.
-   *
-   * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
-   */
-       function &GetRowAssoc($upper=1)
-       {
-               $record = array();
-        //     if (!$this->fields) return $record;
-               
-               if (!$this->bind) {
-                       $this->GetAssocKeys($upper);
-               }
-               
-               foreach($this->bind as $k => $v) {
-                       $record[$k] = $this->fields[$v];
-               }
-
-               return $record;
-       }
-       
-       
-       /**
-        * Clean up recordset
-        *
-        * @return true or false
-        */
-       function Close() 
-       {
-               // free connection object - this seems to globally free the object
-               // and not merely the reference, so don't do this...
-               // $this->connection = false; 
-               if (!$this->_closed) {
-                       $this->_closed = true;
-                       return $this->_close();         
-               } else
-                       return true;
-       }
-       
-       /**
-        * synonyms RecordCount and RowCount    
-        *
-        * @return the number of rows or -1 if this is not supported
-        */
-       function RecordCount() {return $this->_numOfRows;}
-       
-       
-       /*
-       * If we are using PageExecute(), this will return the maximum possible rows
-       * that can be returned when paging a recordset.
-       */
-       function MaxRecordCount()
-       {
-               return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
-       }
-       
-       /**
-        * synonyms RecordCount and RowCount    
-        *
-        * @return the number of rows or -1 if this is not supported
-        */
-       function RowCount() {return $this->_numOfRows;} 
-       
-
-        /**
-        * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
-        *
-        * @return  the number of records from a previous SELECT. All databases support this.
-        *
-        * But aware possible problems in multiuser environments. For better speed the table
-        * must be indexed by the condition. Heavy test this before deploying.
-        */ 
-       function PO_RecordCount($table="", $condition="") {
-               
-               $lnumrows = $this->_numOfRows;
-               // the database doesn't support native recordcount, so we do a workaround
-               if ($lnumrows == -1 && $this->connection) {
-                       IF ($table) {
-                               if ($condition) $condition = " WHERE " . $condition; 
-                               $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
-                               if ($resultrows) $lnumrows = reset($resultrows->fields);
-                       }
-               }
-               return $lnumrows;
-       }
-       
-       /**
-        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
-        */
-       function CurrentRow() {return $this->_currentRow;}
-       
-       /**
-        * synonym for CurrentRow -- for ADO compat
-        *
-        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
-        */
-       function AbsolutePosition() {return $this->_currentRow;}
-       
-       /**
-        * @return the number of columns in the recordset. Some databases will set this to 0
-        * if no records are returned, others will return the number of columns in the query.
-        */
-       function FieldCount() {return $this->_numOfFields;}   
-
-
-       /**
-        * Get the ADOFieldObject of a specific column.
-        *
-        * @param fieldoffset   is the column position to access(0-based).
-        *
-        * @return the ADOFieldObject for that column, or false.
-        */
-       function &FetchField($fieldoffset) 
-       {
-               // must be defined by child class
-       }       
-       
-       /**
-        * Get the ADOFieldObjects of all columns in an array.
-        *
-        */
-       function FieldTypesArray()
-       {
-               $arr = array();
-               for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) 
-                       $arr[] = $this->FetchField($i);
-               return $arr;
-       }
-       
-       /**
-       * Return the fields array of the current row as an object for convenience.
-       * The default case is lowercase field names.
-       *
-       * @return the object with the properties set to the fields of the current row
-       */
-       function &FetchObj()
-       {
-               $o =& $this->FetchObject(false);
-               return $o;
-       }
-       
-       /**
-       * Return the fields array of the current row as an object for convenience.
-       * The default case is uppercase.
-       * 
-       * @param $isupper to set the object property names to uppercase
-       *
-       * @return the object with the properties set to the fields of the current row
-       */
-       function &FetchObject($isupper=true)
-       {
-               if (empty($this->_obj)) {
-                       $this->_obj =& new ADOFetchObj();
-                       $this->_names = array();
-                       for ($i=0; $i <$this->_numOfFields; $i++) {
-                               $f = $this->FetchField($i);
-                               $this->_names[] = $f->name;
-                       }
-               }
-               $i = 0;
-               $o = &$this->_obj;
-               for ($i=0; $i <$this->_numOfFields; $i++) {
-                       $name = $this->_names[$i];
-                       if ($isupper) $n = strtoupper($name);
-                       else $n = $name;
-                       
-                       $o->$n = $this->Fields($name);
-               }
-               return $o;
-       }
-       
-       /**
-       * Return the fields array of the current row as an object for convenience.
-       * The default is lower-case field names.
-       * 
-       * @return the object with the properties set to the fields of the current row,
-       *       or false if EOF
-       *
-       * Fixed bug reported by tim@orotech.net
-       */
-       function &FetchNextObj()
-       {
-               return $this->FetchNextObject(false);
-       }
-       
-       
-       /**
-       * Return the fields array of the current row as an object for convenience. 
-       * The default is upper case field names.
-       * 
-       * @param $isupper to set the object property names to uppercase
-       *
-       * @return the object with the properties set to the fields of the current row,
-       *       or false if EOF
-       *
-       * Fixed bug reported by tim@orotech.net
-       */
-       function &FetchNextObject($isupper=true)
-       {
-               $o = false;
-               if ($this->_numOfRows != 0 && !$this->EOF) {
-                       $o = $this->FetchObject($isupper);      
-                       $this->_currentRow++;
-                       if ($this->_fetch()) return $o;
-               }
-               $this->EOF = true;
-               return $o;
-       }
-       
-       /**
-        * Get the metatype of the column. This is used for formatting. This is because
-        * many databases use different names for the same type, so we transform the original
-        * type to our standardised version which uses 1 character codes:
-        *
-        * @param t  is the type passed in. Normally is ADOFieldObject->type.
-        * @param len is the maximum length of that field. This is because we treat character
-        *      fields bigger than a certain size as a 'B' (blob).
-        * @param fieldobj is the field object returned by the database driver. Can hold
-        *      additional info (eg. primary_key for mysql).
-        * 
-        * @return the general type of the data: 
-        *      C for character < 200 chars
-        *      X for teXt (>= 200 chars)
-        *      B for Binary
-        *      N for numeric floating point
-        *      D for date
-        *      T for timestamp
-        *      L for logical/Boolean
-        *      I for integer
-        *      R for autoincrement counter/integer
-        * 
-        *
-       */
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-       // changed in 2.32 to hashing instead of switch stmt for speed...
-       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
-               ##
-               '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',
-               ##
-               'TIME' => 'T',
-               'TIMESTAMP' => 'T',
-               'DATETIME' => 'T',
-               'TIMESTAMPTZ' => 'T',
-               'T' => 'T',
-               ##
-               'BOOL' => 'L',
-               'BOOLEAN' => 'L', 
-               'BIT' => 'L',
-               'L' => 'L',
-               ##
-               'COUNTER' => 'R',
-               'R' => 'R',
-               'SERIAL' => 'R', // ifx
-               'INT IDENTITY' => 'R',
-               ##
-               'INT' => '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' 
-               );
-               
-               $tmap = false;
-               $t = strtoupper($t);
-               $tmap = @$typeMap[$t];
-               switch ($tmap) {
-               case 'C':
-               
-                       // is the char field is too long, return as text field... 
-                       if ($this->blobSize >= 0) {
-                               if ($len > $this->blobSize) return 'X';
-                       } else if ($len > 250) {
-                               return 'X';
-                       }
-                       return 'C';
-                       
-               case 'I':
-                       if (!empty($fieldobj->primary_key)) return 'R';
-                       return 'I';
-               
-               case false:
-                       return 'N';
-                       
-               case 'B':
-                        if (isset($fieldobj->binary)) 
-                                return ($fieldobj->binary) ? 'B' : 'X';
-                       return 'B';
-               
-               case 'D':
-                       if (!empty($this->datetime)) return 'T';
-                       return 'D';
-                       
-               default: 
-                       if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
-                       return $tmap;
-               }
-       }
-       
-       function _close() {}
-       
-       /**
-        * set/returns the current recordset page when paginating
-        */
-       function AbsolutePage($page=-1)
-       {
-               if ($page != -1) $this->_currentPage = $page;
-               return $this->_currentPage;
-       }
-       
-       /**
-        * set/returns the status of the atFirstPage flag when paginating
-        */
-       function AtFirstPage($status=false)
-       {
-               if ($status != false) $this->_atFirstPage = $status;
-               return $this->_atFirstPage;
-       }
-       
-       function LastPageNo($page = false)
-       {
-               if ($page != false) $this->_lastPageNo = $page;
-               return $this->_lastPageNo;
-       }
-       
-       /**
-        * set/returns the status of the atLastPage flag when paginating
-        */
-       function AtLastPage($status=false)
-       {
-               if ($status != false) $this->_atLastPage = $status;
-               return $this->_atLastPage;
-       }
-       
-} // end class ADORecordSet
-       
-       //==============================================================================================        
-       // CLASS ADORecordSet_array
-       //==============================================================================================        
-       
-       /**
-        * This class encapsulates the concept of a recordset created in memory
-        * as an array. This is useful for the creation of cached recordsets.
-        * 
-        * Note that the constructor is different from the standard ADORecordSet
-        */
-       
-       class ADORecordSet_array extends ADORecordSet
-       {
-               var $databaseType = 'array';
-
-               var $_array;    // holds the 2-dimensional data array
-               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 $canSeek = true;
-               var $affectedrows = false;
-               var $insertid = false;
-               var $sql = '';
-               var $compat = false;
-               /**
-                * Constructor
-                *
-                */
-               function ADORecordSet_array($fakeid=1)
-               {
-               global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
-               
-                       // fetch() on EOF does not delete $this->fields
-                       $this->compat = !empty($ADODB_COMPAT_FETCH);
-                       $this->ADORecordSet($fakeid); // fake queryID           
-                       $this->fetchMode = $ADODB_FETCH_MODE;
-               }
-               
-               
-               /**
-                * Setup the array.
-                *
-                * @param array         is a 2-dimensional array holding the data.
-                *                      The first row should hold the column names 
-                *                      unless paramter $colnames is used.
-                * @param typearr       holds an array of types. These are the same types 
-                *                      used in MetaTypes (C,B,L,I,N).
-                * @param [colnames]    array of column names. If set, then the first row of
-                *                      $array should not hold the column names.
-                */
-               function InitArray($array,$typearr,$colnames=false)
-               {
-                       $this->_array = $array;
-                       $this->_types = $typearr;       
-                       if ($colnames) {
-                               $this->_skiprow1 = false;
-                               $this->_colnames = $colnames;
-                       } else  {
-                               $this->_skiprow1 = true;
-                               $this->_colnames = $array[0];
-                       }
-                       $this->Init();
-               }
-               /**
-                * Setup the Array and datatype file objects
-                *
-                * @param array         is a 2-dimensional array holding the data.
-                *                      The first row should hold the column names 
-                *                      unless paramter $colnames is used.
-                * @param fieldarr      holds an array of ADOFieldObject's.
-                */
-               function InitArrayFields($array,$fieldarr)
-               {
-                       $this->_array = $array;
-                       $this->_skiprow1= false;
-                       if ($fieldarr) {
-                               $this->_fieldobjects = $fieldarr;
-                       } 
-                       $this->Init();
-               }
-               
-               function &GetArray($nRows=-1)
-               {
-                       if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
-                               return $this->_array;
-                       } else {
-                               $arr =& ADORecordSet::GetArray($nRows);
-                               return $arr;
-                       }
-               }
-               
-               function _initrs()
-               {
-                       $this->_numOfRows =  sizeof($this->_array);
-                       if ($this->_skiprow1) $this->_numOfRows -= 1;
-               
-                       $this->_numOfFields =(isset($this->_fieldobjects)) ?
-                                sizeof($this->_fieldobjects):sizeof($this->_types);
-               }
-               
-               /* 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 &FetchField($fieldOffset = -1) 
-               {
-                       if (isset($this->_fieldobjects)) {
-                               return $this->_fieldobjects[$fieldOffset];
-                       }
-                       $o =  new ADOFieldObject();
-                       $o->name = $this->_colnames[$fieldOffset];
-                       $o->type =  $this->_types[$fieldOffset];
-                       $o->max_length = -1; // length not known
-                       
-                       return $o;
-               }
-                       
-               function _seek($row)
-               {
-                       if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
-                               $this->_currentRow = $row;
-                               if ($this->_skiprow1) $row += 1;
-                               $this->fields = $this->_array[$row];
-                               return true;
-                       }
-                       return false;
-               }
-               
-               function MoveNext() 
-               {
-                       if (!$this->EOF) {              
-                               $this->_currentRow++;
-                               
-                               $pos = $this->_currentRow;
-                               
-                               if ($this->_numOfRows <= $pos) {
-                                       if (!$this->compat) $this->fields = false;
-                               } else {
-                                       if ($this->_skiprow1) $pos += 1;
-                                       $this->fields = $this->_array[$pos];
-                                       return true;
-                               }               
-                               $this->EOF = true;
-                       }
-                       
-                       return false;
-               }       
-       
-               function _fetch()
-               {
-                       $pos = $this->_currentRow;
-                       
-                       if ($this->_numOfRows <= $pos) {
-                               if (!$this->compat) $this->fields = false;
-                               return false;
-                       }
-                       if ($this->_skiprow1) $pos += 1;
-                       $this->fields = $this->_array[$pos];
-                       return true;
-               }
-               
-               function _close() 
-               {
-                       return true;    
-               }
-       
-       } // ADORecordSet_array
-
-       //==============================================================================================        
-       // HELPER FUNCTIONS
-       //==============================================================================================                        
-       
-       /**
-        * Synonym for ADOLoadCode. Private function. Do not use.
-        *
-        * @deprecated
-        */
-       function ADOLoadDB($dbType) 
-       { 
-               return ADOLoadCode($dbType);
-       }
-               
-       /**
-        * Load the code for a specific database driver. Private function. Do not use.
-        */
-       function ADOLoadCode($dbType) 
-       {
-       global $ADODB_LASTDB;
-       
-               if (!$dbType) return false;
-               $db = strtolower($dbType);
-               switch ($db) {
-                       case 'maxsql': $db = 'mysqlt'; break;
-                       case 'postgres':
-                       case 'pgsql': $db = 'postgres7'; break;
-               }
-               @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
-               $ADODB_LASTDB = $db;
-               
-               $ok = class_exists("ADODB_" . $db);
-               if ($ok) return $db;
-               
-               $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
-               if (file_exists($file)) ADOConnection::outp("Missing file: $file");
-               else ADOConnection::outp("Syntax error in file: $file");
-               return false;
-       }
-
-       /**
-        * synonym for ADONewConnection for people like me who cannot remember the correct name
-        */
-       function &NewADOConnection($db='')
-       {
-               $tmp =& ADONewConnection($db);
-               return $tmp;
-       }
-       
-       /**
-        * Instantiate a new Connection class for a specific database driver.
-        *
-        * @param [db]  is the database Connection object to create. If undefined,
-        *      use the last database driver that was loaded by ADOLoadCode().
-        *
-        * @return the freshly created instance of the Connection class.
-        */
-       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;
-               
-               if (!empty($ADODB_NEWCONNECTION)) {
-                       $obj = $ADODB_NEWCONNECTION($db);
-                       if ($obj) {
-                               if ($errorfn)  $obj->raiseErrorFn = $errorfn;
-                               return $obj;
-                       }
-               }
-               
-               if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
-               if (empty($db)) $db = $ADODB_LASTDB;
-               
-               if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
-               
-               if (!$db) {
-                        if ($errorfn) {
-                               // raise an error
-                               $ignore = false;
-                               $errorfn('ADONewConnection', 'ADONewConnection', -998,
-                                                "could not load the database driver for '$db",
-                                                $db,false,$ignore);
-                       } else
-                                ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
-                               
-                       return false;
-               }
-               
-               $cls = 'ADODB_'.$db;
-               if (!class_exists($cls)) {
-                       adodb_backtrace();
-                       return false;
-               }
-               
-               $obj =& new $cls();
-               if ($errorfn) $obj->raiseErrorFn = $errorfn;
-               
-               return $obj;
-       }
-       
-       // $perf == true means called by NewPerfMonitor()
-       function _adodb_getdriver($provider,$drivername,$perf=false)
-       {
-               if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') 
-                       $drivername = $provider;
-               else {
-                       if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
-                       else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
-                       else 
-                       switch($drivername) {
-                       case 'oracle': $drivername = 'oci8';break;
-                       //case 'sybase': $drivername = 'mssql';break;
-                       case 'access': 
-                                               if ($perf) $drivername = '';
-                                               break;
-                       case 'db2':     
-                                               break;
-                       default:
-                               $drivername = 'generic';
-                               break;
-                       }
-               }
-               
-               return $drivername;
-       }
-       
-       function &NewPerfMonitor(&$conn)
-       {
-               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
-               if (!$drivername || $drivername == 'generic') return false;
-               include_once(ADODB_DIR.'/adodb-perf.inc.php');
-               @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
-               $class = "Perf_$drivername";
-               if (!class_exists($class)) return false;
-               $perf =& new $class($conn);
-               
-               return $perf;
-       }
-       
-       function &NewDataDictionary(&$conn)
-       {
-               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
-               
-               include_once(ADODB_DIR.'/adodb-lib.inc.php');
-               include_once(ADODB_DIR.'/adodb-datadict.inc.php');
-               $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
-
-               if (!file_exists($path)) {
-                       ADOConnection::outp("Database driver '$path' not available");
-                       return false;
-               }
-               include_once($path);
-               $class = "ADODB2_$drivername";
-               $dict =& new $class();
-               $dict->dataProvider = $conn->dataProvider;
-               $dict->connection = &$conn;
-               $dict->upperName = strtoupper($drivername);
-               $dict->quote = $conn->nameQuote;
-               if (is_resource($conn->_connectionID))
-                       $dict->serverInfo = $conn->ServerInfo();
-               
-               return $dict;
-       }
-
-
-       /**
-       * Save a file $filename and its $contents (normally for caching) with file locking
-       */
-       function adodb_write_file($filename, $contents,$debug=false)
-       { 
-       # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
-       # So to simulate locking, we assume that rename is an atomic operation.
-       # First we delete $filename, then we create a $tempfile write to it and 
-       # rename to the desired $filename. If the rename works, then we successfully 
-       # modified the file exclusively.
-       # What a stupid need - having to simulate locking.
-       # Risks:
-       # 1. $tempfile name is not unique -- very very low
-       # 2. unlink($filename) fails -- ok, rename will fail
-       # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
-       # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated
-               if (strncmp(PHP_OS,'WIN',3) === 0) {
-                       // skip the decimal place
-                       $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;
-                       fclose($fd);
-                       chmod($tmpname,0644);
-                       // the tricky moment
-                       @unlink($filename);
-                       if (!@rename($tmpname,$filename)) {
-                               unlink($tmpname);
-                               $ok = false;
-                       }
-                       if (!$ok) {
-                               if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
-                       }
-                       return $ok;
-               }
-               if (!($fd = fopen($filename, 'a'))) return false;
-               if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
-                       $ok = fwrite( $fd, $contents );
-                       fclose($fd);
-                       chmod($filename,0644);
-               }else {
-                       fclose($fd);
-                       if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
-                       $ok = false;
-               }
-       
-               return $ok;
-       }
-       
-       /*
-               Perform a print_r, with pre tags for better formatting.
-       */
-       function adodb_pr($var)
-       {
-               if (isset($_SERVER['HTTP_USER_AGENT'])) { 
-                       echo " <pre>\n";print_r($var);echo "</pre>\n";
-               } else
-                       print_r($var);
-       }
-       
-       /*
-               Perform a stack-crawl and pretty print it.
-               
-               @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)
-       {
-               $s = '';
-               if (PHPVERSION() < 4.3) return;
-                
-               $html =  (isset($_SERVER['HTTP_USER_AGENT']));
-               $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
-
-               $MAXSTRLEN = 64;
-       
-               $s = ($html) ? '<pre align=left>' : '';
-               
-               if (is_array($printOrArr)) $traceArr = $printOrArr;
-               else $traceArr = debug_backtrace();
-               array_shift($traceArr);
-               $tabs = sizeof($traceArr)-1;
-               
-               foreach ($traceArr as $arr) {
-                       $levels -= 1;
-                       if ($levels < 0) break;
-                       
-                       $args = array();
-                       for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";
-                       $tabs -= 1;
-                       if ($html) $s .= '<font face="Courier New,Courier">';
-                       if (isset($arr['class'])) $s .= $arr['class'].'.';
-                       if (isset($arr['args']))
-                        foreach($arr['args'] as $v) {
-                               if (is_null($v)) $args[] = 'null';
-                               else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
-                               else if (is_object($v)) $args[] = 'Object:'.get_class($v);
-                               else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
-                               else {
-                                       $v = (string) @$v;
-                                       $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
-                                       if (strlen($v) > $MAXSTRLEN) $str .= '...';
-                                       $args[] = $str;
-                               }
-                       }
-                       $s .= $arr['function'].'('.implode(', ',$args).')';
-                       
-                       
-                       $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
-                               
-                       $s .= "\n";
-               }       
-               if ($html) $s .= '</pre>';
-               if ($printOrArr) print $s;
-               
-               return $s;
-       }
-       
-} // defined
+<?php \r
+/*\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://adodb.sourceforge.net\r
+ * \r
+ * This is the main include file for ADOdb.\r
+ * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php\r
+ *\r
+ * The ADOdb files are formatted so that doxygen can be used to generate documentation.\r
+ * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/\r
+ */\r
+\r
+/**\r
+       \mainpage       \r
+       \r
+        @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.\r
+\r
+       Released under both BSD license and Lesser GPL library license. You can choose which license\r
+       you prefer.\r
+       \r
+       PHP's database access functions are not standardised. This creates a need for a database \r
+       class library to hide the differences between the different database API's (encapsulate \r
+       the differences) so we can easily switch databases.\r
+\r
+       We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,\r
+       Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,\r
+       ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and\r
+       other databases via ODBC. \r
+        \r
+       Latest Download at http://php.weblogs.com/adodb<br>\r
+       Manual is at http://php.weblogs.com/adodb_manual\r
+         \r
+ */\r
\r
+ if (!defined('_ADODB_LAYER')) {\r
+       define('_ADODB_LAYER',1);\r
+       \r
+       //==============================================================================================        \r
+       // CONSTANT DEFINITIONS\r
+       //==============================================================================================        \r
+\r
+\r
+       /** \r
+        * Set ADODB_DIR to the directory where this file resides...\r
+        * This constant was formerly called $ADODB_RootPath\r
+        */\r
+       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));\r
+       \r
+       //==============================================================================================        \r
+       // GLOBAL VARIABLES\r
+       //==============================================================================================        \r
+\r
+       GLOBAL \r
+               $ADODB_vers,            // database version\r
+               $ADODB_COUNTRECS,       // count number of records returned - slows down query\r
+               $ADODB_CACHE_DIR,       // directory to cache recordsets\r
+               $ADODB_EXTENSION,   // ADODB extension installed\r
+               $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF\r
+               $ADODB_FETCH_MODE;      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...\r
+       \r
+       //==============================================================================================        \r
+       // GLOBAL SETUP\r
+       //==============================================================================================        \r
+       \r
+       $ADODB_EXTENSION = defined('ADODB_EXTENSION');\r
+       if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {\r
+               \r
+               define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');\r
+       \r
+       // allow [ ] @ ` " and . in table names\r
+               define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');\r
+       \r
+       // prefetching used by oracle\r
+               if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);\r
+       \r
+       \r
+       /*\r
+       Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.\r
+       This currently works only with mssql, odbc, oci8po and ibase derived drivers.\r
+       \r
+               0 = assoc lowercase field names. $rs->fields['orderid']\r
+               1 = assoc uppercase field names. $rs->fields['ORDERID']\r
+               2 = use native-case field names. $rs->fields['OrderID']\r
+       */\r
+       \r
+               define('ADODB_FETCH_DEFAULT',0);\r
+               define('ADODB_FETCH_NUM',1);\r
+               define('ADODB_FETCH_ASSOC',2);\r
+               define('ADODB_FETCH_BOTH',3);\r
+               \r
+               if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);\r
+       \r
+               // PHP's version scheme makes converting to numbers difficult - workaround\r
+               $_adodb_ver = (float) PHP_VERSION;\r
+               if ($_adodb_ver >= 5.0) {\r
+                       define('ADODB_PHPVER',0x5000);\r
+               } else if ($_adodb_ver > 4.299999) { # 4.3\r
+                       define('ADODB_PHPVER',0x4300);\r
+               } else if ($_adodb_ver > 4.199999) { # 4.2\r
+                       define('ADODB_PHPVER',0x4200);\r
+               } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {\r
+                       define('ADODB_PHPVER',0x4050);\r
+               } else {\r
+                       define('ADODB_PHPVER',0x4000);\r
+               }\r
+       }\r
+       \r
+       //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);\r
+\r
+       \r
+       /**\r
+               Accepts $src and $dest arrays, replacing string $data\r
+       */\r
+       function ADODB_str_replace($src, $dest, $data)\r
+       {\r
+               if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);\r
+               \r
+               $s = reset($src);\r
+               $d = reset($dest);\r
+               while ($s !== false) {\r
+                       $data = str_replace($s,$d,$data);\r
+                       $s = next($src);\r
+                       $d = next($dest);\r
+               }\r
+               return $data;\r
+       }\r
+       \r
+       function ADODB_Setup()\r
+       {\r
+       GLOBAL \r
+               $ADODB_vers,            // database version\r
+               $ADODB_COUNTRECS,       // count number of records returned - slows down query\r
+               $ADODB_CACHE_DIR,       // directory to cache recordsets\r
+               $ADODB_FETCH_MODE;\r
+               \r
+               $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;\r
+               \r
+               if (!isset($ADODB_CACHE_DIR)) {\r
+                       $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';\r
+               } else {\r
+                       // do not accept url based paths, eg. http:/ or ftp:/\r
+                       if (strpos($ADODB_CACHE_DIR,'://') !== false) \r
+                               die("Illegal path http:// or ftp://");\r
+               }\r
+               \r
+                       \r
+               // Initialize random number generator for randomizing cache flushes\r
+               srand(((double)microtime())*1000000);\r
+               \r
+               /**\r
+                * ADODB version as a string.\r
+                */\r
+               $ADODB_vers = 'V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';\r
+       \r
+               /**\r
+                * Determines whether recordset->RecordCount() is used. \r
+                * Set to false for highest performance -- RecordCount() will always return -1 then\r
+                * for databases that provide "virtual" recordcounts...\r
+                */\r
+               if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; \r
+       }\r
+       \r
+       \r
+       //==============================================================================================        \r
+       // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB\r
+       //==============================================================================================        \r
+       \r
+       ADODB_Setup();\r
+\r
+       //==============================================================================================        \r
+       // CLASS ADOFieldObject\r
+       //==============================================================================================        \r
+       /**\r
+        * Helper class for FetchFields -- holds info on a column\r
+        */\r
+       class ADOFieldObject { \r
+               var $name = '';\r
+               var $max_length=0;\r
+               var $type="";\r
+\r
+               // additional fields by dannym... (danny_milo@yahoo.com)\r
+               var $not_null = false; \r
+               // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^\r
+               // so we can as well make not_null standard (leaving it at "false" does not harm anyways)\r
+\r
+               var $has_default = false; // this one I have done only in mysql and postgres for now ... \r
+                       // others to come (dannym)\r
+               var $default_value; // default, if any, and supported. Check has_default first.\r
+       }\r
+       \r
+\r
+       \r
+       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)\r
+       {\r
+               //print "Errorno ($fn errno=$errno m=$errmsg) ";\r
+               $thisConnection->_transOK = false;\r
+               if ($thisConnection->_oldRaiseFn) {\r
+                       $fn = $thisConnection->_oldRaiseFn;\r
+                       $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);\r
+               }\r
+       }\r
+       \r
+       //==============================================================================================        \r
+       // CLASS ADOConnection\r
+       //==============================================================================================        \r
+       \r
+       /**\r
+        * Connection object. For connecting to databases, and executing queries.\r
+        */ \r
+       class ADOConnection {\r
+       //\r
+       // PUBLIC VARS \r
+       //\r
+       var $dataProvider = 'native';\r
+       var $databaseType = '';         /// RDBMS currently in use, eg. odbc, mysql, mssql                                      \r
+       var $database = '';                     /// Name of database to be used.        \r
+       var $host = '';                         /// The hostname of the database server \r
+       var $user = '';                         /// The username which is used to connect to the database server. \r
+       var $password = '';             /// Password for the username. For security, we no longer store it.\r
+       var $debug = false;             /// if set to true will output sql statements\r
+       var $maxblobsize = 256000;      /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro\r
+       var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase    \r
+       var $substr = 'substr';         /// substring operator\r
+       var $length = 'length';         /// string length operator\r
+       var $random = 'rand()';         /// random function\r
+       var $upperCase = false;         /// uppercase function\r
+       var $fmtDate = "'Y-m-d'";       /// used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.\r
+       var $true = '1';                        /// string that represents TRUE for a database\r
+       var $false = '0';                       /// string that represents FALSE for a database\r
+       var $replaceQuote = "\\'";      /// string to use to replace quotes\r
+       var $nameQuote = '"';           /// string to use to quote identifiers and names\r
+       var $charSet=false;             /// character set to use - only for interbase\r
+       var $metaDatabasesSQL = '';\r
+       var $metaTablesSQL = '';\r
+       var $uniqueOrderBy = false; /// All order by columns have to be unique\r
+       var $emptyDate = '&nbsp;';\r
+       var $emptyTimeStamp = '&nbsp;';\r
+       var $lastInsID = false;\r
+       //--\r
+       var $hasInsertID = false;               /// supports autoincrement ID?\r
+       var $hasAffectedRows = false;   /// supports affected rows for update/delete?\r
+       var $hasTop = false;                    /// support mssql/access SELECT TOP 10 * FROM TABLE\r
+       var $hasLimit = false;                  /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+       var $readOnly = false;                  /// this is a readonly database - used by phpLens\r
+       var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards\r
+       var $hasGenID = false;          /// can generate sequences using GenID();\r
+       var $hasTransactions = true; /// has transactions\r
+       //--\r
+       var $genID = 0;                         /// sequence id used by GenID();\r
+       var $raiseErrorFn = false;      /// error function to call\r
+       var $isoDates = false; /// accepts dates in ISO format\r
+       var $cacheSecs = 3600; /// cache for 1 hour\r
+       var $sysDate = false; /// name of function that returns the current date\r
+       var $sysTimeStamp = false; /// name of function that returns the current timestamp\r
+       var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets\r
+       \r
+       var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '\r
+       var $numCacheHits = 0; \r
+       var $numCacheMisses = 0;\r
+       var $pageExecuteCountRows = true;\r
+       var $uniqueSort = false; /// indicates that all fields in order by must be unique\r
+       var $leftOuter = false; /// operator to use for left outer join in WHERE clause\r
+       var $rightOuter = false; /// operator to use for right outer join in WHERE clause\r
+       var $ansiOuter = false; /// whether ansi outer join syntax supported\r
+       var $autoRollback = false; // autoRollback on PConnect().\r
+       var $poorAffectedRows = false; // affectedRows not working or unreliable\r
+       \r
+       var $fnExecute = false;\r
+       var $fnCacheExecute = false;\r
+       var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char\r
+       var $rsPrefix = "ADORecordSet_";\r
+       \r
+       var $autoCommit = true;         /// do not modify this yourself - actually private\r
+       var $transOff = 0;                      /// temporarily disable transactions\r
+       var $transCnt = 0;                      /// count of nested transactions\r
+       \r
+       var $fetchMode=false;\r
+        //\r
+        // PRIVATE VARS\r
+        //\r
+       var $_oldRaiseFn =  false;\r
+       var $_transOK = null;\r
+       var $_connectionID      = false;        /// The returned link identifier whenever a successful database connection is made.     \r
+       var $_errorMsg = false;         /// A variable which was used to keep the returned last error message.  The value will\r
+                                                               /// then returned by the errorMsg() function    \r
+       var $_errorCode = false;        /// Last error code, not guaranteed to be used - only by oci8                                   \r
+       var $_queryID = false;          /// This variable keeps the last created result link identifier\r
+       \r
+       var $_isPersistentConnection = false;   /// A boolean variable to state whether its a persistent connection or normal connection.       */\r
+       var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.\r
+       var $_evalAll = false;\r
+       var $_affected = false;\r
+       var $_logsql = false;\r
+       \r
+\r
+       \r
+       /**\r
+        * Constructor\r
+        */\r
+       function ADOConnection()                        \r
+       {\r
+               die('Virtual Class -- cannot instantiate');\r
+       }\r
+       \r
+       function Version()\r
+       {\r
+       global $ADODB_vers;\r
+       \r
+               return (float) substr($ADODB_vers,1);\r
+       }\r
+       \r
+       /**\r
+               Get server version info...\r
+               \r
+               @returns An array with 2 elements: $arr['string'] is the description string, \r
+                       and $arr[version] is the version (also a string).\r
+       */\r
+       function ServerInfo()\r
+       {\r
+               return array('description' => '', 'version' => '');\r
+       }\r
+       \r
+       function _findvers($str)\r
+       {\r
+               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];\r
+               else return '';\r
+       }\r
+       \r
+       /**\r
+       * All error messages go through this bottleneck function.\r
+       * You can define your own handler by defining the function name in ADODB_OUTP.\r
+       */\r
+       function outp($msg,$newline=true)\r
+       {\r
+       global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP;\r
+       \r
+               if (defined('ADODB_OUTP')) {\r
+                       $fn = ADODB_OUTP;\r
+                       $fn($msg,$newline);\r
+                       return;\r
+               } else if (isset($ADODB_OUTP)) {\r
+                       $fn = $ADODB_OUTP;\r
+                       $fn($msg,$newline);\r
+                       return;\r
+               }\r
+               \r
+               if ($newline) $msg .= "<br>\n";\r
+               \r
+               if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;\r
+               else echo strip_tags($msg);\r
+               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  do not flush if output buffering enabled - useless - thx to Jesse Mullan \r
+               \r
+       }\r
+       \r
+       function Time()\r
+       {\r
+               $rs =& $this->Execute("select $this->sysTimeStamp");\r
+               if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));\r
+               \r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * Connect to database\r
+        *\r
+        * @param [argHostname]         Host to connect to\r
+        * @param [argUsername]         Userid to login\r
+        * @param [argPassword]         Associated password\r
+        * @param [argDatabaseName]     database\r
+        * @param [forceNew]            force new connection\r
+        *\r
+        * @return true or false\r
+        */       \r
+       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) \r
+       {\r
+               if ($argHostname != "") $this->host = $argHostname;\r
+               if ($argUsername != "") $this->user = $argUsername;\r
+               if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons\r
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;         \r
+               \r
+               $this->_isPersistentConnection = false; \r
+               if ($forceNew) {\r
+                       if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
+               } else {\r
+                        if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;\r
+               }\r
+               $err = $this->ErrorMsg();\r
+               if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";\r
+               if ($fn = $this->raiseErrorFn) \r
+                       $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);\r
+               \r
+               if ($this->debug) ADOConnection::outp( $this->host.': '.$err);\r
+               return false;\r
+       }       \r
+       \r
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)\r
+       {\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Always force a new connection to database - currently only works with oracle\r
+        *\r
+        * @param [argHostname]         Host to connect to\r
+        * @param [argUsername]         Userid to login\r
+        * @param [argPassword]         Associated password\r
+        * @param [argDatabaseName]     database\r
+        *\r
+        * @return true or false\r
+        */       \r
+       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") \r
+       {\r
+               return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);\r
+       }\r
+       \r
+       /**\r
+        * Establish persistent connect to database\r
+        *\r
+        * @param [argHostname]         Host to connect to\r
+        * @param [argUsername]         Userid to login\r
+        * @param [argPassword]         Associated password\r
+        * @param [argDatabaseName]     database\r
+        *\r
+        * @return return true or false\r
+        */     \r
+       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")\r
+       {\r
+               if (defined('ADODB_NEVER_PERSIST')) \r
+                       return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);\r
+               \r
+               if ($argHostname != "") $this->host = $argHostname;\r
+               if ($argUsername != "") $this->user = $argUsername;\r
+               if ($argPassword != "") $this->password = $argPassword;\r
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;         \r
+                       \r
+               $this->_isPersistentConnection = true;  \r
+               if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
+               $err = $this->ErrorMsg();\r
+               if (empty($err)) {\r
+                       $err = "Connection error to server '$argHostname' with user '$argUsername'";\r
+               }       \r
+               if ($fn = $this->raiseErrorFn) {\r
+                       $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);\r
+               }\r
+               \r
+               if ($this->debug) ADOConnection::outp( $this->host.': '.$err);\r
+               return false;\r
+       }\r
+\r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysDate;\r
+               return $col; // child class implement\r
+       }\r
+       \r
+       /**\r
+        * Should prepare the sql statement and return the stmt resource.\r
+        * For databases that do not support this, we return the $sql. To ensure\r
+        * compatibility with databases that do not support prepare:\r
+        *\r
+        *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");\r
+        *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');\r
+        *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');\r
+        *\r
+        * @param sql   SQL to send to database\r
+        *\r
+        * @return return FALSE, or the prepared statement, or the original sql if\r
+        *                      if the database does not support prepare.\r
+        *\r
+        */     \r
+       function Prepare($sql)\r
+       {\r
+               return $sql;\r
+       }\r
+\r
+       /**\r
+        * Some databases, eg. mssql require a different function for preparing\r
+        * stored procedures. So we cannot use Prepare().\r
+        *\r
+        * Should prepare the stored procedure  and return the stmt resource.\r
+        * For databases that do not support this, we return the $sql. To ensure\r
+        * compatibility with databases that do not support prepare:\r
+        *\r
+        * @param sql   SQL to send to database\r
+        *\r
+        * @return return FALSE, or the prepared statement, or the original sql if\r
+        *                      if the database does not support prepare.\r
+        *\r
+        */     \r
+       function PrepareSP($sql,$param=true)\r
+       {\r
+               return $this->Prepare($sql,$param);\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat\r
+       */\r
+       function Quote($s)\r
+       {\r
+               return $this->qstr($s,false);\r
+       }\r
+       \r
+       /**\r
+        Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>\r
+       */\r
+       function QMagic($s)\r
+       {\r
+               return $this->qstr($s,get_magic_quotes_gpc());\r
+       }\r
+\r
+       function q(&$s)\r
+       {\r
+               $s = $this->qstr($s,false);\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function ErrorNative()\r
+       {\r
+               return $this->ErrorNo();\r
+       }\r
+\r
+       \r
+   /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function nextId($seq_name)\r
+       {\r
+               return $this->GenID($seq_name);\r
+       }\r
+\r
+       /**\r
+       *        Lock a row, will escalate and lock the table if row locking not supported\r
+       *       will normally free the lock at the end of the transaction\r
+       *\r
+       *  @param $table        name of table to lock\r
+       *  @param $where        where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock\r
+       */\r
+       function RowLock($table,$where)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function CommitLock($table)\r
+       {\r
+               return $this->CommitTrans();\r
+       }\r
+       \r
+       function RollbackLock($table)\r
+       {\r
+               return $this->RollbackTrans();\r
+       }\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       *\r
+       * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical\r
+       *       for easy porting :-)\r
+       *\r
+       * @param mode   The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM\r
+       * @returns              The previous fetch mode\r
+       */\r
+       function SetFetchMode($mode)\r
+       {       \r
+               $old = $this->fetchMode;\r
+               $this->fetchMode = $mode;\r
+               \r
+               if ($old === false) {\r
+               global $ADODB_FETCH_MODE;\r
+                       return $ADODB_FETCH_MODE;\r
+               }\r
+               return $old;\r
+       }\r
+       \r
+\r
+       /**\r
+       * PEAR DB Compat - do not use internally. \r
+       */\r
+       function &Query($sql, $inputarr=false)\r
+       {\r
+               $rs = &$this->Execute($sql, $inputarr);\r
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+               return $rs;\r
+       }\r
+\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function &LimitQuery($sql, $offset, $count, $params=false)\r
+       {\r
+               $rs = &$this->SelectLimit($sql, $count, $offset, $params); \r
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+               return $rs;\r
+       }\r
+\r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function Disconnect()\r
+       {\r
+               return $this->Close();\r
+       }\r
+       \r
+       /*\r
+                Returns placeholder for parameter, eg.\r
+                $DB->Param('a')\r
+                \r
+                will return ':a' for Oracle, and '?' for most other databases...\r
+                \r
+                For databases that require positioned params, eg $1, $2, $3 for postgresql,\r
+                       pass in Param(false) before setting the first parameter.\r
+       */\r
+       function Param($name)\r
+       {\r
+               return '?';\r
+       }\r
+       \r
+       /*\r
+               InParameter and OutParameter are self-documenting versions of Parameter().\r
+       */\r
+       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)\r
+       {\r
+               return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);\r
+       }\r
+       \r
+       /*\r
+       */\r
+       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)\r
+       {\r
+               return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);\r
+       \r
+       }\r
+       \r
+       /* \r
+       Usage in oracle\r
+               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');\r
+               $db->Parameter($stmt,$id,'myid');\r
+               $db->Parameter($stmt,$group,'group',64);\r
+               $db->Execute();\r
+               \r
+               @param $stmt Statement returned by Prepare() or PrepareSP().\r
+               @param $var PHP variable to bind to\r
+               @param $name Name of stored procedure variable name to bind to.\r
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
+               @param [$maxLen] Holds an maximum length of the variable.\r
+               @param [$type] The data type of $var. Legal values depend on driver.\r
+\r
+       */\r
+       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+               Improved method of initiating a transaction. Used together with CompleteTrans().\r
+               Advantages include:\r
+               \r
+               a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.\r
+                  Only the outermost block is treated as a transaction.<br>\r
+               b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>\r
+               c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block\r
+                  are disabled, making it backward compatible.\r
+       */\r
+       function StartTrans($errfn = 'ADODB_TransMonitor')\r
+       {\r
+               if ($this->transOff > 0) {\r
+                       $this->transOff += 1;\r
+                       return;\r
+               }\r
+               \r
+               $this->_oldRaiseFn = $this->raiseErrorFn;\r
+               $this->raiseErrorFn = $errfn;\r
+               $this->_transOK = true;\r
+               \r
+               if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");\r
+               $this->BeginTrans();\r
+               $this->transOff = 1;\r
+       }\r
+       \r
+       \r
+       /**\r
+               Used together with StartTrans() to end a transaction. Monitors connection\r
+               for sql errors, and will commit or rollback as appropriate.\r
+               \r
+               @autoComplete if true, monitor sql errors and commit and rollback as appropriate, \r
+               and if set to false force rollback even if no SQL error detected.\r
+               @returns true on commit, false on rollback.\r
+       */\r
+       function CompleteTrans($autoComplete = true)\r
+       {\r
+               if ($this->transOff > 1) {\r
+                       $this->transOff -= 1;\r
+                       return true;\r
+               }\r
+               $this->raiseErrorFn = $this->_oldRaiseFn;\r
+               \r
+               $this->transOff = 0;\r
+               if ($this->_transOK && $autoComplete) {\r
+                       if (!$this->CommitTrans()) {\r
+                               $this->_transOK = false;\r
+                               if ($this->debug) ADOConnection::outp("Smart Commit failed");\r
+                       } else\r
+                               if ($this->debug) ADOConnection::outp("Smart Commit occurred");\r
+               } else {\r
+                       $this->RollbackTrans();\r
+                       if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");\r
+               }\r
+               \r
+               return $this->_transOK;\r
+       }\r
+       \r
+       /*\r
+               At the end of a StartTrans/CompleteTrans block, perform a rollback.\r
+       */\r
+       function FailTrans()\r
+       {\r
+               if ($this->debug) \r
+                       if ($this->transOff == 0) {\r
+                               ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");\r
+                       } else {\r
+                               ADOConnection::outp("FailTrans was called");\r
+                               adodb_backtrace();\r
+                       }\r
+               $this->_transOK = false;\r
+       }\r
+       \r
+       /**\r
+               Check if transaction has failed, only for Smart Transactions.\r
+       */\r
+       function HasFailedTrans()\r
+       {\r
+               if ($this->transOff > 0) return $this->_transOK == false;\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * Execute SQL \r
+        *\r
+        * @param sql           SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)\r
+        * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.\r
+        * @return              RecordSet or false\r
+        */\r
+       function &Execute($sql,$inputarr=false) \r
+       {\r
+               if ($this->fnExecute) {\r
+                       $fn = $this->fnExecute;\r
+                       $ret =& $fn($this,$sql,$inputarr);\r
+                       if (isset($ret)) return $ret;\r
+               }\r
+               if ($inputarr && is_array($inputarr)) {\r
+                       $element0 = reset($inputarr);\r
+                       # is_object check because oci8 descriptors can be passed in\r
+                       $array_2d = is_array($element0) && !is_object(reset($element0));\r
+                       \r
+                       if (!is_array($sql) && !$this->_bindInputArray) {\r
+                               $sqlarr = explode('?',$sql);\r
+                                       \r
+                               if (!$array_2d) $inputarr = array($inputarr);\r
+                               foreach($inputarr as $arr) {\r
+                                       $sql = ''; $i = 0;\r
+                                       foreach($arr as $v) {\r
+                                               $sql .= $sqlarr[$i];\r
+                                               // from Ron Baldwin <ron.baldwin@sourceprose.com>\r
+                                               // Only quote string types      \r
+                                               if (gettype($v) == 'string')\r
+                                                       $sql .= $this->qstr($v);\r
+                                               else if ($v === null)\r
+                                                       $sql .= 'NULL';\r
+                                               else\r
+                                                       $sql .= $v;\r
+                                               $i += 1;\r
+                                       }\r
+                                       $sql .= $sqlarr[$i];\r
+                                       \r
+                                       if ($i+1 != sizeof($sqlarr))    \r
+                                               ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));\r
+               \r
+                                       $ret =& $this->_Execute($sql,false);\r
+                                       if (!$ret) return $ret;\r
+                               }       \r
+                       } else {\r
+                               if ($array_2d) {\r
+                                       $stmt = $this->Prepare($sql);\r
+                                       foreach($inputarr as $arr) {\r
+                                               $ret =& $this->_Execute($stmt,$arr);\r
+                                               if (!$ret) return $ret;\r
+                                       }\r
+                               } else {\r
+                                       $ret =& $this->_Execute($sql,$inputarr);\r
+                               }\r
+                       }\r
+               } else {\r
+                       $ret =& $this->_Execute($sql,false);\r
+               }\r
+\r
+               return $ret;\r
+       }\r
+       \r
+       function& _Execute($sql,$inputarr=false)\r
+       {\r
+\r
+               if ($this->debug) {\r
+               global $HTTP_SERVER_VARS;\r
+               \r
+                       $ss = '';\r
+                       if ($inputarr) {\r
+                               foreach($inputarr as $kk=>$vv) {\r
+                                       if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';\r
+                                       $ss .= "($kk=>'$vv') ";\r
+                               }\r
+                               $ss = "[ $ss ]";\r
+                       }\r
+                       $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);\r
+                       \r
+                       // check if running from browser or command-line\r
+                       $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);\r
+                       \r
+                       if ($inBrowser) {\r
+                               if ($this->debug === -1)\r
+                                       ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);\r
+                               else \r
+                                       ADOConnection::outp( "<hr>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr>\n",false);\r
+                       } else {\r
+                               ADOConnection::outp("-----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);\r
+                       }\r
+                       $this->_queryID = $this->_query($sql,$inputarr);\r
+                       /* \r
+                               Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql\r
+                               because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion\r
+                       */\r
+                       if ($this->databaseType == 'mssql') { \r
+                       // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6\r
+                               if($emsg = $this->ErrorMsg()) {\r
+                                       if ($err = $this->ErrorNo()) ADOConnection::outp($err.': '.$emsg);\r
+                               }\r
+                       } else if (!$this->_queryID) {\r
+                               ADOConnection::outp($this->ErrorNo() .': '. $this->ErrorMsg());\r
+                       }       \r
+               } else {\r
+                       //****************************\r
+                       // non-debug version of query\r
+                       //****************************\r
+                       \r
+                       $this->_queryID =@$this->_query($sql,$inputarr);\r
+               }\r
+               \r
+               /************************\r
+               // OK, query executed\r
+               *************************/\r
+\r
+               if ($this->_queryID === false) {\r
+               // error handling if query fails\r
+                       if ($this->debug == 99) adodb_backtrace(true,5);        \r
+                       $fn = $this->raiseErrorFn;\r
+                       if ($fn) {\r
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);\r
+                       } \r
+                               \r
+                       return false;\r
+               } \r
+               \r
+               \r
+               if ($this->_queryID === true) {\r
+               // return simplified empty recordset for inserts/updates/deletes with lower overhead\r
+                       $rs =& new ADORecordSet_empty();\r
+                       #if (is_array($sql)) $rs->sql = $sql[0];\r
+                       #else $rs->sql = $sql;\r
+                       return $rs;\r
+               }\r
+               \r
+               // return real recordset from select statement\r
+               $rsclass = $this->rsPrefix.$this->databaseType;\r
+               $rs =& new $rsclass($this->_queryID,$this->fetchMode);\r
+               $rs->connection = &$this; // Pablo suggestion\r
+               $rs->Init();\r
+               if (is_array($sql)) $rs->sql = $sql[0];\r
+               else $rs->sql = $sql;\r
+               if ($rs->_numOfRows <= 0) {\r
+               global $ADODB_COUNTRECS;\r
+                       if ($ADODB_COUNTRECS) {\r
+                               if (!$rs->EOF){ \r
+                                       $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));\r
+                                       $rs->_queryID = $this->_queryID;\r
+                               } else\r
+                                       $rs->_numOfRows = 0;\r
+                       }\r
+               }\r
+               return $rs;\r
+       }\r
+\r
+       function CreateSequence($seqname='adodbseq',$startID=1)\r
+       {\r
+               if (empty($this->_genSeqSQL)) return false;\r
+               return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));\r
+       }\r
+\r
+       function DropSequence($seqname)\r
+       {\r
+               if (empty($this->_dropSeqSQL)) return false;\r
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
+       }\r
+\r
+       /**\r
+        * Generates a sequence id and stores it in $this->genID;\r
+        * GenID is only available if $this->hasGenID = true;\r
+        *\r
+        * @param seqname               name of sequence to use\r
+        * @param startID               if sequence does not exist, start at this ID\r
+        * @return              0 if not supported, otherwise a sequence id\r
+        */\r
+       function GenID($seqname='adodbseq',$startID=1)\r
+       {\r
+               if (!$this->hasGenID) {\r
+                       return 0; // formerly returns false pre 1.60\r
+               }\r
+               \r
+               $getnext = sprintf($this->_genIDSQL,$seqname);\r
+               \r
+               $holdtransOK = $this->_transOK;\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       $this->_transOK = $holdtransOK; //if the status was ok before reset\r
+                       $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);\r
+               else $this->genID = 0; // false\r
+       \r
+               if ($rs) $rs->Close();\r
+\r
+               return $this->genID;\r
+       }       \r
+\r
+       /**\r
+        * @return  the last inserted ID. Not all databases support this.\r
+        */ \r
+       function Insert_ID()\r
+       {\r
+               if ($this->_logsql && $this->lastInsID) return $this->lastInsID;\r
+               if ($this->hasInsertID) return $this->_insertid();\r
+               if ($this->debug) {\r
+                       ADOConnection::outp( '<p>Insert_ID error</p>');\r
+                       adodb_backtrace();\r
+               }\r
+               return false;\r
+       }\r
+\r
+\r
+       /**\r
+        * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>\r
+        *\r
+        * @return  the last inserted ID. All databases support this. But aware possible\r
+        * problems in multiuser environments. Heavy test this before deploying.\r
+        */ \r
+       function PO_Insert_ID($table="", $id="") \r
+       {\r
+          if ($this->hasInsertID){\r
+                  return $this->Insert_ID();\r
+          } else {\r
+                  return $this->GetOne("SELECT MAX($id) FROM $table");\r
+          }\r
+       }\r
+\r
+       /**\r
+       * @return # rows affected by UPDATE/DELETE\r
+       */ \r
+       function Affected_Rows()\r
+       {\r
+               if ($this->hasAffectedRows) {\r
+                       if ($this->fnExecute === 'adodb_log_sql') {\r
+                               if ($this->_logsql && $this->_affected !== false) return $this->_affected;\r
+                       }\r
+                       $val = $this->_affectedrows();\r
+                       return ($val < 0) ? false : $val;\r
+               }\r
+                                 \r
+               if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);\r
+               return false;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @return  the last error message\r
+        */\r
+       function ErrorMsg()\r
+       {\r
+               return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @return the last error number. Normally 0 means no error.\r
+        */\r
+       function ErrorNo() \r
+       {\r
+               return ($this->_errorMsg) ? -1 : 0;\r
+       }\r
+       \r
+       function MetaError($err=false)\r
+       {\r
+               include_once(ADODB_DIR."/adodb-error.inc.php");\r
+               if ($err === false) $err = $this->ErrorNo();\r
+               return adodb_error($this->dataProvider,$this->databaseType,$err);\r
+       }\r
+       \r
+       function MetaErrorMsg($errno)\r
+       {\r
+               include_once(ADODB_DIR."/adodb-error.inc.php");\r
+               return adodb_errormsg($errno);\r
+       }\r
+       \r
+       /**\r
+        * @returns an array with the primary key columns in it.\r
+        */\r
+       function MetaPrimaryKeys($table, $owner=false)\r
+       {\r
+       // owner not used in base class - see oci8\r
+               $p = array();\r
+               $objs =& $this->MetaColumns($table);\r
+               if ($objs) {\r
+                       foreach($objs as $v) {\r
+                               if (!empty($v->primary_key))\r
+                                       $p[] = $v->name;\r
+                       }\r
+               }\r
+               if (sizeof($p)) return $p;\r
+               if (function_exists('ADODB_VIEW_PRIMARYKEYS'))\r
+                       return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * @returns assoc array where keys are tables, and values are foreign keys\r
+        */\r
+       function MetaForeignKeys($table, $owner=false, $upper=false)\r
+       {\r
+               return false;\r
+       }\r
+       /**\r
+        * Choose a database to connect to. Many databases do not support this.\r
+        *\r
+        * @param dbName        is the name of the database to select\r
+        * @return              true or false\r
+        */\r
+       function SelectDB($dbName) \r
+       {return false;}\r
+       \r
+       \r
+       /**\r
+       * Will select, getting rows from $offset (1-based), for $nrows. \r
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
+       * eg. \r
+       *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)\r
+       *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)\r
+       *\r
+       * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)\r
+       * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set\r
+       *\r
+       * @param sql\r
+       * @param [offset]       is the row to start calculations from (1-based)\r
+       * @param [nrows]                is the number of rows to get\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [secs2cache]           is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               if ($this->hasTop && $nrows > 0) {\r
+               // suggested by Reinhard Balling. Access requires top after distinct \r
+                // Informix requires first before distinct - F Riosa\r
+                       $ismssql = (strpos($this->databaseType,'mssql') !== false);\r
+                       if ($ismssql) $isaccess = false;\r
+                       else $isaccess = (strpos($this->databaseType,'access') !== false);\r
+                       \r
+                       if ($offset <= 0) {\r
+                               \r
+                                       // access includes ties in result\r
+                                       if ($isaccess) {\r
+                                               $sql = preg_replace(\r
+                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
+\r
+                                               if ($secs2cache>0) {\r
+                                                       $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);\r
+                                               } else {\r
+                                                       $ret =& $this->Execute($sql,$inputarr);\r
+                                               }\r
+                                               return $ret; // PHP5 fix\r
+                                       } else if ($ismssql){\r
+                                               $sql = preg_replace(\r
+                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
+                                       } else {\r
+                                               $sql = preg_replace(\r
+                                               '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
+                                       }\r
+                       } else {\r
+                               $nn = $nrows + $offset;\r
+                               if ($isaccess || $ismssql) {\r
+                                       $sql = preg_replace(\r
+                                       '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);\r
+                               } else {\r
+                                       $sql = preg_replace(\r
+                                       '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows\r
+               // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.\r
+               global $ADODB_COUNTRECS;\r
+               \r
+               $savec = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = false;\r
+                       \r
+               if ($offset>0){\r
+                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
+                       else $rs = &$this->Execute($sql,$inputarr);\r
+               } else {\r
+                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
+                       else $rs = &$this->Execute($sql,$inputarr);\r
+               }\r
+               $ADODB_COUNTRECS = $savec;\r
+               if ($rs && !$rs->EOF) {\r
+                       $rs =& $this->_rs2rs($rs,$nrows,$offset);\r
+               }\r
+               //print_r($rs);\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+       * Create serializable recordset. Breaks rs link to connection.\r
+       *\r
+       * @param rs                     the recordset to serialize\r
+       */\r
+       function &SerializableRS(&$rs)\r
+       {\r
+               $rs2 =& $this->_rs2rs($rs);\r
+               $ignore = false;\r
+               $rs2->connection =& $ignore;\r
+               \r
+               return $rs2;\r
+       }\r
+       \r
+       /**\r
+       * Convert database recordset to an array recordset\r
+       * input recordset's cursor should be at beginning, and\r
+       * old $rs will be closed.\r
+       *\r
+       * @param rs                     the recordset to copy\r
+       * @param [nrows]        number of rows to retrieve (optional)\r
+       * @param [offset]       offset by number of rows (optional)\r
+       * @return                       the new recordset\r
+       */\r
+       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)\r
+       {\r
+               if (! $rs) return false;\r
+               \r
+               $dbtype = $rs->databaseType;\r
+               if (!$dbtype) {\r
+                       $rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?\r
+                       return $rs;\r
+               }\r
+               if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {\r
+                       $rs->MoveFirst();\r
+                       $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?\r
+                       return $rs;\r
+               }\r
+               $flds = array();\r
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
+                       $flds[] = $rs->FetchField($i);\r
+               }\r
+\r
+               $arr =& $rs->GetArrayLimit($nrows,$offset);\r
+               //print_r($arr);\r
+               if ($close) $rs->Close();\r
+               \r
+               $arrayClass = $this->arrayClass;\r
+               \r
+               $rs2 =& new $arrayClass();\r
+               $rs2->connection = &$this;\r
+               $rs2->sql = $rs->sql;\r
+               $rs2->dataProvider = $this->dataProvider;\r
+               $rs2->InitArrayFields($arr,$flds);\r
+               return $rs2;\r
+       }\r
+       \r
+       /*\r
+       * Return all rows. Compat with PEAR DB\r
+       */\r
+       function &GetAll($sql, $inputarr=false)\r
+       {\r
+               $arr =& $this->GetArray($sql,$inputarr);\r
+               return $arr;\r
+       }\r
+       \r
+       function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)\r
+       {\r
+               $rs =& $this->Execute($sql, $inputarr);\r
+               if (!$rs) return false;\r
+               \r
+               $arr =& $rs->GetAssoc($force_array,$first2cols);\r
+               return $arr;\r
+       }\r
+       \r
+       function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)\r
+       {\r
+               if (!is_numeric($secs2cache)) {\r
+                       $first2cols = $force_array;\r
+                       $force_array = $inputarr;\r
+               }\r
+               $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);\r
+               if (!$rs) return false;\r
+               \r
+               $arr =& $rs->GetAssoc($force_array,$first2cols);\r
+               return $arr;\r
+       }\r
+       \r
+       /**\r
+       * Return first element of first row of sql statement. Recordset is disposed\r
+       * for you.\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function GetOne($sql,$inputarr=false)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $crecs = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = false;\r
+               \r
+               $ret = false;\r
+               $rs = &$this->Execute($sql,$inputarr);\r
+               if ($rs) {              \r
+                       if (!$rs->EOF) $ret = reset($rs->fields);\r
+                       $rs->Close();\r
+               } \r
+               $ADODB_COUNTRECS = $crecs;\r
+               return $ret;\r
+       }\r
+       \r
+       function CacheGetOne($secs2cache,$sql=false,$inputarr=false)\r
+       {\r
+               $ret = false;\r
+               $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
+               if ($rs) {              \r
+                       if (!$rs->EOF) $ret = reset($rs->fields);\r
+                       $rs->Close();\r
+               } \r
+               \r
+               return $ret;\r
+       }\r
+       \r
+       function GetCol($sql, $inputarr = false, $trim = false)\r
+       {\r
+               $rv = false;\r
+               $rs = &$this->Execute($sql, $inputarr);\r
+               if ($rs) {\r
+                       $rv = array();\r
+                       if ($trim) {\r
+                               while (!$rs->EOF) {\r
+                                       $rv[] = trim(reset($rs->fields));\r
+                                       $rs->MoveNext();\r
+                               }\r
+                       } else {\r
+                               while (!$rs->EOF) {\r
+                                       $rv[] = reset($rs->fields);\r
+                                       $rs->MoveNext();\r
+                               }\r
+                       }\r
+                       $rs->Close();\r
+               }\r
+               return $rv;\r
+       }\r
+       \r
+       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)\r
+       {\r
+               $rv = false;\r
+               $rs = &$this->CacheExecute($secs, $sql, $inputarr);\r
+               if ($rs) {\r
+                       if ($trim) {\r
+                               while (!$rs->EOF) {\r
+                                       $rv[] = trim(reset($rs->fields));\r
+                                       $rs->MoveNext();\r
+                               }\r
+                       } else {\r
+                               while (!$rs->EOF) {\r
+                                       $rv[] = reset($rs->fields);\r
+                                       $rs->MoveNext();\r
+                               }\r
+                       }\r
+                       $rs->Close();\r
+               }\r
+               return $rv;\r
+       }\r
\r
+       /*\r
+               Calculate the offset of a date for a particular database and generate\r
+                       appropriate SQL. Useful for calculating future/past dates and storing\r
+                       in a database.\r
+                       \r
+               If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.\r
+       */\r
+       function OffsetDate($dayFraction,$date=false)\r
+       {               \r
+               if (!$date) $date = $this->sysDate;\r
+               return  '('.$date.'+'.$dayFraction.')';\r
+       }\r
+       \r
+       \r
+       /**\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function &GetArray($sql,$inputarr=false)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               \r
+               $savec = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = false;\r
+               $rs =& $this->Execute($sql,$inputarr);\r
+               $ADODB_COUNTRECS = $savec;\r
+               if (!$rs) \r
+                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+                       else return false;\r
+               $arr =& $rs->GetArray();\r
+               $rs->Close();\r
+               return $arr;\r
+       }\r
+       \r
+       function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)\r
+       {\r
+               return $this->CacheGetArray($secs2cache,$sql,$inputarr);\r
+       }\r
+       \r
+       function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               \r
+               $savec = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = false;\r
+               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);\r
+               $ADODB_COUNTRECS = $savec;\r
+               \r
+               if (!$rs) \r
+                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
+                       else return false;\r
+               \r
+               $arr =& $rs->GetArray();\r
+               $rs->Close();\r
+               return $arr;\r
+       }\r
+       \r
+       \r
+       \r
+       /**\r
+       * Return one row of sql statement. Recordset is disposed for you.\r
+       *\r
+       * @param sql                    SQL statement\r
+       * @param [inputarr]             input bind array\r
+       */\r
+       function &GetRow($sql,$inputarr=false)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $crecs = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = false;\r
+               \r
+               $rs =& $this->Execute($sql,$inputarr);\r
+               \r
+               $ADODB_COUNTRECS = $crecs;\r
+               if ($rs) {\r
+                       if (!$rs->EOF) $arr = $rs->fields;\r
+                       else $arr = array();\r
+                       $rs->Close();\r
+                       return $arr;\r
+               }\r
+               \r
+               return false;\r
+       }\r
+       \r
+       function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)\r
+       {\r
+               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);\r
+               if ($rs) {\r
+                       $arr = false;\r
+                       if (!$rs->EOF) $arr = $rs->fields;\r
+                       $rs->Close();\r
+                       return $arr;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+       * Insert or replace a single record. Note: this is not the same as MySQL's replace. \r
+       * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.\r
+       * Also note that no table locking is done currently, so it is possible that the\r
+       * record be inserted twice by two programs...\r
+       *\r
+       * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');\r
+       *\r
+       * $table                table name\r
+       * $fieldArray   associative array of data (you must quote strings yourself).\r
+       * $keyCol               the primary key field name or if compound key, array of field names\r
+       * autoQuote             set to true to use a hueristic to quote strings. Works with nulls and numbers\r
+       *                                       but does not work with dates nor SQL functions.\r
+       * has_autoinc   the primary key is an auto-inc field, so skip in insert.\r
+       *\r
+       * Currently blob replace not supported\r
+       *\r
+       * returns 0 = fail, 1 = update, 2 = insert \r
+       */\r
+       \r
+       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)\r
+       {\r
+               global $ADODB_INCLUDED_LIB;\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               \r
+               return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);\r
+       }\r
+       \r
+       \r
+       /**\r
+       * Will select, getting rows from $offset (1-based), for $nrows. \r
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
+       * eg. \r
+       *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)\r
+       *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)\r
+       *\r
+       * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set\r
+       *\r
+       * @param [secs2cache]   seconds to cache data, set to 0 to force query. This is optional\r
+       * @param sql\r
+       * @param [offset]       is the row to start calculations from (1-based)\r
+       * @param [nrows]        is the number of rows to get\r
+       * @param [inputarr]     array of bind variables\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)\r
+       {       \r
+               if (!is_numeric($secs2cache)) {\r
+                       if ($sql === false) $sql = -1;\r
+                       if ($offset == -1) $offset = false;\r
+                                                                         // sql,       nrows, offset,inputarr\r
+                       $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);\r
+               } else {\r
+                       if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");\r
+                       $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+               }\r
+               return $rs;\r
+       }\r
+       \r
+       /**\r
+       * Flush cached recordsets that match a particular $sql statement. \r
+       * If $sql == false, then we purge all files in the cache.\r
+       */\r
+       function CacheFlush($sql=false,$inputarr=false)\r
+       {\r
+       global $ADODB_CACHE_DIR;\r
+       \r
+               if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {\r
+                       if (strncmp(PHP_OS,'WIN',3) === 0) {\r
+                               $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';\r
+                       } else {\r
+                               $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; \r
+                               // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';\r
+                       }\r
+                       if ($this->debug) {\r
+                               ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");\r
+                       } else {\r
+                               exec($cmd);\r
+                       }\r
+                       return;\r
+               } \r
+               $f = $this->_gencachename($sql.serialize($inputarr),false);\r
+               adodb_write_file($f,''); // is adodb_write_file needed?\r
+               if (!@unlink($f)) {\r
+                       if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");\r
+               }\r
+       }\r
+       \r
+       /**\r
+       * Private function to generate filename for caching.\r
+       * Filename is generated based on:\r
+       *\r
+       *  - sql statement\r
+       *  - database type (oci8, ibase, ifx, etc)\r
+       *  - database name\r
+       *  - userid\r
+       *  - setFetchMode (adodb 4.23)\r
+       *\r
+       * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). \r
+       * Assuming that we can have 50,000 files per directory with good performance, \r
+       * then we can scale to 12.8 million unique cached recordsets. Wow!\r
+       */\r
+       function _gencachename($sql,$createdir)\r
+       {\r
+       global $ADODB_CACHE_DIR;\r
+       static $notSafeMode;\r
+               \r
+               if ($this->fetchMode === false) { \r
+               global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               } else {\r
+                       $mode = $this->fetchMode;\r
+               }\r
+               $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);\r
+               \r
+               if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');\r
+               $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;\r
+                       \r
+               if ($createdir && $notSafeMode && !file_exists($dir)) {\r
+                       $oldu = umask(0);\r
+                       if (!mkdir($dir,0771)) \r
+                               if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");\r
+                       umask($oldu);\r
+               }\r
+               return $dir.'/adodb_'.$m.'.cache';\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Execute SQL, caching recordsets.\r
+        *\r
+        * @param [secs2cache]  seconds to cache data, set to 0 to force query. \r
+        *                                        This is an optional parameter.\r
+        * @param sql           SQL statement to execute\r
+        * @param [inputarr]    holds the input data  to bind to\r
+        * @return              RecordSet or false\r
+        */\r
+       function &CacheExecute($secs2cache,$sql=false,$inputarr=false)\r
+       {\r
+               if (!is_numeric($secs2cache)) {\r
+                       $inputarr = $sql;\r
+                       $sql = $secs2cache;\r
+                       $secs2cache = $this->cacheSecs;\r
+               }\r
+               global $ADODB_INCLUDED_CSV;\r
+               if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
+               \r
+               if (is_array($sql)) $sql = $sql[0];\r
+                       \r
+               $md5file = $this->_gencachename($sql.serialize($inputarr),true);\r
+               $err = '';\r
+               \r
+               if ($secs2cache > 0){\r
+                       $rs = &csv2rs($md5file,$err,$secs2cache);\r
+                       $this->numCacheHits += 1;\r
+               } else {\r
+                       $err='Timeout 1';\r
+                       $rs = false;\r
+                       $this->numCacheMisses += 1;\r
+               }\r
+               if (!$rs) {\r
+               // no cached rs found\r
+                       if ($this->debug) {\r
+                               if (get_magic_quotes_runtime()) {\r
+                                       ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");\r
+                               }\r
+                               if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");\r
+                       }\r
+                       $rs = &$this->Execute($sql,$inputarr);\r
+                       if ($rs) {\r
+                               $eof = $rs->EOF;\r
+                               $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately\r
+                               $txt = _rs2serialize($rs,false,$sql); // serialize\r
+               \r
+                               if (!adodb_write_file($md5file,$txt,$this->debug)) {\r
+                                       if ($fn = $this->raiseErrorFn) {\r
+                                               $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);\r
+                                       }\r
+                                       if ($this->debug) ADOConnection::outp( " Cache write error");\r
+                               }\r
+                               if ($rs->EOF && !$eof) {\r
+                                       $rs->MoveFirst();\r
+                                       //$rs = &csv2rs($md5file,$err);         \r
+                                       $rs->connection = &$this; // Pablo suggestion\r
+                               }  \r
+                               \r
+                       } else\r
+                               @unlink($md5file);\r
+               } else {\r
+                       $this->_errorMsg = '';\r
+                       $this->_errorCode = 0;\r
+                       \r
+                       if ($this->fnCacheExecute) {\r
+                               $fn = $this->fnCacheExecute;\r
+                               $fn($this, $secs2cache, $sql, $inputarr);\r
+                       }\r
+               // ok, set cached object found\r
+                       $rs->connection = &$this; // Pablo suggestion\r
+                       if ($this->debug){ \r
+                       global $HTTP_SERVER_VARS;\r
+                                       \r
+                               $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);\r
+                               $ttl = $rs->timeCreated + $secs2cache - time();\r
+                               $s = is_array($sql) ? $sql[0] : $sql;\r
+                               if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';\r
+                               \r
+                               ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");\r
+                       }\r
+               }\r
+               return $rs;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Generates an Update Query based on an existing recordset.\r
+        * $arrFields is an associative array of fields with the value\r
+        * that should be assigned.\r
+        *\r
+        * Note: This function should only be used on a recordset\r
+        *         that is run against a single table and sql should only \r
+        *               be a simple select stmt with no groupby/orderby/limit\r
+        *\r
+        * "Jonathan Younger" <jyounger@unilab.com>\r
+        */\r
+       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$forcenulls=null)\r
+       {\r
+               global $ADODB_INCLUDED_LIB;\r
+               if (!isset($forcenulls)) {\r
+                       $forcenulls = defined('ADODB_FORCE_NULLS') ? true : false;\r
+               }\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);\r
+       }\r
+\r
+\r
+       /**\r
+        * Generates an Insert Query based on an existing recordset.\r
+        * $arrFields is an associative array of fields with the value\r
+        * that should be assigned.\r
+        *\r
+        * Note: This function should only be used on a recordset\r
+        *         that is run against a single table.\r
+        */\r
+       function GetInsertSQL(&$rs, $arrFields,$magicq=false,$forcenulls=null)\r
+       {       \r
+               global $ADODB_INCLUDED_LIB;\r
+               if (!isset($forcenulls)) {\r
+                       $forcenulls = defined('ADODB_FORCE_NULLS') ? true : false;\r
+               }\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);\r
+       }\r
+       \r
+\r
+       /**\r
+       * Update a blob column, given a where clause. There are more sophisticated\r
+       * blob handling functions that we could have implemented, but all require\r
+       * a very complex API. Instead we have chosen something that is extremely\r
+       * simple to understand and use. \r
+       *\r
+       * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.\r
+       *\r
+       * Usage to update a $blobvalue which has a primary key blob_id=1 into a \r
+       * field blobtable.blobcolumn:\r
+       *\r
+       *       UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');\r
+       *\r
+       * Insert example:\r
+       *\r
+       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+       *       $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       \r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;\r
+       }\r
+\r
+       /**\r
+       * Usage:\r
+       *       UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');\r
+       *       \r
+       *       $blobtype supports 'BLOB' and 'CLOB'\r
+       *\r
+       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+       *       $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');\r
+       */\r
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')\r
+       {\r
+               $fd = fopen($path,'rb');\r
+               if ($fd === false) return false;\r
+               $val = fread($fd,filesize($path));\r
+               fclose($fd);\r
+               return $this->UpdateBlob($table,$column,$val,$where,$blobtype);\r
+       }\r
+       \r
+       function BlobDecode($blob)\r
+       {\r
+               return $blob;\r
+       }\r
+       \r
+       function BlobEncode($blob)\r
+       {\r
+               return $blob;\r
+       }\r
+       \r
+       function SetCharSet($charset)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";\r
+       }\r
+       \r
+       function LogSQL($enable=true)\r
+       {\r
+               include_once(ADODB_DIR.'/adodb-perf.inc.php');\r
+               \r
+               if ($enable) $this->fnExecute = 'adodb_log_sql';\r
+               else $this->fnExecute = false;\r
+               \r
+               $old = $this->_logsql;  \r
+               $this->_logsql = $enable;\r
+               if ($enable && !$old) $this->_affected = false;\r
+               return $old;\r
+       }\r
+       \r
+       function GetCharSet()\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+       * Usage:\r
+       *       UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');\r
+       *\r
+       *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');\r
+       *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');\r
+       */\r
+       function UpdateClob($table,$column,$val,$where)\r
+       {\r
+               return $this->UpdateBlob($table,$column,$val,$where,'CLOB');\r
+       }\r
+       \r
+       \r
+       /**\r
+       *  Change the SQL connection locale to a specified locale.\r
+       *  This is used to get the date formats written depending on the client locale.\r
+       */\r
+       function SetDateLocale($locale = 'En')\r
+       {\r
+               $this->locale = $locale;\r
+               switch ($locale)\r
+               {\r
+                       default:\r
+                       case 'En':\r
+                               $this->fmtDate="Y-m-d";\r
+                               $this->fmtTimeStamp = "Y-m-d H:i:s";\r
+                               break;\r
+       \r
+                       case 'Fr':\r
+                       case 'Ro':\r
+                       case 'It':\r
+                               $this->fmtDate="d-m-Y";\r
+                               $this->fmtTimeStamp = "d-m-Y H:i:s";\r
+                               break;\r
+                               \r
+                       case 'Ge':\r
+                               $this->fmtDate="d.m.Y";\r
+                               $this->fmtTimeStamp = "d.m.Y H:i:s";\r
+                               break;\r
+               }\r
+       }\r
+\r
+       \r
+       /**\r
+        * Close Connection\r
+        */\r
+       function Close() \r
+       {\r
+               return $this->_close();\r
+               \r
+               // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need \r
+               // to be closed too!\r
+               //if ($this->_isPersistentConnection != true) return $this->_close();\r
+               //else return true;     \r
+       }\r
+       \r
+       /**\r
+        * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().\r
+        *\r
+        * @return true if succeeded or false if database does not support transactions\r
+        */\r
+       function BeginTrans() {return false;}\r
+       \r
+       \r
+       /**\r
+        * If database does not support transactions, always return true as data always commited\r
+        *\r
+        * @param $ok  set to false to rollback transaction, true to commit\r
+        *\r
+        * @return true/false.\r
+        */\r
+       function CommitTrans($ok=true) \r
+       { return true;}\r
+       \r
+       \r
+       /**\r
+        * If database does not support transactions, rollbacks always fail, so return false\r
+        *\r
+        * @return true/false.\r
+        */\r
+       function RollbackTrans() \r
+       { return false;}\r
+\r
+\r
+       /**\r
+        * return the databases that the driver can connect to. \r
+        * Some databases will return an empty array.\r
+        *\r
+        * @return an array of database names.\r
+        */\r
+               function MetaDatabases() \r
+               {\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+                       if ($this->metaDatabasesSQL) {\r
+                               $save = $ADODB_FETCH_MODE; \r
+                               $ADODB_FETCH_MODE = ADODB_FETCH_NUM; \r
+                               \r
+                               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+                               \r
+                               $arr = $this->GetCol($this->metaDatabasesSQL);\r
+                               if (isset($savem)) $this->SetFetchMode($savem);\r
+                               $ADODB_FETCH_MODE = $save; \r
+                       \r
+                               return $arr;\r
+                       }\r
+                       \r
+                       return false;\r
+               }\r
+               \r
+       /**\r
+        * @param ttype can either be 'VIEW' or 'TABLE' or false. \r
+        *              If false, both views and tables are returned.\r
+        *              "VIEW" returns only views\r
+        *              "TABLE" returns only tables\r
+        * @param showSchema returns the schema/user with the table name, eg. USER.TABLE\r
+        * @param mask  is the input mask - only supported by oci8 and postgresql\r
+        *\r
+        * @return  array of tables for current database.\r
+        */ \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               if ($mask) return false;\r
+               \r
+               if ($this->metaTablesSQL) {\r
+                       // complicated state saving by the need for backward compat\r
+                       $save = $ADODB_FETCH_MODE; \r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM; \r
+                       \r
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+                       \r
+                       $rs = $this->Execute($this->metaTablesSQL);\r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save; \r
+                       \r
+                       if ($rs === false) return false;\r
+                       $arr =& $rs->GetArray();\r
+                       $arr2 = array();\r
+                       \r
+                       if ($hast = ($ttype && isset($arr[0][1]))) { \r
+                               $showt = strncmp($ttype,'T',1);\r
+                       }\r
+                       \r
+                       for ($i=0; $i < sizeof($arr); $i++) {\r
+                               if ($hast) {\r
+                                       if ($showt == 0) {\r
+                                               if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);\r
+                                       } else {\r
+                                               if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);\r
+                                       }\r
+                               } else\r
+                                       $arr2[] = trim($arr[$i][0]);\r
+                       }\r
+                       $rs->Close();\r
+                       return $arr2;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       \r
+       function _findschema(&$table,&$schema)\r
+       {\r
+               if (!$schema && ($at = strpos($table,'.')) !== false) {\r
+                       $schema = substr($table,0,$at);\r
+                       $table = substr($table,$at+1);\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * List columns in a database as an array of ADOFieldObjects. \r
+        * See top of file for definition of object.\r
+        *\r
+        * @param table table name to query\r
+        * @param upper uppercase table name (required by some databases)\r
+        * @schema is optional database schema to use - not supported by all databases.\r
+        *\r
+        * @return  array of ADOFieldObjects for current table.\r
+        */\r
+       function &MetaColumns($table,$upper=true) \r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               \r
+               if (!empty($this->metaColumnsSQL)) {\r
+               \r
+                       $schema = false;\r
+                       $this->_findschema($table,$schema);\r
+               \r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));\r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld =& new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               if (isset($rs->fields[3]) && $rs->fields[3]) {\r
+                                       if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];\r
+                                       $fld->scale = $rs->fields[4];\r
+                                       if ($fld->scale>0) $fld->max_length += 1;\r
+                               } else\r
+                                       $fld->max_length = $rs->fields[2];\r
+                                       \r
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                               else $retarr[strtoupper($fld->name)] = $fld;\r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+       \r
+    /**\r
+      * List indexes on a table as an array.\r
+      * @param table        table name to query\r
+      * @param primary include primary keys.\r
+         *\r
+      * @return array of indexes on current table.\r
+      */\r
+     function &MetaIndexes($table, $primary = false, $owner = false)\r
+     {\r
+             return FALSE;\r
+     }\r
+\r
+       /**\r
+        * List columns names in a table as an array. \r
+        * @param table table name to query\r
+        *\r
+        * @return  array of column names for current table.\r
+        */ \r
+       function &MetaColumnNames($table, $numIndexes=false) \r
+       {\r
+               $objarr =& $this->MetaColumns($table);\r
+               if (!is_array($objarr)) return false;\r
+               \r
+               $arr = array();\r
+               if ($numIndexes) {\r
+                       $i = 0;\r
+                       foreach($objarr as $v) $arr[$i++] = $v->name;\r
+               } else\r
+                       foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;\r
+               \r
+               return $arr;\r
+       }\r
+                       \r
+       /**\r
+        * Different SQL databases used different methods to combine strings together.\r
+        * This function provides a wrapper. \r
+        * \r
+        * param s      variable number of string parameters\r
+        *\r
+        * Usage: $db->Concat($str1,$str2);\r
+        * \r
+        * @return concatenated string\r
+        */      \r
+       function Concat()\r
+       {       \r
+               $arr = func_get_args();\r
+               return implode($this->concat_operator, $arr);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Converts a date "d" to a string that the database can understand.\r
+        *\r
+        * @param d     a date in Unix date time format.\r
+        *\r
+        * @return  date string in database date format\r
+        */\r
+       function DBDate($d)\r
+       {\r
+               if (empty($d) && $d !== 0) return 'null';\r
+\r
+               if (is_string($d) && !is_numeric($d)) {\r
+                       if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;\r
+                       if ($this->isoDates) return "'$d'";\r
+                       $d = ADOConnection::UnixDate($d);\r
+               }\r
+\r
+               return adodb_date($this->fmtDate,$d);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Converts a timestamp "ts" to a string that the database can understand.\r
+        *\r
+        * @param ts    a timestamp in Unix date time format.\r
+        *\r
+        * @return  timestamp string in database timestamp format\r
+        */\r
+       function DBTimeStamp($ts)\r
+       {\r
+               if (empty($ts) && $ts !== 0) return 'null';\r
+\r
+               # strlen(14) allows YYYYMMDDHHMMSS format\r
+               if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) \r
+                       return adodb_date($this->fmtTimeStamp,$ts);\r
+               \r
+               if ($ts === 'null') return $ts;\r
+               if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";\r
+               \r
+               $ts = ADOConnection::UnixTimeStamp($ts);\r
+               return adodb_date($this->fmtTimeStamp,$ts);\r
+       }\r
+       \r
+       /**\r
+        * Also in ADORecordSet.\r
+        * @param $v is a date string in YYYY-MM-DD format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
+        */\r
+       function UnixDate($v)\r
+       {\r
+               if (is_numeric($v) && strlen($v) !== 8) return $v;\r
+               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", \r
+                       ($v), $rr)) return false;\r
+\r
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+               // h-m-s-MM-DD-YY\r
+               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+\r
+       /**\r
+        * Also in ADORecordSet.\r
+        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
+        */\r
+       function UnixTimeStamp($v)\r
+       {\r
+               if (!preg_match( \r
+                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", \r
+                       ($v), $rr)) return false;\r
+                       \r
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;\r
+       \r
+               // h-m-s-MM-DD-YY\r
+               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
+               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+       /**\r
+        * Also in ADORecordSet.\r
+        *\r
+        * Format database date based on user defined format.\r
+        *\r
+        * @param v     is the character date in YYYY-MM-DD format, returned by database\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a date formated as user desires\r
+        */\r
+        \r
+       function UserDate($v,$fmt='Y-m-d',$gmt=false)\r
+       {\r
+               $tt = $this->UnixDate($v);\r
+\r
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               else if ($tt == 0) return $this->emptyDate;\r
+               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR\r
+               }\r
+               \r
+               return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);\r
+       \r
+       }\r
+       \r
+               /**\r
+        *\r
+        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a timestamp formated as user desires\r
+        */\r
+       function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)\r
+       {\r
+               # strlen(14) allows YYYYMMDDHHMMSS format\r
+               if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);\r
+               $tt = $this->UnixTimeStamp($v);\r
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               if ($tt == 0) return $this->emptyTimeStamp;\r
+               return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);\r
+       }\r
+       \r
+       /**\r
+       * Quotes a string, without prefixing nor appending quotes. \r
+       */\r
+       function addq($s,$magic_quotes=false)\r
+       {\r
+               if (!$magic_quotes) {\r
+               \r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               // only since php 4.0.5\r
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
+                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));\r
+                       }\r
+                       return  str_replace("'",$this->replaceQuote,$s);\r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               \r
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything\r
+                       return $s;\r
+               else {// change \' to '' for sybase/mssql\r
+                       $s = str_replace('\\\\','\\',$s);\r
+                       return str_replace("\\'",$this->replaceQuote,$s);\r
+               }\r
+       }\r
+       \r
+       /**\r
+        * Correctly quotes a string so that all strings are escaped. We prefix and append\r
+        * to the string single-quotes.\r
+        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());\r
+        * \r
+        * @param s                     the string to quote\r
+        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().\r
+        *                              This undoes the stupidity of magic quotes for GPC.\r
+        *\r
+        * @return  quoted string to be sent back to database\r
+        */\r
+       function qstr($s,$magic_quotes=false)\r
+       {       \r
+               if (!$magic_quotes) {\r
+               \r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               // only since php 4.0.5\r
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
+                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));\r
+                       }\r
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";\r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               \r
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything\r
+                       return "'$s'";\r
+               else {// change \' to '' for sybase/mssql\r
+                       $s = str_replace('\\\\','\\',$s);\r
+                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";\r
+               }\r
+       }\r
+       \r
+       \r
+       /**\r
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
+       *\r
+       * See readme.htm#ex8 for an example of usage.\r
+       *\r
+       * @param sql\r
+       * @param nrows          is the number of rows per page to get\r
+       * @param page           is the page number to get (1-based)\r
+       * @param [inputarr]     array of bind variables\r
+       * @param [secs2cache]           is a private parameter only used by jlim\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       *\r
+       * NOTE: phpLens uses a different algorithm and does not use PageExecute().\r
+       *\r
+       */\r
+       function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) \r
+       {\r
+               global $ADODB_INCLUDED_LIB;\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);\r
+               else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);\r
+               return $rs;\r
+       }\r
+       \r
+               \r
+       /**\r
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
+       *\r
+       * @param secs2cache     seconds to cache data, set to 0 to force query\r
+       * @param sql\r
+       * @param nrows          is the number of rows per page to get\r
+       * @param page           is the page number to get (1-based)\r
+       * @param [inputarr]     array of bind variables\r
+       * @return               the recordset ($rs->databaseType == 'array')\r
+       */\r
+       function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) \r
+       {\r
+               /*switch($this->dataProvider) {\r
+               case 'postgres':\r
+               case 'mysql': \r
+                       break;\r
+               default: $secs2cache = 0; break;\r
+               }*/\r
+               $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);\r
+               return $rs;\r
+       }\r
+\r
+} // end class ADOConnection\r
+       \r
+       \r
+       \r
+       //==============================================================================================        \r
+       // CLASS ADOFetchObj\r
+       //==============================================================================================        \r
+               \r
+       /**\r
+       * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().\r
+       */\r
+       class ADOFetchObj {\r
+       };\r
+       \r
+       //==============================================================================================        \r
+       // CLASS ADORecordSet_empty\r
+       //==============================================================================================        \r
+       \r
+       /**\r
+       * Lightweight recordset when there are no records to be returned\r
+       */\r
+       class ADORecordSet_empty\r
+       {\r
+               var $dataProvider = 'empty';\r
+               var $databaseType = false;\r
+               var $EOF = true;\r
+               var $_numOfRows = 0;\r
+               var $fields = false;\r
+               var $connection = false;\r
+               function RowCount() {return 0;}\r
+               function RecordCount() {return 0;}\r
+               function PO_RecordCount(){return 0;}\r
+               function Close(){return true;}\r
+               function FetchRow() {return false;}\r
+               function FieldCount(){ return 0;}\r
+               function Init() {}\r
+       }\r
+       \r
+       //==============================================================================================        \r
+       // DATE AND TIME FUNCTIONS\r
+       //==============================================================================================        \r
+       include_once(ADODB_DIR.'/adodb-time.inc.php');\r
+       \r
+       //==============================================================================================        \r
+       // CLASS ADORecordSet\r
+       //==============================================================================================        \r
+\r
+       if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');\r
+       else include_once(ADODB_DIR.'/adodb-iterator.inc.php');\r
+   /**\r
+        * RecordSet class that represents the dataset returned by the database.\r
+        * To keep memory overhead low, this class holds only the current row in memory.\r
+        * No prefetching of data is done, so the RecordCount() can return -1 ( which\r
+        * means recordcount not known).\r
+        */\r
+       class ADORecordSet extends ADODB_BASE_RS {\r
+       /*\r
+        * public variables     \r
+        */\r
+       var $dataProvider = "native";\r
+       var $fields = false;    /// holds the current row data\r
+       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob\r
+                                                       /// in other words, we use a text area for editing.\r
+       var $canSeek = false;   /// indicates that seek is supported\r
+       var $sql;                               /// sql text\r
+       var $EOF = false;               /// Indicates that the current record position is after the last record in a Recordset object. \r
+       \r
+       var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0\r
+       var $emptyDate = '&nbsp;'; /// what to display when $time==0\r
+       var $debug = false;\r
+       var $timeCreated=0;     /// datetime in Unix format rs created -- for cached recordsets\r
+\r
+       var $bind = false;              /// used by Fields() to hold array - should be private?\r
+       var $fetchMode;                 /// default fetch mode\r
+       var $connection = false; /// the parent connection\r
+       /*\r
+        *      private variables       \r
+        */\r
+       var $_numOfRows = -1;   /** number of rows, or -1 */\r
+       var $_numOfFields = -1; /** number of fields in recordset */\r
+       var $_queryID = -1;             /** This variable keeps the result link identifier.     */\r
+       var $_currentRow = -1;  /** This variable keeps the current row in the Recordset.       */\r
+       var $_closed = false;   /** has recordset been closed */\r
+       var $_inited = false;   /** Init() should only be called once */\r
+       var $_obj;                              /** Used by FetchObj */\r
+       var $_names;                    /** Used by FetchObj */\r
+       \r
+       var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */\r
+       var $_atFirstPage = false;      /** Added by Iván Oliva to implement recordset pagination */\r
+       var $_atLastPage = false;       /** Added by Iván Oliva to implement recordset pagination */\r
+       var $_lastPageNo = -1; \r
+       var $_maxRecordCount = 0;\r
+       var $datetime = false;\r
+       \r
+       /**\r
+        * Constructor\r
+        *\r
+        * @param queryID       this is the queryID returned by ADOConnection->_query()\r
+        *\r
+        */\r
+       function ADORecordSet($queryID) \r
+       {\r
+               $this->_queryID = $queryID;\r
+       }\r
+       \r
+       \r
+       \r
+       function Init()\r
+       {\r
+               if ($this->_inited) return;\r
+               $this->_inited = true;\r
+               if ($this->_queryID) @$this->_initrs();\r
+               else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+               }\r
+               if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {\r
+                       \r
+                       $this->_currentRow = 0;\r
+                       if ($this->EOF = ($this->_fetch() === false)) {\r
+                               $this->_numOfRows = 0; // _numOfRows could be -1\r
+                       }\r
+               } else {\r
+                       $this->EOF = true;\r
+               }\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Generate a SELECT tag string from a recordset, and return the string.\r
+        * If the recordset has 2 cols, we treat the 1st col as the containing \r
+        * the text to display to the user, and 2nd col as the return value. Default\r
+        * strings are compared with the FIRST column.\r
+        *\r
+        * @param name                  name of SELECT tag\r
+        * @param [defstr]              the value to hilite. Use an array for multiple hilites for listbox.\r
+        * @param [blank1stItem]        true to leave the 1st item in list empty\r
+        * @param [multiple]            true for listbox, false for popup\r
+        * @param [size]                #rows to show for listbox. not used by popup\r
+        * @param [selectAttr]          additional attributes to defined for SELECT tag.\r
+        *                              useful for holding javascript onChange='...' handlers.\r
+        & @param [compareFields0]      when we have 2 cols in recordset, we compare the defstr with \r
+        *                              column 0 (1st col) if this is true. This is not documented.\r
+        *\r
+        * @return HTML\r
+        *\r
+        * changes by glen.davies@cce.ac.nz to support multiple hilited items\r
+        */\r
+       function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,\r
+                       $size=0, $selectAttr='',$compareFields0=true)\r
+       {\r
+               global $ADODB_INCLUDED_LIB;\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,\r
+                       $size, $selectAttr,$compareFields0);\r
+       }\r
+       \r
+       /**\r
+        * Generate a SELECT tag string from a recordset, and return the string.\r
+        * If the recordset has 2 cols, we treat the 1st col as the containing \r
+        * the text to display to the user, and 2nd col as the return value. Default\r
+        * strings are compared with the SECOND column.\r
+        *\r
+        */\r
+       function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')  \r
+       {\r
+               global $ADODB_INCLUDED_LIB;\r
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,\r
+                       $size, $selectAttr,false);\r
+       }\r
+\r
+\r
+       /**\r
+        * return recordset as a 2-dimensional array.\r
+        *\r
+        * @param [nRows]  is the number of rows to return. -1 means every row.\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetArray($nRows = -1) \r
+       {\r
+       global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);\r
+               \r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nRows != $cnt) {\r
+                       $results[] = $this->fields;\r
+                       $this->MoveNext();\r
+                       $cnt++;\r
+               }\r
+               return $results;\r
+       }\r
+       \r
+       function &GetAll($nRows = -1)\r
+       {\r
+               $arr =& $this->GetArray($nRows);\r
+               return $arr;\r
+       }\r
+       \r
+       /*\r
+       * Some databases allow multiple recordsets to be returned. This function\r
+       * will return true if there is a next recordset, or false if no more.\r
+       */\r
+       function NextRecordSet()\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       /**\r
+        * return recordset as a 2-dimensional array. \r
+        * Helper function for ADOConnection->SelectLimit()\r
+        *\r
+        * @param offset        is the row to start calculations from (1-based)\r
+        * @param [nrows]       is the number of rows to return\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {       \r
+               if ($offset <= 0) {\r
+                       $arr =& $this->GetArray($nrows);\r
+                       return $arr;\r
+               } \r
+               \r
+               $this->Move($offset);\r
+               \r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Synonym for GetArray() for compatibility with ADO.\r
+        *\r
+        * @param [nRows]  is the number of rows to return. -1 means every row.\r
+        *\r
+        * @return an array indexed by the rows (0-based) from the recordset\r
+        */\r
+       function &GetRows($nRows = -1) \r
+       {\r
+               $arr =& $this->GetArray($nRows);\r
+               return $arr;\r
+       }\r
+       \r
+       /**\r
+        * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. \r
+        * The first column is treated as the key and is not included in the array. \r
+        * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless\r
+        * $force_array == true.\r
+        *\r
+        * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional\r
+        *      array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,\r
+        *      read the source.\r
+        *\r
+        * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and \r
+        * instead of returning array[col0] => array(remaining cols), return array[col0] => col1\r
+        *\r
+        * @return an associative array indexed by the first column of the array, \r
+        *      or false if the  data has less than 2 cols.\r
+        */\r
+       function &GetAssoc($force_array = false, $first2cols = false) {\r
+               $cols = $this->_numOfFields;\r
+               if ($cols < 2) {\r
+                       return false;\r
+               }\r
+               $numIndex = isset($this->fields[0]);\r
+               $results = array();\r
+               \r
+               if (!$first2cols && ($cols > 2 || $force_array)) {\r
+                       if ($numIndex) {\r
+                               while (!$this->EOF) {\r
+                                       $results[trim($this->fields[0])] = array_slice($this->fields, 1);\r
+                                       $this->MoveNext();\r
+                               }\r
+                       } else {\r
+                               while (!$this->EOF) {\r
+                                       $results[trim(reset($this->fields))] = array_slice($this->fields, 1);\r
+                                       $this->MoveNext();\r
+                               }\r
+                       }\r
+               } else {\r
+                       // return scalar values\r
+                       if ($numIndex) {\r
+                               while (!$this->EOF) {\r
+                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string\r
+                                       $results[trim(($this->fields[0]))] = $this->fields[1];\r
+                                       $this->MoveNext();\r
+                               }\r
+                       } else {\r
+                               while (!$this->EOF) {\r
+                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string\r
+                                       $v1 = trim(reset($this->fields));\r
+                                       $v2 = ''.next($this->fields); \r
+                                       $results[$v1] = $v2;\r
+                                       $this->MoveNext();\r
+                               }\r
+                       }\r
+               }\r
+               return $results; \r
+       }\r
+       \r
+       \r
+       /**\r
+        *\r
+        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a timestamp formated as user desires\r
+        */\r
+       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')\r
+       {\r
+               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);\r
+               $tt = $this->UnixTimeStamp($v);\r
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               if ($tt === 0) return $this->emptyTimeStamp;\r
+               return adodb_date($fmt,$tt);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @param v     is the character date in YYYY-MM-DD format, returned by database\r
+        * @param fmt   is the format to apply to it, using date()\r
+        *\r
+        * @return a date formated as user desires\r
+        */\r
+       function UserDate($v,$fmt='Y-m-d')\r
+       {\r
+               $tt = $this->UnixDate($v);\r
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
+               if (($tt === false || $tt == -1) && $v != false) return $v;\r
+               else if ($tt == 0) return $this->emptyDate;\r
+               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR\r
+               }\r
+               return adodb_date($fmt,$tt);\r
+       }\r
+       \r
+       \r
+       /**\r
+        * @param $v is a date string in YYYY-MM-DD format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
+        */\r
+       function UnixDate($v)\r
+       {\r
+               if (is_numeric($v) && strlen($v) !== 8) return $v;\r
+               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", \r
+                       ($v), $rr)) return false;\r
+                       \r
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR || $rr[1] > 10000) return 0;\r
+               \r
+               // h-m-s-MM-DD-YY\r
+               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+\r
+       /**\r
+        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format\r
+        *\r
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
+        */\r
+       function UnixTimeStamp($v)\r
+       {\r
+               \r
+               if (!preg_match( \r
+                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", \r
+                       ($v), $rr)) return false;\r
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;\r
+       \r
+               // h-m-s-MM-DD-YY\r
+               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
+               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);\r
+       }\r
+       \r
+       \r
+       /**\r
+       * PEAR DB Compat - do not use internally\r
+       */\r
+       function Free()\r
+       {\r
+               return $this->Close();\r
+       }\r
+       \r
+       \r
+       /**\r
+       * PEAR DB compat, number of rows\r
+       */\r
+       function NumRows()\r
+       {\r
+               return $this->_numOfRows;\r
+       }\r
+       \r
+       \r
+       /**\r
+       * PEAR DB compat, number of cols\r
+       */\r
+       function NumCols()\r
+       {\r
+               return $this->_numOfFields;\r
+       }\r
+       \r
+       /**\r
+       * Fetch a row, returning false if no more rows. \r
+       * This is PEAR DB compat mode.\r
+       *\r
+       * @return false or array containing the current record\r
+       */\r
+       function &FetchRow()\r
+       {\r
+               if ($this->EOF) return false;\r
+               $arr = $this->fields;\r
+               $this->_currentRow++;\r
+               if (!$this->_fetch()) $this->EOF = true;\r
+               return $arr;\r
+       }\r
+       \r
+       \r
+       /**\r
+       * Fetch a row, returning PEAR_Error if no more rows. \r
+       * This is PEAR DB compat mode.\r
+       *\r
+       * @return DB_OK or error object\r
+       */\r
+       function FetchInto(&$arr)\r
+       {\r
+               if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;\r
+               $arr = $this->fields;\r
+               $this->MoveNext();\r
+               return 1; // DB_OK\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Move to the first row in the recordset. Many databases do NOT support this.\r
+        *\r
+        * @return true or false\r
+        */\r
+       function MoveFirst() \r
+       {\r
+               if ($this->_currentRow == 0) return true;\r
+               return $this->Move(0);                  \r
+       }                       \r
+\r
+       \r
+       /**\r
+        * Move to the last row in the recordset. \r
+        *\r
+        * @return true or false\r
+        */\r
+       function MoveLast() \r
+       {\r
+               if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);\r
+               if ($this->EOF) return false;\r
+               while (!$this->EOF) {\r
+                       $f = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               $this->fields = $f;\r
+               $this->EOF = false;\r
+               return true;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Move to next record in the recordset.\r
+        *\r
+        * @return true if there still rows available, or false if there are no more rows (EOF).\r
+        */\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {\r
+                       $this->_currentRow++;\r
+                       if ($this->_fetch()) return true;\r
+               }\r
+               $this->EOF = true;\r
+               /* -- tested error handling when scrolling cursor -- seems useless.\r
+               $conn = $this->connection;\r
+               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {\r
+                       $fn = $conn->raiseErrorFn;\r
+                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);\r
+               }\r
+               */\r
+               return false;\r
+       }       \r
+       \r
+       /**\r
+        * Random access to a specific row in the recordset. Some databases do not support\r
+        * access to previous rows in the databases (no scrolling backwards).\r
+        *\r
+        * @param rowNumber is the row to move to (0-based)\r
+        *\r
+        * @return true if there still rows available, or false if there are no more rows (EOF).\r
+        */\r
+       function Move($rowNumber = 0) \r
+       {\r
+               $this->EOF = false;\r
+               if ($rowNumber == $this->_currentRow) return true;\r
+               if ($rowNumber >= $this->_numOfRows)\r
+                       if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;\r
+                               \r
+               if ($this->canSeek) { \r
+       \r
+                       if ($this->_seek($rowNumber)) {\r
+                               $this->_currentRow = $rowNumber;\r
+                               if ($this->_fetch()) {\r
+                                       return true;\r
+                               }\r
+                       } else {\r
+                               $this->EOF = true;\r
+                               return false;\r
+                       }\r
+               } else {\r
+                       if ($rowNumber < $this->_currentRow) return false;\r
+                       global $ADODB_EXTENSION;\r
+                       if ($ADODB_EXTENSION) {\r
+                               while (!$this->EOF && $this->_currentRow < $rowNumber) {\r
+                                       adodb_movenext($this);\r
+                               }\r
+                       } else {\r
+                       \r
+                               while (! $this->EOF && $this->_currentRow < $rowNumber) {\r
+                                       $this->_currentRow++;\r
+                                       \r
+                                       if (!$this->_fetch()) $this->EOF = true;\r
+                               }\r
+                       }\r
+                       return !($this->EOF);\r
+               }\r
+               \r
+               $this->fields = false;  \r
+               $this->EOF = true;\r
+               return false;\r
+       }\r
+       \r
+               \r
+       /**\r
+        * Get the value of a field in the current row by column name.\r
+        * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.\r
+        * \r
+        * @param colname  is the field to access\r
+        *\r
+        * @return the value of $colname column\r
+        */\r
+       function Fields($colname)\r
+       {\r
+               return $this->fields[$colname];\r
+       }\r
+       \r
+       function GetAssocKeys($upper=true)\r
+       {\r
+               $this->bind = array();\r
+               for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                       $o =& $this->FetchField($i);\r
+                       if ($upper === 2) $this->bind[$o->name] = $i;\r
+                       else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;\r
+               }\r
+       }\r
+       \r
+  /**\r
+   * Use associative array to get fields array for databases that do not support\r
+   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it\r
+   *\r
+   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC\r
+   * before you execute your SQL statement, and access $rs->fields['col'] directly.\r
+   *\r
+   * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField\r
+   */\r
+       function &GetRowAssoc($upper=1)\r
+       {\r
+               $record = array();\r
+        //     if (!$this->fields) return $record;\r
+               \r
+               if (!$this->bind) {\r
+                       $this->GetAssocKeys($upper);\r
+               }\r
+               \r
+               foreach($this->bind as $k => $v) {\r
+                       $record[$k] = $this->fields[$v];\r
+               }\r
+\r
+               return $record;\r
+       }\r
+       \r
+       \r
+       /**\r
+        * Clean up recordset\r
+        *\r
+        * @return true or false\r
+        */\r
+       function Close() \r
+       {\r
+               // free connection object - this seems to globally free the object\r
+               // and not merely the reference, so don't do this...\r
+               // $this->connection = false; \r
+               if (!$this->_closed) {\r
+                       $this->_closed = true;\r
+                       return $this->_close();         \r
+               } else\r
+                       return true;\r
+       }\r
+       \r
+       /**\r
+        * synonyms RecordCount and RowCount    \r
+        *\r
+        * @return the number of rows or -1 if this is not supported\r
+        */\r
+       function RecordCount() {return $this->_numOfRows;}\r
+       \r
+       \r
+       /*\r
+       * If we are using PageExecute(), this will return the maximum possible rows\r
+       * that can be returned when paging a recordset.\r
+       */\r
+       function MaxRecordCount()\r
+       {\r
+               return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();\r
+       }\r
+       \r
+       /**\r
+        * synonyms RecordCount and RowCount    \r
+        *\r
+        * @return the number of rows or -1 if this is not supported\r
+        */\r
+       function RowCount() {return $this->_numOfRows;} \r
+       \r
+\r
+        /**\r
+        * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>\r
+        *\r
+        * @return  the number of records from a previous SELECT. All databases support this.\r
+        *\r
+        * But aware possible problems in multiuser environments. For better speed the table\r
+        * must be indexed by the condition. Heavy test this before deploying.\r
+        */ \r
+       function PO_RecordCount($table="", $condition="") {\r
+               \r
+               $lnumrows = $this->_numOfRows;\r
+               // the database doesn't support native recordcount, so we do a workaround\r
+               if ($lnumrows == -1 && $this->connection) {\r
+                       IF ($table) {\r
+                               if ($condition) $condition = " WHERE " . $condition; \r
+                               $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");\r
+                               if ($resultrows) $lnumrows = reset($resultrows->fields);\r
+                       }\r
+               }\r
+               return $lnumrows;\r
+       }\r
+       \r
+       /**\r
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
+        */\r
+       function CurrentRow() {return $this->_currentRow;}\r
+       \r
+       /**\r
+        * synonym for CurrentRow -- for ADO compat\r
+        *\r
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
+        */\r
+       function AbsolutePosition() {return $this->_currentRow;}\r
+       \r
+       /**\r
+        * @return the number of columns in the recordset. Some databases will set this to 0\r
+        * if no records are returned, others will return the number of columns in the query.\r
+        */\r
+       function FieldCount() {return $this->_numOfFields;}   \r
+\r
+\r
+       /**\r
+        * Get the ADOFieldObject of a specific column.\r
+        *\r
+        * @param fieldoffset   is the column position to access(0-based).\r
+        *\r
+        * @return the ADOFieldObject for that column, or false.\r
+        */\r
+       function &FetchField($fieldoffset) \r
+       {\r
+               // must be defined by child class\r
+       }       \r
+       \r
+       /**\r
+        * Get the ADOFieldObjects of all columns in an array.\r
+        *\r
+        */\r
+       function& FieldTypesArray()\r
+       {\r
+               $arr = array();\r
+               for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) \r
+                       $arr[] = $this->FetchField($i);\r
+               return $arr;\r
+       }\r
+       \r
+       /**\r
+       * Return the fields array of the current row as an object for convenience.\r
+       * The default case is lowercase field names.\r
+       *\r
+       * @return the object with the properties set to the fields of the current row\r
+       */\r
+       function &FetchObj()\r
+       {\r
+               $o =& $this->FetchObject(false);\r
+               return $o;\r
+       }\r
+       \r
+       /**\r
+       * Return the fields array of the current row as an object for convenience.\r
+       * The default case is uppercase.\r
+       * \r
+       * @param $isupper to set the object property names to uppercase\r
+       *\r
+       * @return the object with the properties set to the fields of the current row\r
+       */\r
+       function &FetchObject($isupper=true)\r
+       {\r
+               if (empty($this->_obj)) {\r
+                       $this->_obj =& new ADOFetchObj();\r
+                       $this->_names = array();\r
+                       for ($i=0; $i <$this->_numOfFields; $i++) {\r
+                               $f = $this->FetchField($i);\r
+                               $this->_names[] = $f->name;\r
+                       }\r
+               }\r
+               $i = 0;\r
+               $o = &$this->_obj;\r
+               for ($i=0; $i <$this->_numOfFields; $i++) {\r
+                       $name = $this->_names[$i];\r
+                       if ($isupper) $n = strtoupper($name);\r
+                       else $n = $name;\r
+                       \r
+                       $o->$n = $this->Fields($name);\r
+               }\r
+               return $o;\r
+       }\r
+       \r
+       /**\r
+       * Return the fields array of the current row as an object for convenience.\r
+       * The default is lower-case field names.\r
+       * \r
+       * @return the object with the properties set to the fields of the current row,\r
+       *       or false if EOF\r
+       *\r
+       * Fixed bug reported by tim@orotech.net\r
+       */\r
+       function &FetchNextObj()\r
+       {\r
+               return $this->FetchNextObject(false);\r
+       }\r
+       \r
+       \r
+       /**\r
+       * Return the fields array of the current row as an object for convenience. \r
+       * The default is upper case field names.\r
+       * \r
+       * @param $isupper to set the object property names to uppercase\r
+       *\r
+       * @return the object with the properties set to the fields of the current row,\r
+       *       or false if EOF\r
+       *\r
+       * Fixed bug reported by tim@orotech.net\r
+       */\r
+       function &FetchNextObject($isupper=true)\r
+       {\r
+               $o = false;\r
+               if ($this->_numOfRows != 0 && !$this->EOF) {\r
+                       $o = $this->FetchObject($isupper);      \r
+                       $this->_currentRow++;\r
+                       if ($this->_fetch()) return $o;\r
+               }\r
+               $this->EOF = true;\r
+               return $o;\r
+       }\r
+       \r
+       /**\r
+        * Get the metatype of the column. This is used for formatting. This is because\r
+        * many databases use different names for the same type, so we transform the original\r
+        * type to our standardised version which uses 1 character codes:\r
+        *\r
+        * @param t  is the type passed in. Normally is ADOFieldObject->type.\r
+        * @param len is the maximum length of that field. This is because we treat character\r
+        *      fields bigger than a certain size as a 'B' (blob).\r
+        * @param fieldobj is the field object returned by the database driver. Can hold\r
+        *      additional info (eg. primary_key for mysql).\r
+        * \r
+        * @return the general type of the data: \r
+        *      C for character < 250 chars\r
+        *      X for teXt (>= 250 chars)\r
+        *      B for Binary\r
+        *      N for numeric or floating point\r
+        *      D for date\r
+        *      T for timestamp\r
+        *      L for logical/Boolean\r
+        *      I for integer\r
+        *      R for autoincrement counter/integer\r
+        * \r
+        *\r
+       */\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+       // changed in 2.32 to hashing instead of switch stmt for speed...\r
+       static $typeMap = array(\r
+               'VARCHAR' => 'C',\r
+               'VARCHAR2' => 'C',\r
+               'CHAR' => 'C',\r
+               'C' => 'C',\r
+               'STRING' => 'C',\r
+               'NCHAR' => 'C',\r
+               'NVARCHAR' => 'C',\r
+               'VARYING' => 'C',\r
+               'BPCHAR' => 'C',\r
+               'CHARACTER' => 'C',\r
+               'INTERVAL' => 'C',  # Postgres\r
+               ##\r
+               'LONGCHAR' => 'X',\r
+               'TEXT' => 'X',\r
+               'NTEXT' => 'X',\r
+               'M' => 'X',\r
+               'X' => 'X',\r
+               'CLOB' => 'X',\r
+               'NCLOB' => 'X',\r
+               'LVARCHAR' => 'X',\r
+               ##\r
+               'BLOB' => 'B',\r
+               'IMAGE' => 'B',\r
+               'BINARY' => 'B',\r
+               'VARBINARY' => 'B',\r
+               'LONGBINARY' => 'B',\r
+               'B' => 'B',\r
+               ##\r
+               'YEAR' => 'D', // mysql\r
+               'DATE' => 'D',\r
+               'D' => 'D',\r
+               ##\r
+               'TIME' => 'T',\r
+               'TIMESTAMP' => 'T',\r
+               'DATETIME' => 'T',\r
+               'TIMESTAMPTZ' => 'T',\r
+               'T' => 'T',\r
+               ##\r
+               'BOOL' => 'L',\r
+               'BOOLEAN' => 'L', \r
+               'BIT' => 'L',\r
+               'L' => 'L',\r
+               ##\r
+               'COUNTER' => 'R',\r
+               'R' => 'R',\r
+               'SERIAL' => 'R', // ifx\r
+               'INT IDENTITY' => 'R',\r
+               ##\r
+               'INT' => 'I',\r
+               'INTEGER' => 'I',\r
+               'INTEGER UNSIGNED' => 'I',\r
+               'SHORT' => 'I',\r
+               'TINYINT' => 'I',\r
+               'SMALLINT' => 'I',\r
+               'I' => 'I',\r
+               ##\r
+               'LONG' => 'N', // interbase is numeric, oci8 is blob\r
+               'BIGINT' => 'N', // this is bigger than PHP 32-bit integers\r
+               'DECIMAL' => 'N',\r
+               'DEC' => 'N',\r
+               'REAL' => 'N',\r
+               'DOUBLE' => 'N',\r
+               'DOUBLE PRECISION' => 'N',\r
+               'SMALLFLOAT' => 'N',\r
+               'FLOAT' => 'N',\r
+               'NUMBER' => 'N',\r
+               'NUM' => 'N',\r
+               'NUMERIC' => 'N',\r
+               'MONEY' => 'N',\r
+               \r
+               ## informix 9.2\r
+               'SQLINT' => 'I', \r
+               'SQLSERIAL' => 'I', \r
+               'SQLSMINT' => 'I', \r
+               'SQLSMFLOAT' => 'N', \r
+               'SQLFLOAT' => 'N', \r
+               'SQLMONEY' => 'N', \r
+               'SQLDECIMAL' => 'N', \r
+               'SQLDATE' => 'D', \r
+               'SQLVCHAR' => 'C', \r
+               'SQLCHAR' => 'C', \r
+               'SQLDTIME' => 'T', \r
+               'SQLINTERVAL' => 'N', \r
+               'SQLBYTES' => 'B', \r
+               'SQLTEXT' => 'X' \r
+               );\r
+               \r
+               $tmap = false;\r
+               $t = strtoupper($t);\r
+               $tmap = @$typeMap[$t];\r
+               switch ($tmap) {\r
+               case 'C':\r
+               \r
+                       // is the char field is too long, return as text field... \r
+                       if ($this->blobSize >= 0) {\r
+                               if ($len > $this->blobSize) return 'X';\r
+                       } else if ($len > 250) {\r
+                               return 'X';\r
+                       }\r
+                       return 'C';\r
+                       \r
+               case 'I':\r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       return 'I';\r
+               \r
+               case false:\r
+                       return 'N';\r
+                       \r
+               case 'B':\r
+                        if (isset($fieldobj->binary)) \r
+                                return ($fieldobj->binary) ? 'B' : 'X';\r
+                       return 'B';\r
+               \r
+               case 'D':\r
+                       if (!empty($this->datetime)) return 'T';\r
+                       return 'D';\r
+                       \r
+               default: \r
+                       if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';\r
+                       return $tmap;\r
+               }\r
+       }\r
+       \r
+       function _close() {}\r
+       \r
+       /**\r
+        * set/returns the current recordset page when paginating\r
+        */\r
+       function AbsolutePage($page=-1)\r
+       {\r
+               if ($page != -1) $this->_currentPage = $page;\r
+               return $this->_currentPage;\r
+       }\r
+       \r
+       /**\r
+        * set/returns the status of the atFirstPage flag when paginating\r
+        */\r
+       function AtFirstPage($status=false)\r
+       {\r
+               if ($status != false) $this->_atFirstPage = $status;\r
+               return $this->_atFirstPage;\r
+       }\r
+       \r
+       function LastPageNo($page = false)\r
+       {\r
+               if ($page != false) $this->_lastPageNo = $page;\r
+               return $this->_lastPageNo;\r
+       }\r
+       \r
+       /**\r
+        * set/returns the status of the atLastPage flag when paginating\r
+        */\r
+       function AtLastPage($status=false)\r
+       {\r
+               if ($status != false) $this->_atLastPage = $status;\r
+               return $this->_atLastPage;\r
+       }\r
+       \r
+} // end class ADORecordSet\r
+       \r
+       //==============================================================================================        \r
+       // CLASS ADORecordSet_array\r
+       //==============================================================================================        \r
+       \r
+       /**\r
+        * This class encapsulates the concept of a recordset created in memory\r
+        * as an array. This is useful for the creation of cached recordsets.\r
+        * \r
+        * Note that the constructor is different from the standard ADORecordSet\r
+        */\r
+       \r
+       class ADORecordSet_array extends ADORecordSet\r
+       {\r
+               var $databaseType = 'array';\r
+\r
+               var $_array;    // holds the 2-dimensional data array\r
+               var $_types;    // the array of types of each column (C B I L M)\r
+               var $_colnames; // names of each column in array\r
+               var $_skiprow1; // skip 1st row because it holds column names\r
+               var $_fieldarr; // holds array of field objects\r
+               var $canSeek = true;\r
+               var $affectedrows = false;\r
+               var $insertid = false;\r
+               var $sql = '';\r
+               var $compat = false;\r
+               /**\r
+                * Constructor\r
+                *\r
+                */\r
+               function ADORecordSet_array($fakeid=1)\r
+               {\r
+               global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;\r
+               \r
+                       // fetch() on EOF does not delete $this->fields\r
+                       $this->compat = !empty($ADODB_COMPAT_FETCH);\r
+                       $this->ADORecordSet($fakeid); // fake queryID           \r
+                       $this->fetchMode = $ADODB_FETCH_MODE;\r
+               }\r
+               \r
+               \r
+               /**\r
+                * Setup the array.\r
+                *\r
+                * @param array         is a 2-dimensional array holding the data.\r
+                *                      The first row should hold the column names \r
+                *                      unless paramter $colnames is used.\r
+                * @param typearr       holds an array of types. These are the same types \r
+                *                      used in MetaTypes (C,B,L,I,N).\r
+                * @param [colnames]    array of column names. If set, then the first row of\r
+                *                      $array should not hold the column names.\r
+                */\r
+               function InitArray($array,$typearr,$colnames=false)\r
+               {\r
+                       $this->_array = $array;\r
+                       $this->_types = $typearr;       \r
+                       if ($colnames) {\r
+                               $this->_skiprow1 = false;\r
+                               $this->_colnames = $colnames;\r
+                       } else  {\r
+                               $this->_skiprow1 = true;\r
+                               $this->_colnames = $array[0];\r
+                       }\r
+                       $this->Init();\r
+               }\r
+               /**\r
+                * Setup the Array and datatype file objects\r
+                *\r
+                * @param array         is a 2-dimensional array holding the data.\r
+                *                      The first row should hold the column names \r
+                *                      unless paramter $colnames is used.\r
+                * @param fieldarr      holds an array of ADOFieldObject's.\r
+                */\r
+               function InitArrayFields(&$array,&$fieldarr)\r
+               {\r
+                       $this->_array =& $array;\r
+                       $this->_skiprow1= false;\r
+                       if ($fieldarr) {\r
+                               $this->_fieldobjects =& $fieldarr;\r
+                       } \r
+                       $this->Init();\r
+               }\r
+               \r
+               function &GetArray($nRows=-1)\r
+               {\r
+                       if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {\r
+                               return $this->_array;\r
+                       } else {\r
+                               $arr =& ADORecordSet::GetArray($nRows);\r
+                               return $arr;\r
+                       }\r
+               }\r
+               \r
+               function _initrs()\r
+               {\r
+                       $this->_numOfRows =  sizeof($this->_array);\r
+                       if ($this->_skiprow1) $this->_numOfRows -= 1;\r
+               \r
+                       $this->_numOfFields =(isset($this->_fieldobjects)) ?\r
+                                sizeof($this->_fieldobjects):sizeof($this->_types);\r
+               }\r
+               \r
+               /* Use associative array to get fields array */\r
+               function Fields($colname)\r
+               {\r
+                       if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                               if (!isset($this->fields[$colname])) $colname = strtolower($colname);\r
+                               return $this->fields[$colname];\r
+                       }\r
+                       if (!$this->bind) {\r
+                               $this->bind = array();\r
+                               for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                                       $o = $this->FetchField($i);\r
+                                       $this->bind[strtoupper($o->name)] = $i;\r
+                               }\r
+                       }\r
+                       return $this->fields[$this->bind[strtoupper($colname)]];\r
+               }\r
+               \r
+               function &FetchField($fieldOffset = -1) \r
+               {\r
+                       if (isset($this->_fieldobjects)) {\r
+                               return $this->_fieldobjects[$fieldOffset];\r
+                       }\r
+                       $o =  new ADOFieldObject();\r
+                       $o->name = $this->_colnames[$fieldOffset];\r
+                       $o->type =  $this->_types[$fieldOffset];\r
+                       $o->max_length = -1; // length not known\r
+                       \r
+                       return $o;\r
+               }\r
+                       \r
+               function _seek($row)\r
+               {\r
+                       if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {\r
+                               $this->_currentRow = $row;\r
+                               if ($this->_skiprow1) $row += 1;\r
+                               $this->fields = $this->_array[$row];\r
+                               return true;\r
+                       }\r
+                       return false;\r
+               }\r
+               \r
+               function MoveNext() \r
+               {\r
+                       if (!$this->EOF) {              \r
+                               $this->_currentRow++;\r
+                               \r
+                               $pos = $this->_currentRow;\r
+                               \r
+                               if ($this->_numOfRows <= $pos) {\r
+                                       if (!$this->compat) $this->fields = false;\r
+                               } else {\r
+                                       if ($this->_skiprow1) $pos += 1;\r
+                                       $this->fields = $this->_array[$pos];\r
+                                       return true;\r
+                               }               \r
+                               $this->EOF = true;\r
+                       }\r
+                       \r
+                       return false;\r
+               }       \r
+       \r
+               function _fetch()\r
+               {\r
+                       $pos = $this->_currentRow;\r
+                       \r
+                       if ($this->_numOfRows <= $pos) {\r
+                               if (!$this->compat) $this->fields = false;\r
+                               return false;\r
+                       }\r
+                       if ($this->_skiprow1) $pos += 1;\r
+                       $this->fields = $this->_array[$pos];\r
+                       return true;\r
+               }\r
+               \r
+               function _close() \r
+               {\r
+                       return true;    \r
+               }\r
+       \r
+       } // ADORecordSet_array\r
+\r
+       //==============================================================================================        \r
+       // HELPER FUNCTIONS\r
+       //==============================================================================================                        \r
+       \r
+       /**\r
+        * Synonym for ADOLoadCode. Private function. Do not use.\r
+        *\r
+        * @deprecated\r
+        */\r
+       function ADOLoadDB($dbType) \r
+       { \r
+               return ADOLoadCode($dbType);\r
+       }\r
+               \r
+       /**\r
+        * Load the code for a specific database driver. Private function. Do not use.\r
+        */\r
+       function ADOLoadCode($dbType) \r
+       {\r
+       global $ADODB_LASTDB;\r
+       \r
+               if (!$dbType) return false;\r
+               $db = strtolower($dbType);\r
+               switch ($db) {\r
+                       case 'maxsql': $db = 'mysqlt'; break;\r
+                       case 'postgres':\r
+                       case 'pgsql': $db = 'postgres7'; break;\r
+               }\r
+               @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");\r
+               $ADODB_LASTDB = $db;\r
+               \r
+               $ok = class_exists("ADODB_" . $db);\r
+               if ($ok) return $db;\r
+               \r
+               print_r(get_declared_classes());\r
+               $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";\r
+               if (!file_exists($file)) ADOConnection::outp("Missing file: $file");\r
+               else ADOConnection::outp("Syntax error in file: $file");\r
+               return false;\r
+       }\r
+\r
+       /**\r
+        * synonym for ADONewConnection for people like me who cannot remember the correct name\r
+        */\r
+       function &NewADOConnection($db='')\r
+       {\r
+               $tmp =& ADONewConnection($db);\r
+               return $tmp;\r
+       }\r
+       \r
+       /**\r
+        * Instantiate a new Connection class for a specific database driver.\r
+        *\r
+        * @param [db]  is the database Connection object to create. If undefined,\r
+        *      use the last database driver that was loaded by ADOLoadCode().\r
+        *\r
+        * @return the freshly created instance of the Connection class.\r
+        */\r
+       function &ADONewConnection($db='')\r
+       {\r
+       GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;\r
+               \r
+               if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);\r
+               $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;\r
+               \r
+               if (!empty($ADODB_NEWCONNECTION)) {\r
+                       $obj = $ADODB_NEWCONNECTION($db);\r
+                       if ($obj) {\r
+                               if ($errorfn)  $obj->raiseErrorFn = $errorfn;\r
+                               return $obj;\r
+                       }\r
+               }\r
+               \r
+               if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';\r
+               if (empty($db)) $db = $ADODB_LASTDB;\r
+               \r
+               if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);\r
+               \r
+               if (!$db) {\r
+                        if ($errorfn) {\r
+                               // raise an error\r
+                               $ignore = false;\r
+                               $errorfn('ADONewConnection', 'ADONewConnection', -998,\r
+                                                "could not load the database driver for '$db",\r
+                                                $db,false,$ignore);\r
+                       } else\r
+                                ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);\r
+                               \r
+                       return false;\r
+               }\r
+               \r
+               $cls = 'ADODB_'.$db;\r
+               if (!class_exists($cls)) {\r
+                       adodb_backtrace();\r
+                       return false;\r
+               }\r
+               \r
+               $obj =& new $cls();\r
+               if ($errorfn) $obj->raiseErrorFn = $errorfn;\r
+               \r
+               return $obj;\r
+       }\r
+       \r
+       // $perf == true means called by NewPerfMonitor()\r
+       function _adodb_getdriver($provider,$drivername,$perf=false)\r
+       {\r
+               if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') \r
+                       $drivername = $provider;\r
+               else {\r
+                       if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);\r
+                       else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);\r
+                       else \r
+                       switch($drivername) {\r
+                       case 'oracle': $drivername = 'oci8';break;\r
+                       //case 'sybase': $drivername = 'mssql';break;\r
+                       case 'access': \r
+                                               if ($perf) $drivername = '';\r
+                                               break;\r
+                       case 'db2':     \r
+                                               break;\r
+                       default:\r
+                               $drivername = 'generic';\r
+                               break;\r
+                       }\r
+               }\r
+               \r
+               return $drivername;\r
+       }\r
+       \r
+       function &NewPerfMonitor(&$conn)\r
+       {\r
+               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);\r
+               if (!$drivername || $drivername == 'generic') return false;\r
+               include_once(ADODB_DIR.'/adodb-perf.inc.php');\r
+               @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");\r
+               $class = "Perf_$drivername";\r
+               if (!class_exists($class)) return false;\r
+               $perf =& new $class($conn);\r
+               \r
+               return $perf;\r
+       }\r
+       \r
+       function &NewDataDictionary(&$conn)\r
+       {\r
+               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);\r
+               \r
+               include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
+               include_once(ADODB_DIR.'/adodb-datadict.inc.php');\r
+               $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";\r
+\r
+               if (!file_exists($path)) {\r
+                       ADOConnection::outp("Database driver '$path' not available");\r
+                       return false;\r
+               }\r
+               include_once($path);\r
+               $class = "ADODB2_$drivername";\r
+               $dict =& new $class();\r
+               $dict->dataProvider = $conn->dataProvider;\r
+               $dict->connection = &$conn;\r
+               $dict->upperName = strtoupper($drivername);\r
+               $dict->quote = $conn->nameQuote;\r
+               if (!empty($conn->_connectionID))\r
+                       $dict->serverInfo = $conn->ServerInfo();\r
+               \r
+               return $dict;\r
+       }\r
+\r
+\r
+       /**\r
+       * Save a file $filename and its $contents (normally for caching) with file locking\r
+       */\r
+       function adodb_write_file($filename, $contents,$debug=false)\r
+       { \r
+       # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows\r
+       # So to simulate locking, we assume that rename is an atomic operation.\r
+       # First we delete $filename, then we create a $tempfile write to it and \r
+       # rename to the desired $filename. If the rename works, then we successfully \r
+       # modified the file exclusively.\r
+       # What a stupid need - having to simulate locking.\r
+       # Risks:\r
+       # 1. $tempfile name is not unique -- very very low\r
+       # 2. unlink($filename) fails -- ok, rename will fail\r
+       # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs\r
+       # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated\r
+               if (strncmp(PHP_OS,'WIN',3) === 0) {\r
+                       // skip the decimal place\r
+                       $mtime = substr(str_replace(' ','_',microtime()),2); \r
+                       // getmypid() actually returns 0 on Win98 - never mind!\r
+                       $tmpname = $filename.uniqid($mtime).getmypid();\r
+                       if (!($fd = fopen($tmpname,'a'))) return false;\r
+                       $ok = ftruncate($fd,0);                 \r
+                       if (!fwrite($fd,$contents)) $ok = false;\r
+                       fclose($fd);\r
+                       chmod($tmpname,0644);\r
+                       // the tricky moment\r
+                       @unlink($filename);\r
+                       if (!@rename($tmpname,$filename)) {\r
+                               unlink($tmpname);\r
+                               $ok = false;\r
+                       }\r
+                       if (!$ok) {\r
+                               if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));\r
+                       }\r
+                       return $ok;\r
+               }\r
+               if (!($fd = fopen($filename, 'a'))) return false;\r
+               if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {\r
+                       $ok = fwrite( $fd, $contents );\r
+                       fclose($fd);\r
+                       chmod($filename,0644);\r
+               }else {\r
+                       fclose($fd);\r
+                       if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");\r
+                       $ok = false;\r
+               }\r
+       \r
+               return $ok;\r
+       }\r
+       \r
+       /*\r
+               Perform a print_r, with pre tags for better formatting.\r
+       */\r
+       function adodb_pr($var)\r
+       {\r
+               if (isset($_SERVER['HTTP_USER_AGENT'])) { \r
+                       echo " <pre>\n";print_r($var);echo "</pre>\n";\r
+               } else\r
+                       print_r($var);\r
+       }\r
+       \r
+       /*\r
+               Perform a stack-crawl and pretty print it.\r
+               \r
+               @param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).\r
+               @param levels Number of levels to display\r
+       */\r
+       function adodb_backtrace($printOrArr=true,$levels=9999)\r
+       {\r
+               $s = '';\r
+               if (PHPVERSION() < 4.3) return;\r
+                \r
+               $html =  (isset($_SERVER['HTTP_USER_AGENT']));\r
+               $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";\r
+\r
+               $MAXSTRLEN = 64;\r
+       \r
+               $s = ($html) ? '<pre align=left>' : '';\r
+               \r
+               if (is_array($printOrArr)) $traceArr = $printOrArr;\r
+               else $traceArr = debug_backtrace();\r
+               array_shift($traceArr);\r
+               $tabs = sizeof($traceArr)-1;\r
+               \r
+               foreach ($traceArr as $arr) {\r
+                       $levels -= 1;\r
+                       if ($levels < 0) break;\r
+                       \r
+                       $args = array();\r
+                       for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";\r
+                       $tabs -= 1;\r
+                       if ($html) $s .= '<font face="Courier New,Courier">';\r
+                       if (isset($arr['class'])) $s .= $arr['class'].'.';\r
+                       if (isset($arr['args']))\r
+                        foreach($arr['args'] as $v) {\r
+                               if (is_null($v)) $args[] = 'null';\r
+                               else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';\r
+                               else if (is_object($v)) $args[] = 'Object:'.get_class($v);\r
+                               else if (is_bool($v)) $args[] = $v ? 'true' : 'false';\r
+                               else {\r
+                                       $v = (string) @$v;\r
+                                       $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));\r
+                                       if (strlen($v) > $MAXSTRLEN) $str .= '...';\r
+                                       $args[] = $str;\r
+                               }\r
+                       }\r
+                       $s .= $arr['function'].'('.implode(', ',$args).')';\r
+                       \r
+                       \r
+                       $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));\r
+                               \r
+                       $s .= "\n";\r
+               }       \r
+               if ($html) $s .= '</pre>';\r
+               if ($printOrArr) print $s;\r
+               \r
+               return $s;\r
+       }\r
+       \r
+} // defined\r
 ?>
\ No newline at end of file
index c6a4bc53685d20492d2f210c037de07d10d65216..48f02416a8e8dfa8356de6c6bc0e22dc9c652a08 100644 (file)
@@ -1,92 +1,95 @@
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_access extends ADODB_DataDict {
-       
-       var $databaseType = 'access';
-       var $seqField = false;
-       
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'TEXT';
-               case 'XL':
-               case 'X': return 'MEMO'; 
-               
-               case 'C2': return 'TEXT'; // up to 32K
-               case 'X2': return 'MEMO';
-               
-               case 'B': return 'BINARY';
-                       
-               case 'D': return 'DATETIME';
-               case 'T': return 'DATETIME';
-               
-               case 'L': return 'BYTE';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'BYTE';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'INTEGER';
-               
-               case 'F': return 'DOUBLE';
-               case 'N': return 'NUMERIC';
-               default:
-                       return $meta;
-               }
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {
-               if ($fautoinc) {
-                       $ftype = 'COUNTER';
-                       return '';
-               }
-               if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';
-               $suffix = '';
-               if (strlen($fdefault)) {
-                       //$suffix .= " DEFAULT $fdefault";
-                       if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");
-               }
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               return $suffix;
-       }
-       
-       function CreateDatabase($dbname,$options=false)
-       {
-               return array();
-       }
-       
-       
-       function SetSchema($schema)
-       {
-       }
-
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
-               return array();
-       }
-       
-}
-
-
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_access extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'access';\r
+       var $seqField = false;\r
+       \r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'TEXT';\r
+               case 'XL':\r
+               case 'X': return 'MEMO'; \r
+               \r
+               case 'C2': return 'TEXT'; // up to 32K\r
+               case 'X2': return 'MEMO';\r
+               \r
+               case 'B': return 'BINARY';\r
+                       \r
+               case 'D': return 'DATETIME';\r
+               case 'T': return 'DATETIME';\r
+               \r
+               case 'L': return 'BYTE';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'BYTE';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'INTEGER';\r
+               \r
+               case 'F': return 'DOUBLE';\r
+               case 'N': return 'NUMERIC';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {\r
+               if ($fautoinc) {\r
+                       $ftype = 'COUNTER';\r
+                       return '';\r
+               }\r
+               if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';\r
+               $suffix = '';\r
+               if (strlen($fdefault)) {\r
+                       //$suffix .= " DEFAULT $fdefault";\r
+                       if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");\r
+               }\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       function CreateDatabase($dbname,$options=false)\r
+       {\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function SetSchema($schema)\r
+       {\r
+       }\r
+\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+}\r
+\r
+\r
 ?>
\ No newline at end of file
index cadf516107799561cbd110ab90060a75e262703b..769ed4aa3ad161d1432b78e53d5ab9a8296513e8 100644 (file)
@@ -1,74 +1,76 @@
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_db2 extends ADODB_DataDict {
-       
-       var $databaseType = 'db2';
-       var $seqField = false;
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'XL':
-               case 'X': return 'VARCHAR(3600)'; 
-               
-               case 'C2': return 'VARCHAR'; // up to 32K
-               case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'TIMESTAMP';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'BIGINT';
-               
-               case 'F': return 'DOUBLE';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {       
-               $suffix = '';
-               if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with 
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               return $suffix;
-       }
-
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
-               return array();
-       }
-       
-}
-
-
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_db2 extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'db2';\r
+       var $seqField = false;\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL': return 'CLOB';\r
+               case 'X': return 'VARCHAR(3600)'; \r
+               \r
+               case 'C2': return 'VARCHAR'; // up to 32K\r
+               case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'TIMESTAMP';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'BIGINT';\r
+               \r
+               case 'F': return 'DOUBLE';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {       \r
+               $suffix = '';\r
+               if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with \r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+}\r
+\r
+\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/datadict/datadict-firebird.inc.php b/lib/adodb/datadict/datadict-firebird.inc.php
new file mode 100644 (file)
index 0000000..b5068e5
--- /dev/null
@@ -0,0 +1,151 @@
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+class ADODB2_firebird15 extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'firebird15';\r
+       var $seqField = false;\r
+       var $seqPrefix = 'gen_';\r
+       var $blobSize = 40000;  \r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'VARCHAR(4000)'; \r
+               \r
+               case 'C2': return 'VARCHAR'; // up to 32K\r
+               case 'X2': return 'VARCHAR(4000)';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'TIMESTAMP';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'INTEGER';\r
+               \r
+               case 'F': return 'DOUBLE PRECISION';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       function NameQuote($name = NULL)\r
+       {\r
+               if (!is_string($name)) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               $name = trim($name);\r
+               \r
+               if ( !is_object($this->connection) ) {\r
+                       return $name;\r
+               }\r
+               \r
+               $quote = $this->connection->nameQuote;\r
+               \r
+               // if name is of the form `name`, quote it\r
+               if ( preg_match('/^`(.+)`$/', $name, $matches) ) {\r
+                       return $quote . $matches[1] . $quote;\r
+               }\r
+               \r
+               // if name contains special characters, quote it\r
+               if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {\r
+                       return $quote . $name . $quote;\r
+               }\r
+               \r
+               return $quote . $name . $quote;\r
+       }\r
+\r
+       function CreateDatabase($dbname, $options=false)\r
+       {\r
+               $options = $this->_Options($options);\r
+               $sql = array();\r
+               \r
+               $sql[] = "DECLARE EXTERNAL FUNCTION LOWER CSTRING(80) RETURNS CSTRING(80) FREE_IT ENTRY_POINT 'IB_UDF_lower' MODULE_NAME 'ib_udf'";\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       function _DropAutoIncrement($t)\r
+       {\r
+               if (strpos($t,'.') !== false) {\r
+                       $tarr = explode('.',$t);\r
+                       return 'DROP GENERATOR '.$tarr[0].'."gen_'.$tarr[1].'"';\r
+               }\r
+               return 'DROP GENERATOR "GEN_'.$t;\r
+       }\r
+       \r
+\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)\r
+       {\r
+               $suffix = '';\r
+               \r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fautoinc) $this->seqField = $fname;\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               \r
+               return $suffix;\r
+       }\r
+       \r
+/*\r
+CREATE or replace TRIGGER jaddress_insert\r
+before insert on jaddress\r
+for each row\r
+begin\r
+IF ( NEW."seqField" IS NULL OR NEW."seqField" = 0 ) THEN\r
+  NEW."seqField" = GEN_ID("GEN_tabname", 1);\r
+end;\r
+*/\r
+       function _Triggers($tabname,$tableoptions)\r
+       {       \r
+               if (!$this->seqField) return array();\r
+               \r
+               $tab1 = preg_replace( '/"/', '', $tabname );\r
+               if ($this->schema) {\r
+                       $t = strpos($tab1,'.');\r
+                       if ($t !== false) $tab = substr($tab1,$t+1);\r
+                       else $tab = $tab1;\r
+                       $seqField = $this->seqField;\r
+                       $seqname = $this->schema.'.'.$this->seqPrefix.$tab;\r
+                       $trigname = $this->schema.'.trig_'.$this->seqPrefix.$tab;\r
+               } else {\r
+                       $seqField = $this->seqField;\r
+                       $seqname = $this->seqPrefix.$tab1;\r
+                       $trigname = 'trig_'.$seqname;\r
+               }\r
+               if (isset($tableoptions['REPLACE']))\r
+               { $sql[] = "DROP GENERATOR \"$seqname\"";\r
+                 $sql[] = "CREATE GENERATOR \"$seqname\"";\r
+                 $sql[] = "ALTER TRIGGER \"$trigname\" BEFORE INSERT OR UPDATE AS BEGIN IF ( NEW.$seqField IS NULL OR NEW.$seqField = 0 ) THEN NEW.$seqField = GEN_ID(\"$seqname\", 1); END";\r
+               }\r
+               else\r
+               { $sql[] = "CREATE GENERATOR \"$seqname\"";\r
+                 $sql[] = "CREATE TRIGGER \"$trigname\" FOR $tabname BEFORE INSERT OR UPDATE AS BEGIN IF ( NEW.$seqField IS NULL OR NEW.$seqField = 0 ) THEN NEW.$seqField = GEN_ID(\"$seqname\", 1); END";\r
+               }\r
+               \r
+               $this->seqField = false;\r
+               return $sql;\r
+       }\r
+\r
+}\r
+\r
+\r
+?>
\ No newline at end of file
index cb4fc462d11520f753279ca5a58f3386d1d8d5da..15232fcd0c323c095fda005b3c3ef7b7619a2456 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_generic extends ADODB_DataDict {
-       
-       var $databaseType = 'generic';
-       var $seqField = false;
-       
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'XL':
-               case 'X': return 'VARCHAR(250)';
-               
-               case 'C2': return 'VARCHAR';
-               case 'X2': return 'VARCHAR(250)';
-               
-               case 'B': return 'VARCHAR';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'DATE';
-               
-               case 'L': return 'DECIMAL(1)';
-               case 'I': return 'DECIMAL(10)';
-               case 'I1': return 'DECIMAL(3)';
-               case 'I2': return 'DECIMAL(5)';
-               case 'I4': return 'DECIMAL(10)';
-               case 'I8': return 'DECIMAL(20)';
-               
-               case 'F': return 'DECIMAL(32,8)';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
-               return array();
-       }
-       
-}
-
-/*
-//db2
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'X': return 'VARCHAR'; 
-               
-               case 'C2': return 'VARCHAR'; // up to 32K
-               case 'X2': return 'VARCHAR';
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'TIMESTAMP';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'BIGINT';
-               
-               case 'F': return 'DOUBLE';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-       
-// ifx
-function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';// 255
-               case 'X': return 'TEXT'; 
-               
-               case 'C2': return 'NVARCHAR';
-               case 'X2': return 'TEXT';
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'DATETIME';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'DECIMAL(20)';
-               
-               case 'F': return 'FLOAT';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-*/
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_generic extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'generic';\r
+       var $seqField = false;\r
+       \r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'VARCHAR(250)';\r
+               \r
+               case 'C2': return 'VARCHAR';\r
+               case 'X2': return 'VARCHAR(250)';\r
+               \r
+               case 'B': return 'VARCHAR';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'DATE';\r
+               \r
+               case 'L': return 'DECIMAL(1)';\r
+               case 'I': return 'DECIMAL(10)';\r
+               case 'I1': return 'DECIMAL(3)';\r
+               case 'I2': return 'DECIMAL(5)';\r
+               case 'I4': return 'DECIMAL(10)';\r
+               case 'I8': return 'DECIMAL(20)';\r
+               \r
+               case 'F': return 'DECIMAL(32,8)';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+}\r
+\r
+/*\r
+//db2\r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'X': return 'VARCHAR'; \r
+               \r
+               case 'C2': return 'VARCHAR'; // up to 32K\r
+               case 'X2': return 'VARCHAR';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'TIMESTAMP';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'BIGINT';\r
+               \r
+               case 'F': return 'DOUBLE';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+// ifx\r
+function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';// 255\r
+               case 'X': return 'TEXT'; \r
+               \r
+               case 'C2': return 'NVARCHAR';\r
+               case 'X2': return 'TEXT';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'DATETIME';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'DECIMAL(20)';\r
+               \r
+               case 'F': return 'FLOAT';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+*/\r
 ?>
\ No newline at end of file
index 0583b962a2a3fe4e7dc87341ca563d1cb4c47470..558d5560a638c662d6402319b805a4d4f9d5ddbc 100644 (file)
@@ -1,64 +1,67 @@
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_ibase extends ADODB_DataDict {
-       
-       var $databaseType = 'ibase';
-       var $seqField = false;
-       
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'XL':
-               case 'X': return 'VARCHAR(4000)'; 
-               
-               case 'C2': return 'VARCHAR'; // up to 32K
-               case 'X2': return 'VARCHAR(4000)';
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'TIMESTAMP';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'INTEGER';
-               
-               case 'F': return 'DOUBLE PRECISION';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
-               return array();
-       }
-       
-}
-
-
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_ibase extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'ibase';\r
+       var $seqField = false;\r
+       \r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'VARCHAR(4000)'; \r
+               \r
+               case 'C2': return 'VARCHAR'; // up to 32K\r
+               case 'X2': return 'VARCHAR(4000)';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'TIMESTAMP';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'INTEGER';\r
+               \r
+               case 'F': return 'DOUBLE PRECISION';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+}\r
+\r
+\r
 ?>
\ No newline at end of file
index 0064c9a43adb16ea1615f97447170bfaf7cd9348..abc2f613087bd32e243901f6d6467f61726a72eb 100644 (file)
@@ -1,77 +1,80 @@
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_informix extends ADODB_DataDict {
-       
-       var $databaseType = 'informix';
-       var $seqField = false;
-       
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';// 255
-               case 'XL':
-               case 'X': return 'TEXT'; 
-               
-               case 'C2': return 'NVARCHAR';
-               case 'X2': return 'TEXT';
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'DATETIME';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'INTEGER';
-               case 'I8': return 'DECIMAL(20)';
-               
-               case 'F': return 'FLOAT';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }
-       }
-
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
-               return array();
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {
-               if ($fautoinc) {
-                       $ftype = 'SERIAL';
-                       return '';
-               }
-               $suffix = '';
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               return $suffix;
-       }
-       
-}
-
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_informix extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'informix';\r
+       var $seqField = false;\r
+       \r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';// 255\r
+               case 'XL':\r
+               case 'X': return 'TEXT'; \r
+               \r
+               case 'C2': return 'NVARCHAR';\r
+               case 'X2': return 'TEXT';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'DATETIME';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INTEGER';\r
+               case 'I8': return 'DECIMAL(20)';\r
+               \r
+               case 'F': return 'FLOAT';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
+               return array();\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {\r
+               if ($fautoinc) {\r
+                       $ftype = 'SERIAL';\r
+                       return '';\r
+               }\r
+               $suffix = '';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+}\r
+\r
 ?>
\ No newline at end of file
index a3fdc9e3ecc52af318c25c330dd8f129d767bd1f..ec61cf4e0228bf27e8bcd354b2853fef48f9b916 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_mssql extends ADODB_DataDict {
-       var $databaseType = 'mssql';
-       
-       var $dropIndex = 'DROP INDEX %2$s.%1$s';
-       
-       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 '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':
-               case 'X': return 'TEXT';
-               
-               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 '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 $v";
-               }
-               $s .= implode(',',$f);
-               $sql[] = $s;
-               return $sql;
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {       
-               $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;
-       }
-}
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_mssql extends ADODB_DataDict {\r
+       var $databaseType = 'mssql';\r
+       \r
+       var $dropIndex = 'DROP INDEX %2$s.%1$s';\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               $len = -1; // mysql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+\r
+               case 'INT': \r
+               case 'INTEGER': return  'I';\r
+               case 'BIT':\r
+               case 'TINYINT': return  'I1';\r
+               case 'SMALLINT': return 'I2';\r
+               case 'BIGINT':  return  'I8';\r
+               \r
+               case 'REAL':\r
+               case 'FLOAT': return 'F';\r
+               default: return parent::MetaType($t,$len,$fieldobj);\r
+               }\r
+       }\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch(strtoupper($meta)) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'TEXT';\r
+               \r
+               case 'C2': return 'NVARCHAR';\r
+               case 'X2': return 'NTEXT';\r
+               \r
+               case 'B': return 'IMAGE';\r
+                       \r
+               case 'D': return 'DATETIME';\r
+               case 'T': return 'DATETIME';\r
+               case 'L': return 'BIT';\r
+               \r
+               case 'I': return 'INT'; \r
+               case 'I1': return 'TINYINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INT';\r
+               case 'I8': return 'BIGINT';\r
+               \r
+               case 'F': return 'REAL';\r
+               case 'N': return 'NUMERIC';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       \r
+       function AddColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $f = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $s = "ALTER TABLE $tabname $this->addCol";\r
+               foreach($lines as $v) {\r
+                       $f[] = "\n $v";\r
+               }\r
+               $s .= implode(',',$f);\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       /*\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $sql = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               foreach($lines as $v) {\r
+                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";\r
+               }\r
+\r
+               return $sql;\r
+       }\r
+       */\r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               if (!is_array($flds))\r
+                       $flds = explode(',',$flds);\r
+               $f = array();\r
+               $s = 'ALTER TABLE ' . $tabname;\r
+               foreach($flds as $v) {\r
+                       $f[] = "\n$this->dropCol $v";\r
+               }\r
+               $s .= implode(',',$f);\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {       \r
+               $suffix = '';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fautoinc) $suffix .= ' IDENTITY(1,1)';\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               else if ($suffix == '') $suffix .= ' NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       /*\r
+CREATE TABLE \r
+    [ database_name.[ owner ] . | owner. ] table_name \r
+    ( { < column_definition > \r
+        | column_name AS computed_column_expression \r
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }\r
+\r
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] \r
+    ) \r
+\r
+[ ON { filegroup | DEFAULT } ] \r
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] \r
+\r
+< column_definition > ::= { column_name data_type } \r
+    [ COLLATE < collation_name > ] \r
+    [ [ DEFAULT constant_expression ] \r
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]\r
+    ] \r
+    [ ROWGUIDCOL] \r
+    [ < column_constraint > ] [ ...n ] \r
+\r
+< column_constraint > ::= [ CONSTRAINT constraint_name ] \r
+    { [ NULL | NOT NULL ] \r
+        | [ { PRIMARY KEY | UNIQUE } \r
+            [ CLUSTERED | NONCLUSTERED ] \r
+            [ WITH FILLFACTOR = fillfactor ] \r
+            [ON {filegroup | DEFAULT} ] ] \r
+        ] \r
+        | [ [ FOREIGN KEY ] \r
+            REFERENCES ref_table [ ( ref_column ) ] \r
+            [ ON DELETE { CASCADE | NO ACTION } ] \r
+            [ ON UPDATE { CASCADE | NO ACTION } ] \r
+            [ NOT FOR REPLICATION ] \r
+        ] \r
+        | CHECK [ NOT FOR REPLICATION ] \r
+        ( logical_expression ) \r
+    } \r
+\r
+< table_constraint > ::= [ CONSTRAINT constraint_name ] \r
+    { [ { PRIMARY KEY | UNIQUE } \r
+        [ CLUSTERED | NONCLUSTERED ] \r
+        { ( column [ ASC | DESC ] [ ,...n ] ) } \r
+        [ WITH FILLFACTOR = fillfactor ] \r
+        [ ON { filegroup | DEFAULT } ] \r
+    ] \r
+    | FOREIGN KEY \r
+        [ ( column [ ,...n ] ) ] \r
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] \r
+        [ ON DELETE { CASCADE | NO ACTION } ] \r
+        [ ON UPDATE { CASCADE | NO ACTION } ] \r
+        [ NOT FOR REPLICATION ] \r
+    | CHECK [ NOT FOR REPLICATION ] \r
+        ( search_conditions ) \r
+    } \r
+\r
+\r
+       */\r
+       \r
+       /*\r
+       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name \r
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) \r
+               [ WITH < index_option > [ ,...n] ] \r
+               [ ON filegroup ]\r
+               < index_option > :: = \r
+                   { PAD_INDEX | \r
+                       FILLFACTOR = fillfactor | \r
+                       IGNORE_DUP_KEY | \r
+                       DROP_EXISTING | \r
+                   STATISTICS_NORECOMPUTE | \r
+                   SORT_IN_TEMPDB  \r
+               }\r
+*/\r
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
+               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';\r
+               \r
+               if ( is_array($flds) )\r
+                       $flds = implode(', ',$flds);\r
+               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+               \r
+\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       \r
+       function _GetSize($ftype, $ty, $fsize, $fprec)\r
+       {\r
+               switch ($ftype) {\r
+               case 'INT':\r
+               case 'SMALLINT':\r
+               case 'TINYINT':\r
+               case 'BIGINT':\r
+                       return $ftype;\r
+               }\r
+               if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {\r
+                       $ftype .= "(".$fsize;\r
+                       if (strlen($fprec)) $ftype .= ",".$fprec;\r
+                       $ftype .= ')';\r
+               }\r
+               return $ftype;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 8990fcf883b5ad1ed26b5555f44071fd9788ddeb..105fdd73cc9540ad8b3539de3c2d3e907c84393d 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_mysql extends ADODB_DataDict {
-       var $databaseType = 'mysql';
-       var $alterCol = ' MODIFY COLUMN';
-       var $alterTableAddIndex = true;
-       var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later
-       
-       var $dropIndex = 'DROP INDEX %s ON %s';
-       
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               
-               $len = -1; // mysql max_length is not accurate
-               switch (strtoupper($t)) {
-               case 'STRING': 
-               case 'CHAR':
-               case 'VARCHAR': 
-               case 'TINYBLOB': 
-               case 'TINYTEXT': 
-               case 'ENUM': 
-               case 'SET':
-                       if ($len <= $this->blobSize) return 'C';
-                       
-               case 'TEXT':
-               case 'LONGTEXT': 
-               case 'MEDIUMTEXT':
-                       return 'X';
-                       
-               // php_mysql extension always returns 'blob' even if 'text'
-               // so we have to check whether binary...
-               case 'IMAGE':
-               case 'LONGBLOB': 
-               case 'BLOB':
-               case 'MEDIUMBLOB':
-                       return !empty($fieldobj->binary) ? 'B' : 'X';
-                       
-               case 'YEAR':
-               case 'DATE': return 'D';
-               
-               case 'TIME':
-               case 'DATETIME':
-               case 'TIMESTAMP': return 'T';
-               
-               case 'FLOAT':
-               case 'DOUBLE':
-                       return 'F';
-                       
-               case 'INT': 
-               case 'INTEGER': return (!empty($fieldobj->primary_key)) ? 'R' : 'I';
-               case 'TINYINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I1';
-               case 'SMALLINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I2';
-               case 'MEDIUMINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I4';
-               case 'BIGINT':  return (!empty($fieldobj->primary_key)) ? 'R' : 'I8';
-               default: return 'N';
-               }
-       }
-
-       function ActualType($meta)
-       {
-               switch(strtoupper($meta)) {
-               case 'C': return 'VARCHAR';
-               case 'XL':
-               case 'X': return 'LONGTEXT';
-               
-               case 'C2': return 'VARCHAR';
-               case 'X2': return 'LONGTEXT';
-               
-               case 'B': return 'LONGBLOB';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'DATETIME';
-               case 'L': return 'TINYINT';
-               
-               case 'R':
-               case 'I': return 'INTEGER';
-               case 'I1': return 'TINYINT';
-               case 'I2': return 'SMALLINT';
-               case 'I4': return 'MEDIUMINT';
-               case 'I8': return 'BIGINT';
-               
-               case 'F': return 'DOUBLE';
-               case 'N': return 'NUMERIC';
-               default:
-                       return $meta;
-               }
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
-       {       
-               $suffix = '';
-               if ($funsigned) $suffix .= ' UNSIGNED';
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               return $suffix;
-       }
-       
-       /*
-       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
-               [table_options] [select_statement]
-               create_definition:
-               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
-               [PRIMARY KEY] [reference_definition]
-               or PRIMARY KEY (index_col_name,...)
-               or KEY [index_name] (index_col_name,...)
-               or INDEX [index_name] (index_col_name,...)
-               or UNIQUE [INDEX] [index_name] (index_col_name,...)
-               or FULLTEXT [INDEX] [index_name] (index_col_name,...)
-               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
-               [reference_definition]
-               or CHECK (expr)
-       */
-       
-       /*
-       CREATE [UNIQUE|FULLTEXT] INDEX index_name
-               ON tbl_name (col_name[(length)],... )
-       */
-       
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
-       {
-               $sql = array();
-               
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
-                       if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";
-                       else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);
-
-                       if ( isset($idxoptions['DROP']) )
-                               return $sql;
-               }
-               
-               if ( empty ($flds) ) {
-                       return $sql;
-               }
-               
-               if (isset($idxoptions['FULLTEXT'])) {
-                       $unique = ' FULLTEXT';
-               } elseif (isset($idxoptions['UNIQUE'])) {
-                       $unique = ' UNIQUE';
-               } else {
-                       $unique = '';
-               }
-               
-               if ( is_array($flds) ) $flds = implode(', ',$flds);
-               
-               if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";
-               else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;
-               
-               $s .= ' (' . $flds . ')';
-               
-               if ( isset($idxoptions[$this->upperName]) )
-                       $s .= $idxoptions[$this->upperName];
-               
-               $sql[] = $s;
-               
-               return $sql;
-       }
-}
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_mysql extends ADODB_DataDict {\r
+       var $databaseType = 'mysql';\r
+       var $alterCol = ' MODIFY COLUMN';\r
+       var $alterTableAddIndex = true;\r
+       var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later\r
+       \r
+       var $dropIndex = 'DROP INDEX %s ON %s';\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               $len = -1; // mysql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+               case 'STRING': \r
+               case 'CHAR':\r
+               case 'VARCHAR': \r
+               case 'TINYBLOB': \r
+               case 'TINYTEXT': \r
+               case 'ENUM': \r
+               case 'SET':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+                       \r
+               case 'TEXT':\r
+               case 'LONGTEXT': \r
+               case 'MEDIUMTEXT':\r
+                       return 'X';\r
+                       \r
+               // php_mysql extension always returns 'blob' even if 'text'\r
+               // so we have to check whether binary...\r
+               case 'IMAGE':\r
+               case 'LONGBLOB': \r
+               case 'BLOB':\r
+               case 'MEDIUMBLOB':\r
+                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
+                       \r
+               case 'YEAR':\r
+               case 'DATE': return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'DATETIME':\r
+               case 'TIMESTAMP': return 'T';\r
+               \r
+               case 'FLOAT':\r
+               case 'DOUBLE':\r
+                       return 'F';\r
+                       \r
+               case 'INT': \r
+               case 'INTEGER': return (!empty($fieldobj->primary_key)) ? 'R' : 'I';\r
+               case 'TINYINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I1';\r
+               case 'SMALLINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I2';\r
+               case 'MEDIUMINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I4';\r
+               case 'BIGINT':  return (!empty($fieldobj->primary_key)) ? 'R' : 'I8';\r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+       function ActualType($meta)\r
+       {\r
+               switch(strtoupper($meta)) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'LONGTEXT';\r
+               \r
+               case 'C2': return 'VARCHAR';\r
+               case 'X2': return 'LONGTEXT';\r
+               \r
+               case 'B': return 'LONGBLOB';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'DATETIME';\r
+               case 'L': return 'TINYINT';\r
+               \r
+               case 'R':\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'TINYINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'MEDIUMINT';\r
+               case 'I8': return 'BIGINT';\r
+               \r
+               case 'F': return 'DOUBLE';\r
+               case 'N': return 'NUMERIC';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)\r
+       {       \r
+               $suffix = '';\r
+               if ($funsigned) $suffix .= ' UNSIGNED';\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fautoinc) $suffix .= ' AUTO_INCREMENT';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       /*\r
+       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]\r
+               [table_options] [select_statement]\r
+               create_definition:\r
+               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]\r
+               [PRIMARY KEY] [reference_definition]\r
+               or PRIMARY KEY (index_col_name,...)\r
+               or KEY [index_name] (index_col_name,...)\r
+               or INDEX [index_name] (index_col_name,...)\r
+               or UNIQUE [INDEX] [index_name] (index_col_name,...)\r
+               or FULLTEXT [INDEX] [index_name] (index_col_name,...)\r
+               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)\r
+               [reference_definition]\r
+               or CHECK (expr)\r
+       */\r
+       \r
+       /*\r
+       CREATE [UNIQUE|FULLTEXT] INDEX index_name\r
+               ON tbl_name (col_name[(length)],... )\r
+       */\r
+       \r
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";\r
+                       else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);\r
+\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               if (isset($idxoptions['FULLTEXT'])) {\r
+                       $unique = ' FULLTEXT';\r
+               } elseif (isset($idxoptions['UNIQUE'])) {\r
+                       $unique = ' UNIQUE';\r
+               } else {\r
+                       $unique = '';\r
+               }\r
+               \r
+               if ( is_array($flds) ) $flds = implode(', ',$flds);\r
+               \r
+               if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";\r
+               else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;\r
+               \r
+               $s .= ' (' . $flds . ')';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+               \r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index cd038f7931d2e9ce0544537c8d531c4cc176b4d4..3eda52ac0edfc01d5d05bb865934f21a6f8d0f5d 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_oci8 extends ADODB_DataDict {
-       
-       var $databaseType = 'oci8';
-       var $seqField = false;
-       var $seqPrefix = 'SEQ_';
-       var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
-       
-       function MetaType($t,$len=-1)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-               case 'VARCHAR':
-               case 'VARCHAR2':
-               case 'CHAR':
-               case 'VARBINARY':
-               case 'BINARY':
-                       if (isset($this) && $len <= $this->blobSize) return 'C';
-                       return 'X';
-               
-               case 'NCHAR':
-               case 'NVARCHAR2':
-               case 'NVARCHAR':
-                       if (isset($this) && $len <= $this->blobSize) return 'C2';
-                       return 'X2';
-                       
-               case 'NCLOB':
-               case 'CLOB':
-                       return 'XL';
-               
-               case 'LONG RAW':
-               case 'LONG VARBINARY':
-               case 'BLOB':
-                       return 'B';
-               
-               case 'DATE': 
-                       return 'T';
-               
-               case 'INT': 
-               case 'SMALLINT':
-               case 'INTEGER': 
-                       return 'I';
-                       
-               default:
-                       return 'N';
-               }
-       }
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'X': return 'VARCHAR(4000)';
-               case 'XL': return 'CLOB';
-               
-               case 'C2': return 'NVARCHAR';
-               case 'X2': return 'NVARCHAR(2000)';
-               
-               case 'B': return 'BLOB';
-                       
-               case 'D': 
-               case 'T': return 'DATE';
-               case 'L': return 'DECIMAL(1)';
-               case 'I1': return 'DECIMAL(3)';
-               case 'I2': return 'DECIMAL(5)';
-               case 'I':
-               case 'I4': return 'DECIMAL(10)';
-               
-               case 'I8': return 'DECIMAL(20)';
-               case 'F': return 'DECIMAL';
-               case 'N': return 'DECIMAL';
-               default:
-                       return $meta;
-               }       
-       }
-       
-       function CreateDatabase($dbname, $options=false)
-       {
-               $options = $this->_Options($options);
-               $password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';
-               $tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';
-               $sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;
-               $sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";
-               
-               return $sql;
-       }
-       
-       function AddColumnSQL($tabname, $flds)
-       {
-               $f = array();
-               list($lines,$pkey) = $this->_GenFields($flds);
-               $s = "ALTER TABLE $tabname ADD (";
-               foreach($lines as $v) {
-                       $f[] = "\n $v";
-               }
-               
-               $s .= implode(',',$f).')';
-               $sql[] = $s;
-               return $sql;
-       }
-       
-       function AlterColumnSQL($tabname, $flds)
-       {
-               $f = array();
-               list($lines,$pkey) = $this->_GenFields($flds);
-               $s = "ALTER TABLE $tabname MODIFY(";
-               foreach($lines as $v) {
-                       $f[] = "\n $v";
-               }
-               $s .= implode(',',$f).')';
-               $sql[] = $s;
-               return $sql;
-       }
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for Oracle");
-               return array();
-       }
-       
-       function _DropAutoIncrement($t)
-       {
-               if (strpos($t,'.') !== false) {
-                       $tarr = explode('.',$t);
-                       return "drop sequence ".$tarr[0].".seq_".$tarr[1];
-               }
-               return "drop sequence seq_".$t;
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
-       {
-               $suffix = '';
-               
-               if ($fdefault == "''" && $fnotnull) {// this is null in oracle
-                       $fnotnull = false;
-                       if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");
-               }
-               
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               
-               if ($fautoinc) $this->seqField = $fname;
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               
-               return $suffix;
-       }
-       
-/*
-CREATE or replace TRIGGER jaddress_insert
-before insert on jaddress
-for each row
-begin
-select seqaddress.nextval into :new.A_ID from dual;
-end;
-*/
-       function _Triggers($tabname,$tableoptions)
-       {
-               if (!$this->seqField) return array();
-               
-               if ($this->schema) {
-                       $t = strpos($tabname,'.');
-                       if ($t !== false) $tab = substr($tabname,$t+1);
-                       else $tab = $tabname;
-                       $seqname = $this->schema.'.'.$this->seqPrefix.$tab;
-                       $trigname = $this->schema.'.TRIG_'.$this->seqPrefix.$tab;
-               } else {
-                       $seqname = $this->seqPrefix.$tabname;
-                       $trigname = "TRIG_$seqname";
-               }
-               if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
-               $sql[] = "CREATE SEQUENCE $seqname";
-               $sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";
-               
-               $this->seqField = false;
-               return $sql;
-       }
-       
-       /*
-       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
-               [table_options] [select_statement]
-               create_definition:
-               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
-               [PRIMARY KEY] [reference_definition]
-               or PRIMARY KEY (index_col_name,...)
-               or KEY [index_name] (index_col_name,...)
-               or INDEX [index_name] (index_col_name,...)
-               or UNIQUE [INDEX] [index_name] (index_col_name,...)
-               or FULLTEXT [INDEX] [index_name] (index_col_name,...)
-               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
-               [reference_definition]
-               or CHECK (expr)
-       */
-       
-
-       
-       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;
-               }
-               
-               if (isset($idxoptions['BITMAP'])) {
-                       $unique = ' BITMAP'; 
-               } elseif (isset($idxoptions['UNIQUE'])) {
-                       $unique = ' UNIQUE';
-               } else {
-                       $unique = '';
-               }
-               
-               if ( is_array($flds) )
-                       $flds = implode(', ',$flds);
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
-               
-               if ( isset($idxoptions[$this->upperName]) )
-                       $s .= $idxoptions[$this->upperName];
-               
-               if (isset($idxoptions['oci8']))
-                       $s .= $idxoptions['oci8'];
-               
-
-               $sql[] = $s;
-               
-               return $sql;
-       }
-       
-       function GetCommentSQL($table,$col)
-       {
-               $table = $this->connection->qstr($table);
-               $col = $this->connection->qstr($col);   
-               return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";
-       }
-       
-       function SetCommentSQL($table,$col,$cmt)
-       {
-               $cmt = $this->connection->qstr($cmt);
-               return  "COMMENT ON COLUMN $table.$col IS $cmt";
-       }
-}
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_oci8 extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'oci8';\r
+       var $seqField = false;\r
+       var $seqPrefix = 'SEQ_';\r
+       var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";\r
+       var $trigPrefix = 'TRIG_';\r
+       \r
+       function MetaType($t,$len=-1)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'VARCHAR2':\r
+               case 'CHAR':\r
+               case 'VARBINARY':\r
+               case 'BINARY':\r
+                       if (isset($this) && $len <= $this->blobSize) return 'C';\r
+                       return 'X';\r
+               \r
+               case 'NCHAR':\r
+               case 'NVARCHAR2':\r
+               case 'NVARCHAR':\r
+                       if (isset($this) && $len <= $this->blobSize) return 'C2';\r
+                       return 'X2';\r
+                       \r
+               case 'NCLOB':\r
+               case 'CLOB':\r
+                       return 'XL';\r
+               \r
+               case 'LONG RAW':\r
+               case 'LONG VARBINARY':\r
+               case 'BLOB':\r
+                       return 'B';\r
+               \r
+               case 'DATE': \r
+                       return 'T';\r
+               \r
+               case 'INT': \r
+               case 'SMALLINT':\r
+               case 'INTEGER': \r
+                       return 'I';\r
+                       \r
+               default:\r
+                       return 'N';\r
+               }\r
+       }\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'X': return 'VARCHAR(4000)';\r
+               case 'XL': return 'CLOB';\r
+               \r
+               case 'C2': return 'NVARCHAR';\r
+               case 'X2': return 'NVARCHAR(2000)';\r
+               \r
+               case 'B': return 'BLOB';\r
+                       \r
+               case 'D': \r
+               case 'T': return 'DATE';\r
+               case 'L': return 'DECIMAL(1)';\r
+               case 'I1': return 'DECIMAL(3)';\r
+               case 'I2': return 'DECIMAL(5)';\r
+               case 'I':\r
+               case 'I4': return 'DECIMAL(10)';\r
+               \r
+               case 'I8': return 'DECIMAL(20)';\r
+               case 'F': return 'DECIMAL';\r
+               case 'N': return 'DECIMAL';\r
+               default:\r
+                       return $meta;\r
+               }       \r
+       }\r
+       \r
+       function CreateDatabase($dbname, $options=false)\r
+       {\r
+               $options = $this->_Options($options);\r
+               $password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';\r
+               $tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';\r
+               $sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;\r
+               $sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       function AddColumnSQL($tabname, $flds)\r
+       {\r
+               $f = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $s = "ALTER TABLE $tabname ADD (";\r
+               foreach($lines as $v) {\r
+                       $f[] = "\n $v";\r
+               }\r
+               \r
+               $s .= implode(',',$f).')';\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               $f = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $s = "ALTER TABLE $tabname MODIFY(";\r
+               foreach($lines as $v) {\r
+                       $f[] = "\n $v";\r
+               }\r
+               $s .= implode(',',$f).')';\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if (!is_array($flds)) $flds = explode(',',$flds);\r
+               $sql = array();\r
+               $s = "ALTER TABLE $tabname DROP(";\r
+               $s .= implode(',',$flds).') CASCADE COSTRAINTS';\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       function _DropAutoIncrement($t)\r
+       {\r
+               if (strpos($t,'.') !== false) {\r
+                       $tarr = explode('.',$t);\r
+                       return "drop sequence ".$tarr[0].".seq_".$tarr[1];\r
+               }\r
+               return "drop sequence seq_".$t;\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)\r
+       {\r
+               $suffix = '';\r
+               \r
+               if ($fdefault == "''" && $fnotnull) {// this is null in oracle\r
+                       $fnotnull = false;\r
+                       if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");\r
+               }\r
+               \r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               \r
+               if ($fautoinc) $this->seqField = $fname;\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               \r
+               return $suffix;\r
+       }\r
+       \r
+/*\r
+CREATE or replace TRIGGER jaddress_insert\r
+before insert on jaddress\r
+for each row\r
+begin\r
+select seqaddress.nextval into :new.A_ID from dual;\r
+end;\r
+*/\r
+       function _Triggers($tabname,$tableoptions)\r
+       {\r
+               if (!$this->seqField) return array();\r
+               \r
+               if ($this->schema) {\r
+                       $t = strpos($tabname,'.');\r
+                       if ($t !== false) $tab = substr($tabname,$t+1);\r
+                       else $tab = $tabname;\r
+                       $seqname = $this->schema.'.'.$this->seqPrefix.$tab;\r
+                       $trigname = $this->schema.'.'.$this->trigPrefix.$this->seqPrefix.$tab;\r
+               } else {\r
+                       $seqname = $this->seqPrefix.$tabname;\r
+                       $trigname = $this->trigPrefix.$seqname;\r
+               }\r
+               if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";\r
+               $seqCache = '';\r
+               if (isset($tableoptions['SEQUENCE_CACHE'])){$seqCache = $tableoptions['SEQUENCE_CACHE'];}\r
+               $seqIncr = '';\r
+               if (isset($tableoptions['SEQUENCE_INCREMENT'])){$seqIncr = ' INCREMENT BY '.$tableoptions['SEQUENCE_INCREMENT'];}\r
+               $seqStart = '';\r
+               if (isset($tableoptions['SEQUENCE_START'])){$seqIncr = ' START WITH '.$tableoptions['SEQUENCE_START'];}\r
+               $sql[] = "CREATE SEQUENCE $seqname $seqStart $seqIncr $seqCache";\r
+               $sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW WHEN (NEW.$this->seqField IS NULL OR NEW.$this->seqField = 0) BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";\r
+               \r
+               $this->seqField = false;\r
+               return $sql;\r
+       }\r
+       \r
+       /*\r
+       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]\r
+               [table_options] [select_statement]\r
+               create_definition:\r
+               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]\r
+               [PRIMARY KEY] [reference_definition]\r
+               or PRIMARY KEY (index_col_name,...)\r
+               or KEY [index_name] (index_col_name,...)\r
+               or INDEX [index_name] (index_col_name,...)\r
+               or UNIQUE [INDEX] [index_name] (index_col_name,...)\r
+               or FULLTEXT [INDEX] [index_name] (index_col_name,...)\r
+               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)\r
+               [reference_definition]\r
+               or CHECK (expr)\r
+       */\r
+       \r
+\r
+       \r
+       function _IndexSQL($idxname, $tabname, $flds,$idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               if (isset($idxoptions['BITMAP'])) {\r
+                       $unique = ' BITMAP'; \r
+               } elseif (isset($idxoptions['UNIQUE'])) {\r
+                       $unique = ' UNIQUE';\r
+               } else {\r
+                       $unique = '';\r
+               }\r
+               \r
+               if ( is_array($flds) )\r
+                       $flds = implode(', ',$flds);\r
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+               \r
+               if (isset($idxoptions['oci8']))\r
+                       $s .= $idxoptions['oci8'];\r
+               \r
+\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+       \r
+       function GetCommentSQL($table,$col)\r
+       {\r
+               $table = $this->connection->qstr($table);\r
+               $col = $this->connection->qstr($col);   \r
+               return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";\r
+       }\r
+       \r
+       function SetCommentSQL($table,$col,$cmt)\r
+       {\r
+               $cmt = $this->connection->qstr($cmt);\r
+               return  "COMMENT ON COLUMN $table.$col IS $cmt";\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 9005ac55948413ce91cebaa9f2cff0dbfb47f2b0..2243a6b573af9149f57187b662fb4e4806ebb927 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_postgres extends ADODB_DataDict {
-       
-       var $databaseType = 'postgres';
-       var $seqField = false;
-       var $seqPrefix = 'SEQ_';
-       var $addCol = ' ADD COLUMN';
-       var $quote = '"';
-       
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-                       case 'INTERVAL':
-                       case 'CHAR':
-                       case 'CHARACTER':
-                       case 'VARCHAR':
-                       case 'NAME':
-                       case 'BPCHAR':
-                               if ($len <= $this->blobSize) return 'C';
-                       
-                       case 'TEXT':
-                               return 'X';
-       
-                       case 'IMAGE': // user defined type
-                       case 'BLOB': // user defined type
-                       case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'
-                       case 'VARBIT':
-                       case 'BYTEA':
-                               return 'B';
-                       
-                       case 'BOOL':
-                       case 'BOOLEAN':
-                               return 'L';
-                       
-                       case 'DATE':
-                               return 'D';
-                       
-                       case 'TIME':
-                       case 'DATETIME':
-                       case 'TIMESTAMP':
-                       case 'TIMESTAMPTZ':
-                               return 'T';
-                       
-                       case 'INTEGER': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I' : 'R';
-                       case 'SMALLINT': 
-                       case 'INT2': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I2' : 'R';
-                       case 'INT4': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I4' : 'R';
-                       case 'BIGINT': 
-                       case 'INT8': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I8' : 'R';
-                               
-                       case 'OID':
-                       case 'SERIAL':
-                               return 'R';
-                       
-                       case 'FLOAT4':
-                       case 'FLOAT8':
-                       case 'DOUBLE PRECISION':
-                       case 'REAL':
-                               return 'F';
-                               
-                        default:
-                               return 'N';
-               }
-       }
-       
-       function ActualType($meta)
-       {
-               switch($meta) {
-               case 'C': return 'VARCHAR';
-               case 'XL':
-               case 'X': return 'TEXT';
-               
-               case 'C2': return 'VARCHAR';
-               case 'X2': return 'TEXT';
-               
-               case 'B': return 'BYTEA';
-                       
-               case 'D': return 'DATE';
-               case 'T': return 'TIMESTAMP';
-               
-               case 'L': return 'SMALLINT';
-               case 'I': return 'INTEGER';
-               case 'I1': return 'SMALLINT';
-               case 'I2': return 'INT2';
-               case 'I4': return 'INT4';
-               case 'I8': return 'INT8';
-               
-               case 'F': return 'FLOAT8';
-               case 'N': return 'NUMERIC';
-               default:
-                       return $meta;
-               }
-       }
-       
-       /* The following does not work in Pg 6.0 - does anyone want to contribute code? 
-       
-       //"ALTER TABLE table ALTER COLUMN column SET DEFAULT mydef" and
-       //"ALTER TABLE table ALTER COLUMN column DROP DEFAULT mydef"
-       //"ALTER TABLE table ALTER COLUMN column SET NOT NULL" and
-       //"ALTER TABLE table ALTER COLUMN column DROP NOT NULL"*/
-       function AlterColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");
-               return array();
-       }
-       
-       
-       function DropColumnSQL($tabname, $flds)
-       {
-               if ($this->debug) ADOConnection::outp("DropColumnSQL only works with PostgreSQL 7.3+");
-               return ADODB_DataDict::DropColumnSQL($tabname, $flds)."/* only works for PostgreSQL 7.3+ */";
-       }
-
-       // return string must begin with space
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {
-               if ($fautoinc) {
-                       $ftype = 'SERIAL';
-                       return '';
-               }
-               $suffix = '';
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fnotnull) $suffix .= ' NOT NULL';
-               if ($fconstraint) $suffix .= ' '.$fconstraint;
-               return $suffix;
-       }
-       
-       function _DropAutoIncrement($t)
-       {
-               return "drop sequence ".$t."_m_id_seq";
-       }
-       
-       /*
-       CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
-       { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
-       | table_constraint } [, ... ]
-       )
-       [ INHERITS ( parent_table [, ... ] ) ]
-       [ WITH OIDS | WITHOUT OIDS ]
-       where column_constraint is:
-       [ CONSTRAINT constraint_name ]
-       { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
-       CHECK (expression) |
-       REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
-       [ ON DELETE action ] [ ON UPDATE action ] }
-       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
-       and table_constraint is:
-       [ CONSTRAINT constraint_name ]
-       { UNIQUE ( column_name [, ... ] ) |
-       PRIMARY KEY ( column_name [, ... ] ) |
-       CHECK ( expression ) |
-       FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
-       [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
-       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
-       */
-       
-       
-       /*
-       CREATE [ UNIQUE ] INDEX index_name ON table
-[ USING acc_method ] ( column [ ops_name ] [, ...] )
-[ WHERE predicate ]
-CREATE [ UNIQUE ] INDEX index_name ON table
-[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
-[ WHERE predicate ]
-       */
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
-       {
-               $sql = array();
-               
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
-                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
-                       if ( isset($idxoptions['DROP']) )
-                               return $sql;
-               }
-               
-               if ( empty ($flds) ) {
-                       return $sql;
-               }
-               
-               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
-               
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
-               
-               if (isset($idxoptions['HASH']))
-                       $s .= 'USING HASH ';
-               
-               if ( isset($idxoptions[$this->upperName]) )
-                       $s .= $idxoptions[$this->upperName];
-               
-               if ( is_array($flds) )
-                       $flds = implode(', ',$flds);
-               $s .= '(' . $flds . ')';
-               $sql[] = $s;
-               
-               return $sql;
-       }
-}
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_postgres extends ADODB_DataDict {\r
+       \r
+       var $databaseType = 'postgres';\r
+       var $seqField = false;\r
+       var $seqPrefix = 'SEQ_';\r
+       var $addCol = ' ADD COLUMN';\r
+       var $quote = '"';\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+                       case 'INTERVAL':\r
+                       case 'CHAR':\r
+                       case 'CHARACTER':\r
+                       case 'VARCHAR':\r
+                       case 'NAME':\r
+                       case 'BPCHAR':\r
+                               if ($len <= $this->blobSize) return 'C';\r
+                       \r
+                       case 'TEXT':\r
+                               return 'X';\r
+       \r
+                       case 'IMAGE': // user defined type\r
+                       case 'BLOB': // user defined type\r
+                       case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'\r
+                       case 'VARBIT':\r
+                       case 'BYTEA':\r
+                               return 'B';\r
+                       \r
+                       case 'BOOL':\r
+                       case 'BOOLEAN':\r
+                               return 'L';\r
+                       \r
+                       case 'DATE':\r
+                               return 'D';\r
+                       \r
+                       case 'TIME':\r
+                       case 'DATETIME':\r
+                       case 'TIMESTAMP':\r
+                       case 'TIMESTAMPTZ':\r
+                               return 'T';\r
+                       \r
+                       case 'INTEGER': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I' : 'R';\r
+                       case 'SMALLINT': \r
+                       case 'INT2': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I2' : 'R';\r
+                       case 'INT4': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I4' : 'R';\r
+                       case 'BIGINT': \r
+                       case 'INT8': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I8' : 'R';\r
+                               \r
+                       case 'OID':\r
+                       case 'SERIAL':\r
+                               return 'R';\r
+                       \r
+                       case 'FLOAT4':\r
+                       case 'FLOAT8':\r
+                       case 'DOUBLE PRECISION':\r
+                       case 'REAL':\r
+                               return 'F';\r
+                               \r
+                        default:\r
+                               return 'N';\r
+               }\r
+       }\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch($meta) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'TEXT';\r
+               \r
+               case 'C2': return 'VARCHAR';\r
+               case 'X2': return 'TEXT';\r
+               \r
+               case 'B': return 'BYTEA';\r
+                       \r
+               case 'D': return 'DATE';\r
+               case 'T': return 'TIMESTAMP';\r
+               \r
+               case 'L': return 'SMALLINT';\r
+               case 'I': return 'INTEGER';\r
+               case 'I1': return 'SMALLINT';\r
+               case 'I2': return 'INT2';\r
+               case 'I4': return 'INT4';\r
+               case 'I8': return 'INT8';\r
+               \r
+               case 'F': return 'FLOAT8';\r
+               case 'N': return 'NUMERIC';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       /* The following does not work in Pg 6.0 - does anyone want to contribute code? \r
+       \r
+       //"ALTER TABLE table ALTER COLUMN column SET DEFAULT mydef" and\r
+       //"ALTER TABLE table ALTER COLUMN column DROP DEFAULT mydef"\r
+       //"ALTER TABLE table ALTER COLUMN column SET NOT NULL" and\r
+       //"ALTER TABLE table ALTER COLUMN column DROP NOT NULL"*/\r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");\r
+               return array();\r
+       }\r
+       \r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               if ($this->debug) ADOConnection::outp("DropColumnSQL only works with PostgreSQL 7.3+");\r
+               return ADODB_DataDict::DropColumnSQL($tabname, $flds)."/* only works for PostgreSQL 7.3+ */";\r
+       }\r
+\r
+       // return string must begin with space\r
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {\r
+               if ($fautoinc) {\r
+                       $ftype = 'SERIAL';\r
+                       return '';\r
+               }\r
+               $suffix = '';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       function _DropAutoIncrement($t)\r
+       {\r
+               return "drop sequence ".$t."_m_id_seq";\r
+       }\r
+       \r
+       /*\r
+       CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (\r
+       { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]\r
+       | table_constraint } [, ... ]\r
+       )\r
+       [ INHERITS ( parent_table [, ... ] ) ]\r
+       [ WITH OIDS | WITHOUT OIDS ]\r
+       where column_constraint is:\r
+       [ CONSTRAINT constraint_name ]\r
+       { NOT NULL | NULL | UNIQUE | PRIMARY KEY |\r
+       CHECK (expression) |\r
+       REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]\r
+       [ ON DELETE action ] [ ON UPDATE action ] }\r
+       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\r
+       and table_constraint is:\r
+       [ CONSTRAINT constraint_name ]\r
+       { UNIQUE ( column_name [, ... ] ) |\r
+       PRIMARY KEY ( column_name [, ... ] ) |\r
+       CHECK ( expression ) |\r
+       FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]\r
+       [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }\r
+       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\r
+       */\r
+       \r
+       \r
+       /*\r
+       CREATE [ UNIQUE ] INDEX index_name ON table\r
+[ USING acc_method ] ( column [ ops_name ] [, ...] )\r
+[ WHERE predicate ]\r
+CREATE [ UNIQUE ] INDEX index_name ON table\r
+[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )\r
+[ WHERE predicate ]\r
+       */\r
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
+               \r
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';\r
+               \r
+               if (isset($idxoptions['HASH']))\r
+                       $s .= 'USING HASH ';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+               \r
+               if ( is_array($flds) )\r
+                       $flds = implode(', ',$flds);\r
+               $s .= '(' . $flds . ')';\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 50c7494dd73c90892948428d0b506ab3bedc0b23..7ab2d360840107c0143fea38935b75077099ada9 100644 (file)
-<?php
-
-/**
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/
-
-class ADODB2_sybase extends ADODB_DataDict {
-       var $databaseType = 'sybase';
-       
-       var $dropIndex = 'DROP INDEX %2$s.%1$s';
-       
-       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 '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':
-               case 'X': return 'TEXT';
-               
-               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 '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 $v";
-               }
-               $s .= implode(',',$f);
-               $sql[] = $s;
-               return $sql;
-       }
-       
-       // return string must begin with space
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
-       {       
-               $suffix = '';
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
-               if ($fautoinc) $suffix .= ' DEFAULT AUTOINCREMENT';
-               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;
-       }
-}
+<?php\r
+\r
+/**\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB2_sybase extends ADODB_DataDict {\r
+       var $databaseType = 'sybase';\r
+       \r
+       var $dropIndex = 'DROP INDEX %2$s.%1$s';\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               $len = -1; // mysql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+\r
+               case 'INT': \r
+               case 'INTEGER': return  'I';\r
+               case 'BIT':\r
+               case 'TINYINT': return  'I1';\r
+               case 'SMALLINT': return 'I2';\r
+               case 'BIGINT':  return  'I8';\r
+               \r
+               case 'REAL':\r
+               case 'FLOAT': return 'F';\r
+               default: return parent::MetaType($t,$len,$fieldobj);\r
+               }\r
+       }\r
+       \r
+       function ActualType($meta)\r
+       {\r
+               switch(strtoupper($meta)) {\r
+               case 'C': return 'VARCHAR';\r
+               case 'XL':\r
+               case 'X': return 'TEXT';\r
+               \r
+               case 'C2': return 'NVARCHAR';\r
+               case 'X2': return 'NTEXT';\r
+               \r
+               case 'B': return 'IMAGE';\r
+                       \r
+               case 'D': return 'DATETIME';\r
+               case 'T': return 'DATETIME';\r
+               case 'L': return 'BIT';\r
+               \r
+               case 'I': return 'INT'; \r
+               case 'I1': return 'TINYINT';\r
+               case 'I2': return 'SMALLINT';\r
+               case 'I4': return 'INT';\r
+               case 'I8': return 'BIGINT';\r
+               \r
+               case 'F': return 'REAL';\r
+               case 'N': return 'NUMERIC';\r
+               default:\r
+                       return $meta;\r
+               }\r
+       }\r
+       \r
+       \r
+       function AddColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $f = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               $s = "ALTER TABLE $tabname $this->addCol";\r
+               foreach($lines as $v) {\r
+                       $f[] = "\n $v";\r
+               }\r
+               $s .= implode(',',$f);\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       function AlterColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               $sql = array();\r
+               list($lines,$pkey) = $this->_GenFields($flds);\r
+               foreach($lines as $v) {\r
+                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";\r
+               }\r
+\r
+               return $sql;\r
+       }\r
+       \r
+       function DropColumnSQL($tabname, $flds)\r
+       {\r
+               $tabname = $this->TableName ($tabname);\r
+               if (!is_array($flds)) $flds = explode(',',$flds);\r
+               $f = array();\r
+               $s = "ALTER TABLE $tabname";\r
+               foreach($flds as $v) {\r
+                       $f[] = "\n$this->dropCol $v";\r
+               }\r
+               $s .= implode(',',$f);\r
+               $sql[] = $s;\r
+               return $sql;\r
+       }\r
+       \r
+       // return string must begin with space\r
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
+       {       \r
+               $suffix = '';\r
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
+               if ($fautoinc) $suffix .= ' DEFAULT AUTOINCREMENT';\r
+               if ($fnotnull) $suffix .= ' NOT NULL';\r
+               else if ($suffix == '') $suffix .= ' NULL';\r
+               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
+               return $suffix;\r
+       }\r
+       \r
+       /*\r
+CREATE TABLE \r
+    [ database_name.[ owner ] . | owner. ] table_name \r
+    ( { < column_definition > \r
+        | column_name AS computed_column_expression \r
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }\r
+\r
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] \r
+    ) \r
+\r
+[ ON { filegroup | DEFAULT } ] \r
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] \r
+\r
+< column_definition > ::= { column_name data_type } \r
+    [ COLLATE < collation_name > ] \r
+    [ [ DEFAULT constant_expression ] \r
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]\r
+    ] \r
+    [ ROWGUIDCOL] \r
+    [ < column_constraint > ] [ ...n ] \r
+\r
+< column_constraint > ::= [ CONSTRAINT constraint_name ] \r
+    { [ NULL | NOT NULL ] \r
+        | [ { PRIMARY KEY | UNIQUE } \r
+            [ CLUSTERED | NONCLUSTERED ] \r
+            [ WITH FILLFACTOR = fillfactor ] \r
+            [ON {filegroup | DEFAULT} ] ] \r
+        ] \r
+        | [ [ FOREIGN KEY ] \r
+            REFERENCES ref_table [ ( ref_column ) ] \r
+            [ ON DELETE { CASCADE | NO ACTION } ] \r
+            [ ON UPDATE { CASCADE | NO ACTION } ] \r
+            [ NOT FOR REPLICATION ] \r
+        ] \r
+        | CHECK [ NOT FOR REPLICATION ] \r
+        ( logical_expression ) \r
+    } \r
+\r
+< table_constraint > ::= [ CONSTRAINT constraint_name ] \r
+    { [ { PRIMARY KEY | UNIQUE } \r
+        [ CLUSTERED | NONCLUSTERED ] \r
+        { ( column [ ASC | DESC ] [ ,...n ] ) } \r
+        [ WITH FILLFACTOR = fillfactor ] \r
+        [ ON { filegroup | DEFAULT } ] \r
+    ] \r
+    | FOREIGN KEY \r
+        [ ( column [ ,...n ] ) ] \r
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] \r
+        [ ON DELETE { CASCADE | NO ACTION } ] \r
+        [ ON UPDATE { CASCADE | NO ACTION } ] \r
+        [ NOT FOR REPLICATION ] \r
+    | CHECK [ NOT FOR REPLICATION ] \r
+        ( search_conditions ) \r
+    } \r
+\r
+\r
+       */\r
+       \r
+       /*\r
+       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name \r
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) \r
+               [ WITH < index_option > [ ,...n] ] \r
+               [ ON filegroup ]\r
+               < index_option > :: = \r
+                   { PAD_INDEX | \r
+                       FILLFACTOR = fillfactor | \r
+                       IGNORE_DUP_KEY | \r
+                       DROP_EXISTING | \r
+                   STATISTICS_NORECOMPUTE | \r
+                   SORT_IN_TEMPDB  \r
+               }\r
+*/\r
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
+       {\r
+               $sql = array();\r
+               \r
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);\r
+                       if ( isset($idxoptions['DROP']) )\r
+                               return $sql;\r
+               }\r
+               \r
+               if ( empty ($flds) ) {\r
+                       return $sql;\r
+               }\r
+               \r
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
+               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';\r
+               \r
+               if ( is_array($flds) )\r
+                       $flds = implode(', ',$flds);\r
+               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
+               \r
+               if ( isset($idxoptions[$this->upperName]) )\r
+                       $s .= $idxoptions[$this->upperName];\r
+\r
+               $sql[] = $s;\r
+               \r
+               return $sql;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 9e418b7fdeeab2d71a5e4802c568b7dbdf072a0a..086a9e883276ee7894edc7ddb77d81af394b13cc 100644 (file)
@@ -1,79 +1,86 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.
-*/
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
- if (!defined('_ADODB_ACCESS')) {
-       define('_ADODB_ACCESS',1);
-
-class  ADODB_access extends ADODB_odbc {       
-       var $databaseType = 'access';
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
-       var $fmtDate = "#Y-m-d#";
-       var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma
-       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
-       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
-       var $sysTimeStamp = 'NOW';
-       var $hasTransactions = false;
-       
-       function ADODB_access()
-       {
-       global $ADODB_EXTENSION;
-       
-               $ADODB_EXTENSION = false;
-               $this->ADODB_odbc();
-       }
-       
-       function BeginTrans() { return false;}
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " IIF(IsNull($field), $ifNull, $field) "; // if Access
-       }
-/*
-       function &MetaTables()
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $savem = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $qid = odbc_tables($this->_connectionID);
-               $rs = new ADORecordSet_odbc($qid);
-               $ADODB_FETCH_MODE = $savem;
-               if (!$rs) return false;
-               
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
-               
-               $arr = &$rs->GetArray();
-               //print_pre($arr);
-               $arr2 = array();
-               for ($i=0; $i < sizeof($arr); $i++) {
-                       if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')
-                               $arr2[] = $arr[$i][2];
-               }
-               return $arr2;
-       }*/
-}
-
-class  ADORecordSet_access extends ADORecordSet_odbc { 
-       
-       var $databaseType = "access";           
-       
-       function ADORecordSet_access($id,$mode=false)
-       {
-               return $this->ADORecordSet_odbc($id,$mode);
-       }
-}// class
-} 
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.\r
+*/\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       if (!defined('ADODB_DIR')) die();\r
+       \r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+ if (!defined('_ADODB_ACCESS')) {\r
+       define('_ADODB_ACCESS',1);\r
+\r
+class  ADODB_access extends ADODB_odbc {       \r
+       var $databaseType = 'access';\r
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $fmtDate = "#Y-m-d#";\r
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma\r
+       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably\r
+       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";\r
+       var $sysTimeStamp = 'NOW';\r
+       var $hasTransactions = false;\r
+       \r
+       function ADODB_access()\r
+       {\r
+       global $ADODB_EXTENSION;\r
+       \r
+               $ADODB_EXTENSION = false;\r
+               $this->ADODB_odbc();\r
+       }\r
+       \r
+       function Time()\r
+       {\r
+               return time();\r
+       }\r
+       \r
+       function BeginTrans() { return false;}\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " IIF(IsNull($field), $ifNull, $field) "; // if Access\r
+       }\r
+/*\r
+       function &MetaTables()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $qid = odbc_tables($this->_connectionID);\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               $ADODB_FETCH_MODE = $savem;\r
+               if (!$rs) return false;\r
+               \r
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+               \r
+               $arr = &$rs->GetArray();\r
+               //print_pre($arr);\r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')\r
+                               $arr2[] = $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }*/\r
+}\r
+\r
\r
+class  ADORecordSet_access extends ADORecordSet_odbc { \r
+       \r
+       var $databaseType = "access";           \r
+       \r
+       function ADORecordSet_access($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_odbc($id,$mode);\r
+       }\r
+}// class\r
+} \r
 ?>
\ No newline at end of file
index 68ea5056abd7e59b9afe4c1237b2e723da941adb..07e28d4e394140474b60a4cb482578f195e0b59d 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-       Microsoft ADO data driver. Requires ADO. Works only on MS Windows.
-*/
-  define("_ADODB_ADO_LAYER", 1 );
-/*--------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------*/
-  
-class ADODB_ado extends ADOConnection {
-       var $databaseType = "ado";      
-       var $_bindInputArray = false;
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $dataProvider = "ado";      
-       var $hasAffectedRows = true;
-       var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary
-       var $_affectedRows = false;
-       var $_thisTransactions;
-       var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic
-       var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;
-       var $_lock_type = -1;
-       var $_execute_option = -1;
-       var $poorAffectedRows = true; 
-       var $charPage;
-               
-       function ADODB_ado() 
-       {       
-               $this->_affectedRows = new VARIANT;
-       }
-
-       function ServerInfo()
-       {
-               if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;
-               return array('description' => $desc, 'version' => '');
-       }
-       
-       function _affectedrows()
-       {
-                       return $this->_affectedRows->value;
-       }
-       
-       // you can also pass a connection string like this:
-       //
-       // $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
-       function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')
-       {
-               $u = 'UID';
-               $p = 'PWD';
-       
-               if (!empty($this->charPage))
-                       $dbc = new COM('ADODB.Connection',null,$this->charPage);
-               else
-                       $dbc = new COM('ADODB.Connection');
-                       
-               if (! $dbc) return false;
-
-               /* special support if provider is mssql or access */
-               if ($argProvider=='mssql') {
-                       $u = 'User Id';  //User parameter name for OLEDB
-                       $p = 'Password'; 
-                       $argProvider = "SQLOLEDB"; // SQL Server Provider
-                       
-                       // not yet
-                       //if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";
-                       
-                       //use trusted conection for SQL if username not specified
-                       if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
-               } else if ($argProvider=='access')
-                       $argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider
-               
-               if ($argProvider) $dbc->Provider = $argProvider;        
-               
-               if ($argUsername) $argHostname .= ";$u=$argUsername";
-               if ($argPassword)$argHostname .= ";$p=$argPassword";
-               
-               if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
-               // @ added below for php 4.0.1 and earlier
-               @$dbc->Open((string) $argHostname);
-               
-               $this->_connectionID = $dbc;
-               
-               $dbc->CursorLocation = $this->_cursor_location;
-               return  $dbc->State > 0;
-       }
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')
-       {
-               return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);
-       }       
-       
-/*
-       adSchemaCatalogs        = 1,
-       adSchemaCharacterSets   = 2,
-       adSchemaCollations      = 3,
-       adSchemaColumns = 4,
-       adSchemaCheckConstraints        = 5,
-       adSchemaConstraintColumnUsage   = 6,
-       adSchemaConstraintTableUsage    = 7,
-       adSchemaKeyColumnUsage  = 8,
-       adSchemaReferentialContraints   = 9,
-       adSchemaTableConstraints        = 10,
-       adSchemaColumnsDomainUsage      = 11,
-       adSchemaIndexes = 12,
-       adSchemaColumnPrivileges        = 13,
-       adSchemaTablePrivileges = 14,
-       adSchemaUsagePrivileges = 15,
-       adSchemaProcedures      = 16,
-       adSchemaSchemata        = 17,
-       adSchemaSQLLanguages    = 18,
-       adSchemaStatistics      = 19,
-       adSchemaTables  = 20,
-       adSchemaTranslations    = 21,
-       adSchemaProviderTypes   = 22,
-       adSchemaViews   = 23,
-       adSchemaViewColumnUsage = 24,
-       adSchemaViewTableUsage  = 25,
-       adSchemaProcedureParameters     = 26,
-       adSchemaForeignKeys     = 27,
-       adSchemaPrimaryKeys     = 28,
-       adSchemaProcedureColumns        = 29,
-       adSchemaDBInfoKeywords  = 30,
-       adSchemaDBInfoLiterals  = 31,
-       adSchemaCubes   = 32,
-       adSchemaDimensions      = 33,
-       adSchemaHierarchies     = 34,
-       adSchemaLevels  = 35,
-       adSchemaMeasures        = 36,
-       adSchemaProperties      = 37,
-       adSchemaMembers = 38
-
-*/
-       
-       function &MetaTables()
-       {
-               $arr= array();
-               $dbc = $this->_connectionID;
-               
-               $adors=@$dbc->OpenSchema(20);//tables
-               if ($adors){
-                       $f = $adors->Fields(2);//table/view name
-                       $t = $adors->Fields(3);//table type
-                       while (!$adors->EOF){
-                               $tt=substr($t->value,0,6);
-                               if ($tt!='SYSTEM' && $tt !='ACCESS')
-                                       $arr[]=$f->value;
-                               //print $f->value . ' ' . $t->value.'<br>';
-                               $adors->MoveNext();
-                       }
-                       $adors->Close();
-               }
-               
-               return $arr;
-       }
-       
-       function &MetaColumns($table)
-       {
-               $table = strtoupper($table);
-               $arr= array();
-               $dbc = $this->_connectionID;
-               
-               $adors=@$dbc->OpenSchema(4);//tables
-       
-               if ($adors){
-                       $t = $adors->Fields(2);//table/view name
-                       while (!$adors->EOF){
-                               
-                               
-                               if (strtoupper($t->Value) == $table) {
-                               
-                                       $fld = new ADOFieldObject();
-                                       $c = $adors->Fields(3);
-                                       $fld->name = $c->Value;
-                                       $fld->type = 'CHAR'; // cannot discover type in ADO!
-                                       $fld->max_length = -1;
-                                       $arr[strtoupper($fld->name)]=$fld;
-                               }
-               
-                               $adors->MoveNext();
-                       }
-                       $adors->Close();
-               }
-               
-               return $arr;
-       }
-       
-
-
-       
-       /* returns queryID or false */
-       function &_query($sql,$inputarr=false) 
-       {
-               
-               $dbc = $this->_connectionID;
-               
-       //      return rs       
-               if ($inputarr) {
-                       
-                       if (!empty($this->charPage))
-                               $oCmd = new COM('ADODB.Command',null,$this->charPage);
-                       else
-                               $oCmd = new COM('ADODB.Command');
-                       $oCmd->ActiveConnection = $dbc;
-                       $oCmd->CommandText = $sql;
-                       $oCmd->CommandType = 1;
-
-                       foreach($inputarr as $val) {
-                               // name, type, direction 1 = input, len,
-                               $this->adoParameterType = 130;
-                               $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
-                               //print $p->Type.' '.$p->value;
-                               $oCmd->Parameters->Append($p);
-                       }
-                       $p = false;
-                       $rs = $oCmd->Execute();
-                       $e = $dbc->Errors;
-                       if ($dbc->Errors->Count > 0) return false;
-                       return $rs;
-               }
-               
-               $rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
-               /*
-                       $rs =  new COM('ADODB.Recordset');
-                       if ($rs) {
-                               $rs->Open ($sql, $dbc, $this->_cursor_type,$this->_lock_type, $this->_execute_option);                                                  
-                       }
-               */
-               if ($dbc->Errors->Count > 0) return false;
-               if (! $rs) return false;
-               
-               if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned
-               return $rs;
-       }
-
-       
-       function BeginTrans() 
-       { 
-               if ($this->transOff) return true;
-               
-               if (isset($this->_thisTransactions))
-                       if (!$this->_thisTransactions) return false;
-               else {
-                       $o = $this->_connectionID->Properties("Transaction DDL");
-                       $this->_thisTransactions = $o ? true : false;
-                       if (!$o) return false;
-               }
-               @$this->_connectionID->BeginTrans();
-               $this->transCnt += 1;
-               return true;
-       }
-       function CommitTrans($ok=true) 
-       { 
-               if (!$ok) return $this->RollbackTrans();
-               if ($this->transOff) return true;
-               
-               @$this->_connectionID->CommitTrans();
-               if ($this->transCnt) @$this->transCnt -= 1;
-               return true;
-       }
-       function RollbackTrans() {
-               if ($this->transOff) return true;
-               @$this->_connectionID->RollbackTrans();
-               if ($this->transCnt) @$this->transCnt -= 1;
-               return true;
-       }
-       
-       /*      Returns: the last error message from previous database operation        */      
-
-       function ErrorMsg() 
-       {
-               $errc = $this->_connectionID->Errors;
-               if ($errc->Count == 0) return '';
-               $err = $errc->Item($errc->Count-1);
-               return $err->Description;
-       }
-       
-       function ErrorNo() 
-       {
-               $errc = $this->_connectionID->Errors;
-               if ($errc->Count == 0) return 0;
-               $err = $errc->Item($errc->Count-1);
-               return $err->NativeError;
-       }
-
-       // returns true or false
-       function _close()
-       {
-               if ($this->_connectionID) $this->_connectionID->Close();
-               $this->_connectionID = false;
-               return true;
-       }
-       
-       
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_ado extends ADORecordSet {  
-       
-       var $bind = false;
-       var $databaseType = "ado";      
-       var $dataProvider = "ado";      
-       var $_tarr = false; // caches the types
-       var $_flds; // and field objects
-       var $canSeek = true;
-       var $hideErrors = true;
-                 
-       function ADORecordSet_ado($id,$mode=false)
-       {
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               $this->fetchMode = $mode;
-               return $this->ADORecordSet($id,$mode);
-       }
-
-
-       // returns the field object
-       function FetchField($fieldOffset = -1) {
-               $off=$fieldOffset+1; // offsets begin at 1
-               
-               $o= new ADOFieldObject();
-               $rs = $this->_queryID;
-               $f = $rs->Fields($fieldOffset);
-               $o->name = $f->Name;
-               $t = $f->Type;
-               $o->type = $this->MetaType($t);
-               $o->max_length = $f->DefinedSize;
-               $o->ado_type = $t;
-               
-
-               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
-               return $o;
-       }
-       
-       /* Use associative array to get fields array */
-       function Fields($colname)
-       {
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
-               if (!$this->bind) {
-                       $this->bind = array();
-                       for ($i=0; $i < $this->_numOfFields; $i++) {
-                               $o = $this->FetchField($i);
-                               $this->bind[strtoupper($o->name)] = $i;
-                       }
-               }
-               
-                return $this->fields[$this->bind[strtoupper($colname)]];
-       }
-
-               
-       function _initrs()
-       {
-               $rs = $this->_queryID;
-               $this->_numOfRows = $rs->RecordCount;
-               
-               $f = $rs->Fields;
-               $this->_numOfFields = $f->Count;
-       }
-       
-       
-        // should only be used to move forward as we normally use forward-only cursors
-       function _seek($row)
-       {
-          $rs = $this->_queryID; 
-               // absoluteposition doesn't work -- my maths is wrong ?
-               //      $rs->AbsolutePosition->$row-2;
-               //      return true;
-               if ($this->_currentRow > $row) return false;
-               @$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst
-               return true;
-       }
-       
-/*
-       OLEDB types
-       
-        enum DBTYPEENUM
-       {       DBTYPE_EMPTY    = 0,
-       DBTYPE_NULL     = 1,
-       DBTYPE_I2       = 2,
-       DBTYPE_I4       = 3,
-       DBTYPE_R4       = 4,
-       DBTYPE_R8       = 5,
-       DBTYPE_CY       = 6,
-       DBTYPE_DATE     = 7,
-       DBTYPE_BSTR     = 8,
-       DBTYPE_IDISPATCH        = 9,
-       DBTYPE_ERROR    = 10,
-       DBTYPE_BOOL     = 11,
-       DBTYPE_VARIANT  = 12,
-       DBTYPE_IUNKNOWN = 13,
-       DBTYPE_DECIMAL  = 14,
-       DBTYPE_UI1      = 17,
-       DBTYPE_ARRAY    = 0x2000,
-       DBTYPE_BYREF    = 0x4000,
-       DBTYPE_I1       = 16,
-       DBTYPE_UI2      = 18,
-       DBTYPE_UI4      = 19,
-       DBTYPE_I8       = 20,
-       DBTYPE_UI8      = 21,
-       DBTYPE_GUID     = 72,
-       DBTYPE_VECTOR   = 0x1000,
-       DBTYPE_RESERVED = 0x8000,
-       DBTYPE_BYTES    = 128,
-       DBTYPE_STR      = 129,
-       DBTYPE_WSTR     = 130,
-       DBTYPE_NUMERIC  = 131,
-       DBTYPE_UDT      = 132,
-       DBTYPE_DBDATE   = 133,
-       DBTYPE_DBTIME   = 134,
-       DBTYPE_DBTIMESTAMP      = 135
-       
-       ADO Types
-       
-       adEmpty = 0,
-       adTinyInt       = 16,
-       adSmallInt      = 2,
-       adInteger       = 3,
-       adBigInt        = 20,
-       adUnsignedTinyInt       = 17,
-       adUnsignedSmallInt      = 18,
-       adUnsignedInt   = 19,
-       adUnsignedBigInt        = 21,
-       adSingle        = 4,
-       adDouble        = 5,
-       adCurrency      = 6,
-       adDecimal       = 14,
-       adNumeric       = 131,
-       adBoolean       = 11,
-       adError = 10,
-       adUserDefined   = 132,
-       adVariant       = 12,
-       adIDispatch     = 9,
-       adIUnknown      = 13,   
-       adGUID  = 72,
-       adDate  = 7,
-       adDBDate        = 133,
-       adDBTime        = 134,
-       adDBTimeStamp   = 135,
-       adBSTR  = 8,
-       adChar  = 129,
-       adVarChar       = 200,
-       adLongVarChar   = 201,
-       adWChar = 130,
-       adVarWChar      = 202,
-       adLongVarWChar  = 203,
-       adBinary        = 128,
-       adVarBinary     = 204,
-       adLongVarBinary = 205,
-       adChapter       = 136,
-       adFileTime      = 64,
-       adDBFileTime    = 137,
-       adPropVariant   = 138,
-       adVarNumeric    = 139
-*/
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               
-               if (!is_numeric($t)) return $t;
-               
-               switch ($t) {
-               case 0:
-               case 12: // variant
-               case 8: // bstr
-               case 129: //char
-               case 130: //wc
-               case 200: // varc
-               case 202:// varWC
-               case 128: // bin
-               case 204: // varBin
-               case 72: // guid
-                       if ($len <= $this->blobSize) return 'C';
-               
-               case 201:
-               case 203:
-                       return 'X';
-               case 128:
-               case 204:
-               case 205:
-                        return 'B';
-               case 7:
-               case 133: return 'D';
-               
-               case 134:
-               case 135: return 'T';
-               
-               case 11: return 'L';
-               
-               case 16://      adTinyInt       = 16,
-               case 2://adSmallInt     = 2,
-               case 3://adInteger      = 3,
-               case 4://adBigInt       = 20,
-               case 17://adUnsignedTinyInt     = 17,
-               case 18://adUnsignedSmallInt    = 18,
-               case 19://adUnsignedInt = 19,
-               case 20://adUnsignedBigInt      = 21,
-                       return 'I';
-               default: return 'N';
-               }
-       }
-       
-       // time stamp not supported yet
-       function _fetch()
-       {       
-               $rs = $this->_queryID;
-               if (!$rs or $rs->EOF) {
-                       $this->fields = false;
-                       return false;
-               }
-               $this->fields = array();
-       
-               if (!$this->_tarr) {
-                       $tarr = array();
-                       $flds = array();
-                       for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
-                               $f = $rs->Fields($i);
-                               $flds[] = $f;
-                               $tarr[] = $f->Type;
-                       }
-                       // bind types and flds only once
-                       $this->_tarr = $tarr; 
-                       $this->_flds = $flds;
-               }
-               $t = reset($this->_tarr);
-               $f = reset($this->_flds);
-               
-               if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null
-               for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
-
-                       switch($t) {
-                       case 135: // timestamp
-                               if (!strlen((string)$f->value)) $this->fields[] = false;
-                               else $this->fields[] = adodb_date('Y-m-d H:i:s',(float)$f->value);
-                               break;                  
-                       case 133:// A date value (yyyymmdd) 
-                               if ($val = $f->value) {
-                                       $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);
-                               } else
-                                       $this->fields[] = false;
-                               break;
-                       case 7: // adDate
-                               if (!strlen((string)$f->value)) $this->fields[] = false;
-                               else $this->fields[] = adodb_date('Y-m-d',(float)$f->value);
-                               break;
-                       case 1: // null
-                               $this->fields[] = false;
-                               break;
-                       case 6: // currency is not supported properly;
-                               ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
-                               $this->fields[] = (float) $f->value;
-                               break;
-                       default:
-                               $this->fields[] = $f->value; 
-                               break;
-                       }
-                       //print " $f->value $t, ";
-                       $f = next($this->_flds);
-                       $t = next($this->_tarr);
-               } // for
-               if ($this->hideErrors) error_reporting($olde);
-               @$rs->MoveNext(); // @ needed for some versions of PHP!
-               
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
-                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
-               }
-               return true;
-       }
-       
-               function NextRecordSet()
-               {
-                       $rs = $this->_queryID;
-                       $this->_queryID = $rs->NextRecordSet();
-                       //$this->_queryID = $this->_QueryId->NextRecordSet();
-                       if ($this->_queryID == null) return false;
-                       
-                       $this->_currentRow = -1;
-                       $this->_currentPage = -1;
-                       $this->bind = false;
-                       $this->fields = false;
-                       $this->_flds = false;
-                       $this->_tarr = false;
-                       
-                       $this->_inited = false;
-                       $this->Init();
-                       return true;
-               }
-
-       function _close() {
-               $this->_flds = false;
-               @$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
-               $this->_queryID = false;        
-       }
-
-}
-
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+       Microsoft ADO data driver. Requires ADO. Works only on MS Windows.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+       \r
+define("_ADODB_ADO_LAYER", 1 );\r
+/*--------------------------------------------------------------------------------------\r
+--------------------------------------------------------------------------------------*/\r
+\r
+       \r
+class ADODB_ado extends ADOConnection {\r
+       var $databaseType = "ado";      \r
+       var $_bindInputArray = false;\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $dataProvider = "ado";      \r
+       var $hasAffectedRows = true;\r
+       var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary\r
+       var $_affectedRows = false;\r
+       var $_thisTransactions;\r
+       var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic\r
+       var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;\r
+       var $_lock_type = -1;\r
+       var $_execute_option = -1;\r
+       var $poorAffectedRows = true; \r
+       var $charPage;\r
+               \r
+       function ADODB_ado() \r
+       {       \r
+               $this->_affectedRows = new VARIANT;\r
+       }\r
+\r
+       function ServerInfo()\r
+       {\r
+               if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;\r
+               return array('description' => $desc, 'version' => '');\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+               if (PHP_VERSION >= 5) return $this->_affectedRows;\r
+               \r
+               return $this->_affectedRows->value;\r
+       }\r
+       \r
+       // you can also pass a connection string like this:\r
+       //\r
+       // $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');\r
+       function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')\r
+       {\r
+               $u = 'UID';\r
+               $p = 'PWD';\r
+       \r
+               if (!empty($this->charPage))\r
+                       $dbc = new COM('ADODB.Connection',null,$this->charPage);\r
+               else\r
+                       $dbc = new COM('ADODB.Connection');\r
+                       \r
+               if (! $dbc) return false;\r
+\r
+               /* special support if provider is mssql or access */\r
+               if ($argProvider=='mssql') {\r
+                       $u = 'User Id';  //User parameter name for OLEDB\r
+                       $p = 'Password'; \r
+                       $argProvider = "SQLOLEDB"; // SQL Server Provider\r
+                       \r
+                       // not yet\r
+                       //if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";\r
+                       \r
+                       //use trusted conection for SQL if username not specified\r
+                       if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";\r
+               } else if ($argProvider=='access')\r
+                       $argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider\r
+               \r
+               if ($argProvider) $dbc->Provider = $argProvider;        \r
+               \r
+               if ($argUsername) $argHostname .= ";$u=$argUsername";\r
+               if ($argPassword)$argHostname .= ";$p=$argPassword";\r
+               \r
+               if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");\r
+               // @ added below for php 4.0.1 and earlier\r
+               @$dbc->Open((string) $argHostname);\r
+               \r
+               $this->_connectionID = $dbc;\r
+               \r
+               $dbc->CursorLocation = $this->_cursor_location;\r
+               return  $dbc->State > 0;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')\r
+       {\r
+               return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);\r
+       }       \r
+       \r
+/*\r
+       adSchemaCatalogs        = 1,\r
+       adSchemaCharacterSets   = 2,\r
+       adSchemaCollations      = 3,\r
+       adSchemaColumns = 4,\r
+       adSchemaCheckConstraints        = 5,\r
+       adSchemaConstraintColumnUsage   = 6,\r
+       adSchemaConstraintTableUsage    = 7,\r
+       adSchemaKeyColumnUsage  = 8,\r
+       adSchemaReferentialContraints   = 9,\r
+       adSchemaTableConstraints        = 10,\r
+       adSchemaColumnsDomainUsage      = 11,\r
+       adSchemaIndexes = 12,\r
+       adSchemaColumnPrivileges        = 13,\r
+       adSchemaTablePrivileges = 14,\r
+       adSchemaUsagePrivileges = 15,\r
+       adSchemaProcedures      = 16,\r
+       adSchemaSchemata        = 17,\r
+       adSchemaSQLLanguages    = 18,\r
+       adSchemaStatistics      = 19,\r
+       adSchemaTables  = 20,\r
+       adSchemaTranslations    = 21,\r
+       adSchemaProviderTypes   = 22,\r
+       adSchemaViews   = 23,\r
+       adSchemaViewColumnUsage = 24,\r
+       adSchemaViewTableUsage  = 25,\r
+       adSchemaProcedureParameters     = 26,\r
+       adSchemaForeignKeys     = 27,\r
+       adSchemaPrimaryKeys     = 28,\r
+       adSchemaProcedureColumns        = 29,\r
+       adSchemaDBInfoKeywords  = 30,\r
+       adSchemaDBInfoLiterals  = 31,\r
+       adSchemaCubes   = 32,\r
+       adSchemaDimensions      = 33,\r
+       adSchemaHierarchies     = 34,\r
+       adSchemaLevels  = 35,\r
+       adSchemaMeasures        = 36,\r
+       adSchemaProperties      = 37,\r
+       adSchemaMembers = 38\r
+\r
+*/\r
+       \r
+       function &MetaTables()\r
+       {\r
+               $arr= array();\r
+               $dbc = $this->_connectionID;\r
+               \r
+               $adors=@$dbc->OpenSchema(20);//tables\r
+               if ($adors){\r
+                       $f = $adors->Fields(2);//table/view name\r
+                       $t = $adors->Fields(3);//table type\r
+                       while (!$adors->EOF){\r
+                               $tt=substr($t->value,0,6);\r
+                               if ($tt!='SYSTEM' && $tt !='ACCESS')\r
+                                       $arr[]=$f->value;\r
+                               //print $f->value . ' ' . $t->value.'<br>';\r
+                               $adors->MoveNext();\r
+                       }\r
+                       $adors->Close();\r
+               }\r
+               \r
+               return $arr;\r
+       }\r
+       \r
+       function &MetaColumns($table)\r
+       {\r
+               $table = strtoupper($table);\r
+               $arr= array();\r
+               $dbc = $this->_connectionID;\r
+               \r
+               $adors=@$dbc->OpenSchema(4);//tables\r
+       \r
+               if ($adors){\r
+                       $t = $adors->Fields(2);//table/view name\r
+                       while (!$adors->EOF){\r
+                               \r
+                               \r
+                               if (strtoupper($t->Value) == $table) {\r
+                               \r
+                                       $fld = new ADOFieldObject();\r
+                                       $c = $adors->Fields(3);\r
+                                       $fld->name = $c->Value;\r
+                                       $fld->type = 'CHAR'; // cannot discover type in ADO!\r
+                                       $fld->max_length = -1;\r
+                                       $arr[strtoupper($fld->name)]=$fld;\r
+                               }\r
+               \r
+                               $adors->MoveNext();\r
+                       }\r
+                       $adors->Close();\r
+               }\r
+               \r
+               return $arr;\r
+       }\r
+       \r
+\r
+\r
+       \r
+       /* returns queryID or false */\r
+       function &_query($sql,$inputarr=false) \r
+       {\r
+               \r
+               $dbc = $this->_connectionID;\r
+               \r
+       //      return rs       \r
+               if ($inputarr) {\r
+                       \r
+                       if (!empty($this->charPage))\r
+                               $oCmd = new COM('ADODB.Command',null,$this->charPage);\r
+                       else\r
+                               $oCmd = new COM('ADODB.Command');\r
+                       $oCmd->ActiveConnection = $dbc;\r
+                       $oCmd->CommandText = $sql;\r
+                       $oCmd->CommandType = 1;\r
+\r
+                       foreach($inputarr as $val) {\r
+                               // name, type, direction 1 = input, len,\r
+                               $this->adoParameterType = 130;\r
+                               $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);\r
+                               //print $p->Type.' '.$p->value;\r
+                               $oCmd->Parameters->Append($p);\r
+                       }\r
+                       $p = false;\r
+                       $rs = $oCmd->Execute();\r
+                       $e = $dbc->Errors;\r
+                       if ($dbc->Errors->Count > 0) return false;\r
+                       return $rs;\r
+               }\r
+               \r
+               $rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);\r
+               /*\r
+                       $rs =  new COM('ADODB.Recordset');\r
+                       if ($rs) {\r
+                               $rs->Open ($sql, $dbc, $this->_cursor_type,$this->_lock_type, $this->_execute_option);                                                  \r
+                       }\r
+               */\r
+               if ($dbc->Errors->Count > 0) return false;\r
+               if (! $rs) return false;\r
+               \r
+               if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned\r
+               return $rs;\r
+       }\r
+\r
+       \r
+       function BeginTrans() \r
+       { \r
+               if ($this->transOff) return true;\r
+               \r
+               if (isset($this->_thisTransactions))\r
+                       if (!$this->_thisTransactions) return false;\r
+               else {\r
+                       $o = $this->_connectionID->Properties("Transaction DDL");\r
+                       $this->_thisTransactions = $o ? true : false;\r
+                       if (!$o) return false;\r
+               }\r
+               @$this->_connectionID->BeginTrans();\r
+               $this->transCnt += 1;\r
+               return true;\r
+       }\r
+       function CommitTrans($ok=true) \r
+       { \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transOff) return true;\r
+               \r
+               @$this->_connectionID->CommitTrans();\r
+               if ($this->transCnt) @$this->transCnt -= 1;\r
+               return true;\r
+       }\r
+       function RollbackTrans() {\r
+               if ($this->transOff) return true;\r
+               @$this->_connectionID->RollbackTrans();\r
+               if ($this->transCnt) @$this->transCnt -= 1;\r
+               return true;\r
+       }\r
+       \r
+       /*      Returns: the last error message from previous database operation        */      \r
+\r
+       function ErrorMsg() \r
+       {\r
+               $errc = $this->_connectionID->Errors;\r
+               if ($errc->Count == 0) return '';\r
+               $err = $errc->Item($errc->Count-1);\r
+               return $err->Description;\r
+       }\r
+       \r
+       function ErrorNo() \r
+       {\r
+               $errc = $this->_connectionID->Errors;\r
+               if ($errc->Count == 0) return 0;\r
+               $err = $errc->Item($errc->Count-1);\r
+               return $err->NativeError;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if ($this->_connectionID) $this->_connectionID->Close();\r
+               $this->_connectionID = false;\r
+               return true;\r
+       }\r
+       \r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_ado extends ADORecordSet {  \r
+       \r
+       var $bind = false;\r
+       var $databaseType = "ado";      \r
+       var $dataProvider = "ado";      \r
+       var $_tarr = false; // caches the types\r
+       var $_flds; // and field objects\r
+       var $canSeek = true;\r
+       var $hideErrors = true;\r
+                 \r
+       function ADORecordSet_ado($id,$mode=false)\r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               return $this->ADORecordSet($id,$mode);\r
+       }\r
+\r
+\r
+       // returns the field object\r
+       function FetchField($fieldOffset = -1) {\r
+               $off=$fieldOffset+1; // offsets begin at 1\r
+               \r
+               $o= new ADOFieldObject();\r
+               $rs = $this->_queryID;\r
+               $f = $rs->Fields($fieldOffset);\r
+               $o->name = $f->Name;\r
+               $t = $f->Type;\r
+               $o->type = $this->MetaType($t);\r
+               $o->max_length = $f->DefinedSize;\r
+               $o->ado_type = $t;\r
+               \r
+\r
+               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";\r
+               return $o;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+\r
+               \r
+       function _initrs()\r
+       {\r
+               $rs = $this->_queryID;\r
+               $this->_numOfRows = $rs->RecordCount;\r
+               \r
+               $f = $rs->Fields;\r
+               $this->_numOfFields = $f->Count;\r
+       }\r
+       \r
+       \r
+        // should only be used to move forward as we normally use forward-only cursors\r
+       function _seek($row)\r
+       {\r
+          $rs = $this->_queryID; \r
+               // absoluteposition doesn't work -- my maths is wrong ?\r
+               //      $rs->AbsolutePosition->$row-2;\r
+               //      return true;\r
+               if ($this->_currentRow > $row) return false;\r
+               @$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst\r
+               return true;\r
+       }\r
+       \r
+/*\r
+       OLEDB types\r
+       \r
+        enum DBTYPEENUM\r
+       {       DBTYPE_EMPTY    = 0,\r
+       DBTYPE_NULL     = 1,\r
+       DBTYPE_I2       = 2,\r
+       DBTYPE_I4       = 3,\r
+       DBTYPE_R4       = 4,\r
+       DBTYPE_R8       = 5,\r
+       DBTYPE_CY       = 6,\r
+       DBTYPE_DATE     = 7,\r
+       DBTYPE_BSTR     = 8,\r
+       DBTYPE_IDISPATCH        = 9,\r
+       DBTYPE_ERROR    = 10,\r
+       DBTYPE_BOOL     = 11,\r
+       DBTYPE_VARIANT  = 12,\r
+       DBTYPE_IUNKNOWN = 13,\r
+       DBTYPE_DECIMAL  = 14,\r
+       DBTYPE_UI1      = 17,\r
+       DBTYPE_ARRAY    = 0x2000,\r
+       DBTYPE_BYREF    = 0x4000,\r
+       DBTYPE_I1       = 16,\r
+       DBTYPE_UI2      = 18,\r
+       DBTYPE_UI4      = 19,\r
+       DBTYPE_I8       = 20,\r
+       DBTYPE_UI8      = 21,\r
+       DBTYPE_GUID     = 72,\r
+       DBTYPE_VECTOR   = 0x1000,\r
+       DBTYPE_RESERVED = 0x8000,\r
+       DBTYPE_BYTES    = 128,\r
+       DBTYPE_STR      = 129,\r
+       DBTYPE_WSTR     = 130,\r
+       DBTYPE_NUMERIC  = 131,\r
+       DBTYPE_UDT      = 132,\r
+       DBTYPE_DBDATE   = 133,\r
+       DBTYPE_DBTIME   = 134,\r
+       DBTYPE_DBTIMESTAMP      = 135\r
+       \r
+       ADO Types\r
+       \r
+       adEmpty = 0,\r
+       adTinyInt       = 16,\r
+       adSmallInt      = 2,\r
+       adInteger       = 3,\r
+       adBigInt        = 20,\r
+       adUnsignedTinyInt       = 17,\r
+       adUnsignedSmallInt      = 18,\r
+       adUnsignedInt   = 19,\r
+       adUnsignedBigInt        = 21,\r
+       adSingle        = 4,\r
+       adDouble        = 5,\r
+       adCurrency      = 6,\r
+       adDecimal       = 14,\r
+       adNumeric       = 131,\r
+       adBoolean       = 11,\r
+       adError = 10,\r
+       adUserDefined   = 132,\r
+       adVariant       = 12,\r
+       adIDispatch     = 9,\r
+       adIUnknown      = 13,   \r
+       adGUID  = 72,\r
+       adDate  = 7,\r
+       adDBDate        = 133,\r
+       adDBTime        = 134,\r
+       adDBTimeStamp   = 135,\r
+       adBSTR  = 8,\r
+       adChar  = 129,\r
+       adVarChar       = 200,\r
+       adLongVarChar   = 201,\r
+       adWChar = 130,\r
+       adVarWChar      = 202,\r
+       adLongVarWChar  = 203,\r
+       adBinary        = 128,\r
+       adVarBinary     = 204,\r
+       adLongVarBinary = 205,\r
+       adChapter       = 136,\r
+       adFileTime      = 64,\r
+       adDBFileTime    = 137,\r
+       adPropVariant   = 138,\r
+       adVarNumeric    = 139\r
+*/\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               if (!is_numeric($t)) return $t;\r
+               \r
+               switch ($t) {\r
+               case 0:\r
+               case 12: // variant\r
+               case 8: // bstr\r
+               case 129: //char\r
+               case 130: //wc\r
+               case 200: // varc\r
+               case 202:// varWC\r
+               case 128: // bin\r
+               case 204: // varBin\r
+               case 72: // guid\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               \r
+               case 201:\r
+               case 203:\r
+                       return 'X';\r
+               case 128:\r
+               case 204:\r
+               case 205:\r
+                        return 'B';\r
+               case 7:\r
+               case 133: return 'D';\r
+               \r
+               case 134:\r
+               case 135: return 'T';\r
+               \r
+               case 11: return 'L';\r
+               \r
+               case 16://      adTinyInt       = 16,\r
+               case 2://adSmallInt     = 2,\r
+               case 3://adInteger      = 3,\r
+               case 4://adBigInt       = 20,\r
+               case 17://adUnsignedTinyInt     = 17,\r
+               case 18://adUnsignedSmallInt    = 18,\r
+               case 19://adUnsignedInt = 19,\r
+               case 20://adUnsignedBigInt      = 21,\r
+                       return 'I';\r
+               default: return 'N';\r
+               }\r
+       }\r
+       \r
+       // time stamp not supported yet\r
+       function _fetch()\r
+       {       \r
+               $rs = $this->_queryID;\r
+               if (!$rs or $rs->EOF) {\r
+                       $this->fields = false;\r
+                       return false;\r
+               }\r
+               $this->fields = array();\r
+       \r
+               if (!$this->_tarr) {\r
+                       $tarr = array();\r
+                       $flds = array();\r
+                       for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
+                               $f = $rs->Fields($i);\r
+                               $flds[] = $f;\r
+                               $tarr[] = $f->Type;\r
+                       }\r
+                       // bind types and flds only once\r
+                       $this->_tarr = $tarr; \r
+                       $this->_flds = $flds;\r
+               }\r
+               $t = reset($this->_tarr);\r
+               $f = reset($this->_flds);\r
+               \r
+               if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null\r
+               for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
+\r
+                       switch($t) {\r
+                       case 135: // timestamp\r
+                               if (!strlen((string)$f->value)) $this->fields[] = false;\r
+                               else $this->fields[] = adodb_date('Y-m-d H:i:s',(float)$f->value);\r
+                               break;                  \r
+                       case 133:// A date value (yyyymmdd) \r
+                               if ($val = $f->value) {\r
+                                       $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);\r
+                               } else\r
+                                       $this->fields[] = false;\r
+                               break;\r
+                       case 7: // adDate\r
+                               if (!strlen((string)$f->value)) $this->fields[] = false;\r
+                               else $this->fields[] = adodb_date('Y-m-d',(float)$f->value);\r
+                               break;\r
+                       case 1: // null\r
+                               $this->fields[] = false;\r
+                               break;\r
+                       case 6: // currency is not supported properly;\r
+                               ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');\r
+                               $this->fields[] = (float) $f->value;\r
+                               break;\r
+                       default:\r
+                               $this->fields[] = $f->value; \r
+                               break;\r
+                       }\r
+                       //print " $f->value $t, ";\r
+                       $f = next($this->_flds);\r
+                       $t = next($this->_tarr);\r
+               } // for\r
+               if ($this->hideErrors) error_reporting($olde);\r
+               @$rs->MoveNext(); // @ needed for some versions of PHP!\r
+               \r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+               }\r
+               return true;\r
+       }\r
+       \r
+               function NextRecordSet()\r
+               {\r
+                       $rs = $this->_queryID;\r
+                       $this->_queryID = $rs->NextRecordSet();\r
+                       //$this->_queryID = $this->_QueryId->NextRecordSet();\r
+                       if ($this->_queryID == null) return false;\r
+                       \r
+                       $this->_currentRow = -1;\r
+                       $this->_currentPage = -1;\r
+                       $this->bind = false;\r
+                       $this->fields = false;\r
+                       $this->_flds = false;\r
+                       $this->_tarr = false;\r
+                       \r
+                       $this->_inited = false;\r
+                       $this->Init();\r
+                       return true;\r
+               }\r
+\r
+       function _close() {\r
+               $this->_flds = false;\r
+               @$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)\r
+               $this->_queryID = false;        \r
+       }\r
+\r
+}\r
+\r
 ?>
\ No newline at end of file
index 74b37a5776054c6ef1847c8b69ca1edab58cc3cb..955fc6d80e844a238e9927630e26b6f416e54a73 100644 (file)
@@ -1,46 +1,49 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-Released under both BSD license and Lesser GPL library license. 
-Whenever there is any discrepancy between the two licenses, 
-the BSD license will take precedence. See License.txt. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-       Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.
-*/
-
-if (!defined('_ADODB_ADO_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-ado.inc.php");
-}
-
-class  ADODB_ado_access extends ADODB_ado {    
-       var $databaseType = 'ado_access';
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
-       var $fmtDate = "#Y-m-d#";
-       var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma
-       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
-       var $sysTimeStamp = 'NOW';
-       var $hasTransactions = false;
-       
-       function ADODB_ado_access()
-       {
-               $this->ADODB_ado();
-       }
-       
-       function BeginTrans() { return false;}
-
-}
-
-class  ADORecordSet_ado_access extends ADORecordSet_ado {      
-       
-       var $databaseType = "ado_access";               
-       
-       function ADORecordSet_ado_access($id,$mode=false)
-       {
-               return $this->ADORecordSet_ado($id,$mode);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+Released under both BSD license and Lesser GPL library license. \r
+Whenever there is any discrepancy between the two licenses, \r
+the BSD license will take precedence. See License.txt. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+       Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ADO_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-ado.inc.php");\r
+}\r
+\r
+class  ADODB_ado_access extends ADODB_ado {    \r
+       var $databaseType = 'ado_access';\r
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $fmtDate = "#Y-m-d#";\r
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma\r
+       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";\r
+       var $sysTimeStamp = 'NOW';\r
+       var $hasTransactions = false;\r
+       \r
+       function ADODB_ado_access()\r
+       {\r
+               $this->ADODB_ado();\r
+       }\r
+       \r
+       function BeginTrans() { return false;}\r
+\r
+}\r
+\r
\r
+class  ADORecordSet_ado_access extends ADORecordSet_ado {      \r
+       \r
+       var $databaseType = "ado_access";               \r
+       \r
+       function ADORecordSet_ado_access($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_ado($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index fec181abc88e3d4a49bed14556a9cb832d8475c4..e18440bc3e7389a441e76f78190d774435f79166 100644 (file)
@@ -1,62 +1,97 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. 
-  Works only on MS Windows.
-  
-  It is normally better to use the mssql driver directly because it is much faster. 
-  This file is only a technology demonstration and for test purposes.
-*/
-
-if (!defined('_ADODB_ADO_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-ado.inc.php");
-}
-
-class  ADODB_ado_mssql extends ADODB_ado {     
-       var $databaseType = 'ado_mssql';
-       var $hasTop = 'top';
-       var $sysDate = 'GetDate()';
-       var $sysTimeStamp = 'GetDate()';
-       var $leftOuter = '*=';
-       var $rightOuter = '=*';
-       var $ansiOuter = true; // for mssql7 or later
-       var $substr = "substring";
-       var $length = 'len';
-       var $upperCase = 'upper';
-       
-       //var $_inTransaction = 1; // always open recordsets, so no transaction problems.
-       
-       function ADODB_ado_mssql()
-       {
-               $this->ADODB_ado();
-       }
-       
-       function _insertid()
-       {
-               return $this->GetOne('select @@identity');
-       }
-       
-       function _affectedrows()
-       {
-               return $this->GetOne('select @@rowcount');
-       }
-       
-}
-class  ADORecordSet_ado_mssql extends ADORecordSet_ado {       
-       
-       var $databaseType = 'ado_mssql';
-       
-       function ADORecordSet_ado_mssql($id,$mode=false)
-       {
-               return $this->ADORecordSet_ado($id,$mode);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. \r
+  Works only on MS Windows.\r
+  \r
+  It is normally better to use the mssql driver directly because it is much faster. \r
+  This file is only a technology demonstration and for test purposes.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ADO_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-ado.inc.php");\r
+}\r
+\r
+\r
+class  ADODB_ado_mssql extends ADODB_ado {        \r
+       var $databaseType = 'ado_mssql';\r
+       var $hasTop = 'top';\r
+       var $hasInsertID = true;\r
+       var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';\r
+       var $sysTimeStamp = 'GetDate()';\r
+       var $leftOuter = '*=';\r
+       var $rightOuter = '=*';\r
+       var $ansiOuter = true; // for mssql7 or later\r
+       var $substr = "substring";\r
+       var $length = 'len';\r
+       var $upperCase = 'upper';\r
+       \r
+       //var $_inTransaction = 1; // always open recordsets, so no transaction problems.\r
+       \r
+       function ADODB_ado_mssql()\r
+       {\r
+               $this->ADODB_ado();\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+               return $this->GetOne('select @@identity');\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+               return $this->GetOne('select @@rowcount');\r
+       }\r
+       \r
+       function MetaColumns($table)\r
+       {\r
+               $table = strtoupper($table);\r
+               $arr= array();\r
+               $dbc = $this->_connectionID;\r
+               \r
+               $osoptions = array();\r
+               $osoptions[0] = null;\r
+               $osoptions[1] = null;\r
+               $osoptions[2] = $table;\r
+               $osoptions[3] = null;\r
+               \r
+               $adors=@$dbc->OpenSchema(4, $osoptions);//tables\r
+       \r
+               if ($adors){\r
+                       while (!$adors->EOF){\r
+                               $fld = new ADOFieldObject();\r
+                               $c = $adors->Fields(3);\r
+                               $fld->name = $c->Value;\r
+                               $fld->type = 'CHAR'; // cannot discover type in ADO!\r
+                               $fld->max_length = -1;\r
+                               $arr[strtoupper($fld->name)]=$fld;\r
+               \r
+                               $adors->MoveNext();\r
+                       }\r
+                       $adors->Close();\r
+               }\r
+               \r
+               return $arr;\r
+       }\r
+       }\r
+       \r
+       class  ADORecordSet_ado_mssql extends ADORecordSet_ado {        \r
+       \r
+       var $databaseType = 'ado_mssql';\r
+       \r
+       function ADORecordSet_ado_mssql($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_ado($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 4030c7189beacb5d526e2c04768ef0f21cb06764..410f61adbe590f63009bcbdcd848a4e56c3e5d73 100644 (file)
@@ -1,79 +1,91 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Support Borland Interbase 6.5 and later
-
-*/
-
-include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
-
-class ADODB_borland_ibase extends ADODB_ibase {
-       var $databaseType = "borland_ibase";    
-       
-       function ADODB_borland_ibase()
-       {
-               $this->ADODB_ibase();
-       }
-       
-       function ServerInfo()
-       {
-               $arr['dialect'] = $this->dialect;
-               switch($arr['dialect']) {
-               case '': 
-               case '1': $s = 'Interbase 6.5, Dialect 1'; break;
-               case '2': $s = 'Interbase 6.5, Dialect 2'; break;
-               default:
-               case '3': $s = 'Interbase 6.5, Dialect 3'; break;
-               }
-               $arr['version'] = '6.5';
-               $arr['description'] = $s;
-               return $arr;
-       }
-       
-       // Note that Interbase 6.5 uses 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
-       // Firebird uses
-       //              SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
-       {
-               if ($nrows > 0) {
-                       if ($offset <= 0) $str = " ROWS $nrows "; 
-                       else {
-                               $a = $offset+1;
-                               $b = $offset+$nrows;
-                               $str = " ROWS $a TO $b";
-                       }
-               } else {
-                       // ok, skip 
-                       $a = $offset + 1;
-                       $str = " ROWS $a TO 999999999"; // 999 million
-               }
-               $sql .= $str;
-               
-               return ($secs2cache) ? 
-                               $this->CacheExecute($secs2cache,$sql,$inputarr)
-                       :
-                               $this->Execute($sql,$inputarr);
-       }
-       
-};
-
-class  ADORecordSet_borland_ibase extends ADORecordSet_ibase { 
-       
-       var $databaseType = "borland_ibase";            
-       
-       function ADORecordSet_borland_ibase($id,$mode=false)
-       {
-               $this->ADORecordSet_ibase($id,$mode);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Support Borland Interbase 6.5 and later\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");\r
+\r
+class ADODB_borland_ibase extends ADODB_ibase {\r
+       var $databaseType = "borland_ibase";    \r
+       \r
+       function ADODB_borland_ibase()\r
+       {\r
+               $this->ADODB_ibase();\r
+       }\r
+       \r
+       function BeginTrans()\r
+       {        \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->autoCommit = false;\r
+               $this->_transactionID = ibase_trans($this->ibasetrans, $this->_connectionID);\r
+               return $this->_transactionID;\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['dialect'] = $this->dialect;\r
+               switch($arr['dialect']) {\r
+               case '': \r
+               case '1': $s = 'Interbase 6.5, Dialect 1'; break;\r
+               case '2': $s = 'Interbase 6.5, Dialect 2'; break;\r
+               default:\r
+               case '3': $s = 'Interbase 6.5, Dialect 3'; break;\r
+               }\r
+               $arr['version'] = '6.5';\r
+               $arr['description'] = $s;\r
+               return $arr;\r
+       }\r
+       \r
+       // Note that Interbase 6.5 uses ROWS instead - don't you love forking wars!\r
+       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows \r
+       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2\r
+       // Firebird uses\r
+       //              SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)\r
+       {\r
+               if ($nrows > 0) {\r
+                       if ($offset <= 0) $str = " ROWS $nrows "; \r
+                       else {\r
+                               $a = $offset+1;\r
+                               $b = $offset+$nrows;\r
+                               $str = " ROWS $a TO $b";\r
+                       }\r
+               } else {\r
+                       // ok, skip \r
+                       $a = $offset + 1;\r
+                       $str = " ROWS $a TO 999999999"; // 999 million\r
+               }\r
+               $sql .= $str;\r
+               \r
+               return ($secs2cache) ? \r
+                               $this->CacheExecute($secs2cache,$sql,$inputarr)\r
+                       :\r
+                               $this->Execute($sql,$inputarr);\r
+       }\r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_borland_ibase extends ADORecordSet_ibase { \r
+       \r
+       var $databaseType = "borland_ibase";            \r
+       \r
+       function ADORecordSet_borland_ibase($id,$mode=false)\r
+       {\r
+               $this->ADORecordSet_ibase($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index a444d9e0f93b26eeea153b87db9dd1e1e2e475a0..75c5760817c45d6ef02be4b93631200b8f7672b8 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-  
-  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.
-  Native types have been converted to MetaTypes.
-  Transactions not supported yet.
-*/ 
-
-if (! defined("_ADODB_CSV_LAYER")) {
- define("_ADODB_CSV_LAYER", 1 );
-
-include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
-class ADODB_csv extends ADOConnection {
-       var $databaseType = 'csv';
-       var $databaseProvider = 'csv';
-       var $hasInsertID = true;
-       var $hasAffectedRows = true;    
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       var $_affectedrows=0;
-       var $_insertid=0;
-       var $_url;
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $hasTransactions = false;
-       var $_errorNo = false;
-       
-       function ADODB_csv() 
-       {               
-       }
-       
-       function _insertid()
-       {
-                       return $this->_insertid;
-       }
-       
-       function _affectedrows()
-       {
-                       return $this->_affectedrows;
-       }
-  
-       function &MetaDatabases()
-       {
-               return false;
-       }
-
-       
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
-               $this->_url = $argHostname;
-               return true;    
-       }
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
-               $this->_url = $argHostname;
-               return true;
-       }
-       
-       function &MetaColumns($table) 
-       {
-               return false;
-       }
-               
-               
-       // parameters use PostgreSQL convention, not MySQL
-       function &SelectLimit($sql,$nrows=-1,$offset=-1)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".
-                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).
-                       "&offset=$offset";
-               $err = false;
-               $rs = csv2rs($url,$err,false);
-               
-               if ($this->debug) print "$url<br><i>$err</i><br>";
-
-               $at = strpos($err,'::::');
-               if ($at === false) {
-                       $this->_errorMsg = $err;
-                       $this->_errorNo = (integer)$err;
-               } else {
-                       $this->_errorMsg = substr($err,$at+4,1024);
-                       $this->_errorNo = -9999;
-               }
-               if ($this->_errorNo) 
-                       if ($fn = $this->raiseErrorFn) {
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');
-                       }
-                       
-               if (is_object($rs)) {   
-               
-                       $rs->databaseType='csv';                
-                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
-                       $rs->connection = &$this;
-               }
-               return $rs;
-       }
-       
-       // returns queryID or false
-       function &_Execute($sql,$inputarr=false)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               if (!$this->_bindInputArray && $inputarr) {
-                       $sqlarr = explode('?',$sql);
-                       $sql = '';
-                       $i = 0;
-                       foreach($inputarr as $v) {
-
-                               $sql .= $sqlarr[$i];
-                               if (gettype($v) == 'string')
-                                       $sql .= $this->qstr($v);
-                               else if ($v === null)
-                                       $sql .= 'NULL';
-                               else
-                                       $sql .= $v;
-                               $i += 1;
-       
-                       }
-                       $sql .= $sqlarr[$i];
-                       if ($i+1 != sizeof($sqlarr))    
-                               print "Input Array does not match ?: ".htmlspecialchars($sql);
-                       $inputarr = false;
-               }
-               
-               $url =  $this->_url.'?sql='.urlencode($sql)."&fetch=".
-                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);
-               $err = false;
-               
-               
-               $rs = csv2rs($url,$err,false);
-               if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";
-               $at = strpos($err,'::::');
-               if ($at === false) {            
-                       $this->_errorMsg = $err;
-                       $this->_errorNo = (integer)$err;
-               } else {
-                       $this->_errorMsg = substr($err,$at+4,1024);
-                       $this->_errorNo = -9999;
-               }
-               
-               if ($this->_errorNo) 
-                       if ($fn = $this->raiseErrorFn) {
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);
-                       }
-               if (is_object($rs)) {
-                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
-                       
-                       $this->_affectedrows = $rs->affectedrows;
-                       $this->_insertid = $rs->insertid;
-                       $rs->databaseType='csv';
-                       $rs->connection = &$this;
-               }
-               return $rs;
-       }
-
-       /*      Returns: the last error message from previous database operation        */      
-       function ErrorMsg() 
-       {
-                       return $this->_errorMsg;
-       }
-       
-       /*      Returns: the last error number from previous database operation */      
-       function ErrorNo() 
-       {
-               return $this->_errorNo;
-       }
-       
-       // returns true or false
-       function _close()
-       {
-               return true;
-       }
-} // class
-
-class ADORecordset_csv extends ADORecordset {
-       function ADORecordset_csv($id,$mode=false)
-       {
-               $this->ADORecordset($id,$mode);
-       }
-       
-       function _close()
-       {
-               return true;
-       }
-}
-
-} // define
-       
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.\r
+  Native types have been converted to MetaTypes.\r
+  Transactions not supported yet.\r
+*/ \r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (! defined("_ADODB_CSV_LAYER")) {\r
+ define("_ADODB_CSV_LAYER", 1 );\r
+\r
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
\r
+class ADODB_csv extends ADOConnection {\r
+       var $databaseType = 'csv';\r
+       var $databaseProvider = 'csv';\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;    \r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $_affectedrows=0;\r
+       var $_insertid=0;\r
+       var $_url;\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $hasTransactions = false;\r
+       var $_errorNo = false;\r
+       \r
+       function ADODB_csv() \r
+       {               \r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+                       return $this->_insertid;\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+                       return $this->_affectedrows;\r
+       }\r
+  \r
+       function &MetaDatabases()\r
+       {\r
+               return false;\r
+       }\r
+\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;\r
+               $this->_url = $argHostname;\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;\r
+               $this->_url = $argHostname;\r
+               return true;\r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               return false;\r
+       }\r
+               \r
+               \r
+       // parameters use PostgreSQL convention, not MySQL\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".\r
+                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).\r
+                       "&offset=$offset";\r
+               $err = false;\r
+               $rs = csv2rs($url,$err,false);\r
+               \r
+               if ($this->debug) print "$url<br><i>$err</i><br>";\r
+\r
+               $at = strpos($err,'::::');\r
+               if ($at === false) {\r
+                       $this->_errorMsg = $err;\r
+                       $this->_errorNo = (integer)$err;\r
+               } else {\r
+                       $this->_errorMsg = substr($err,$at+4,1024);\r
+                       $this->_errorNo = -9999;\r
+               }\r
+               if ($this->_errorNo) \r
+                       if ($fn = $this->raiseErrorFn) {\r
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');\r
+                       }\r
+                       \r
+               if (is_object($rs)) {   \r
+               \r
+                       $rs->databaseType='csv';                \r
+                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;\r
+                       $rs->connection = &$this;\r
+               }\r
+               return $rs;\r
+       }\r
+       \r
+       // returns queryID or false\r
+       function &_Execute($sql,$inputarr=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               if (!$this->_bindInputArray && $inputarr) {\r
+                       $sqlarr = explode('?',$sql);\r
+                       $sql = '';\r
+                       $i = 0;\r
+                       foreach($inputarr as $v) {\r
+\r
+                               $sql .= $sqlarr[$i];\r
+                               if (gettype($v) == 'string')\r
+                                       $sql .= $this->qstr($v);\r
+                               else if ($v === null)\r
+                                       $sql .= 'NULL';\r
+                               else\r
+                                       $sql .= $v;\r
+                               $i += 1;\r
+       \r
+                       }\r
+                       $sql .= $sqlarr[$i];\r
+                       if ($i+1 != sizeof($sqlarr))    \r
+                               print "Input Array does not match ?: ".htmlspecialchars($sql);\r
+                       $inputarr = false;\r
+               }\r
+               \r
+               $url =  $this->_url.'?sql='.urlencode($sql)."&fetch=".\r
+                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);\r
+               $err = false;\r
+               \r
+               \r
+               $rs = csv2rs($url,$err,false);\r
+               if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";\r
+               $at = strpos($err,'::::');\r
+               if ($at === false) {            \r
+                       $this->_errorMsg = $err;\r
+                       $this->_errorNo = (integer)$err;\r
+               } else {\r
+                       $this->_errorMsg = substr($err,$at+4,1024);\r
+                       $this->_errorNo = -9999;\r
+               }\r
+               \r
+               if ($this->_errorNo) \r
+                       if ($fn = $this->raiseErrorFn) {\r
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);\r
+                       }\r
+               if (is_object($rs)) {\r
+                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;\r
+                       \r
+                       $this->_affectedrows = $rs->affectedrows;\r
+                       $this->_insertid = $rs->insertid;\r
+                       $rs->databaseType='csv';\r
+                       $rs->connection = &$this;\r
+               }\r
+               return $rs;\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+                       return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+               return $this->_errorNo;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return true;\r
+       }\r
+} // class\r
+\r
+class ADORecordset_csv extends ADORecordset {\r
+       function ADORecordset_csv($id,$mode=false)\r
+       {\r
+               $this->ADORecordset($id,$mode);\r
+       }\r
+       \r
+       function _close()\r
+       {\r
+               return true;\r
+       }\r
+}\r
+\r
+} // define\r
+       \r
 ?>
\ No newline at end of file
index d901abf8aaa43ca3e78a767295173f3565de1b07..8d7b973d7583042b52d641fd225cdcf19468cf05 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  DB2 data driver. Requires ODBC.
-From phpdb list:
-
-Hi Andrew,
-
-thanks a lot for your help. Today we discovered what
-our real problem was:
-
-After "playing" a little bit with the php-scripts that try
-to connect to the IBM DB2, we set the optional parameter
-Cursortype when calling odbc_pconnect(....).
-
-And the exciting thing: When we set the cursor type
-to SQL_CUR_USE_ODBC Cursor Type, then
-the whole query speed up from 1 till 10 seconds
-to 0.2 till 0.3 seconds for 100 records. Amazing!!!
-
-Therfore, PHP is just almost fast as calling the DB2
-from Servlets using JDBC (don't take too much care
-about the speed at whole: the database was on a
-completely other location, so the whole connection
-was made over a slow network connection).
-
-I hope this helps when other encounter the same
-problem when trying to connect to DB2 from
-PHP.
-
-Kind regards,
-Christian Szardenings
-
-2 Oct 2001
-Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by 
-IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.
-
-From the IBM CLI Reference:
-
-SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) 
-This connection attribute is defined by ODBC, but is not supported by DB2
-CLI. Any attempt to set or get this attribute will result in an SQLSTATE of
-HYC00 (Driver not capable). 
-
-A 32-bit option specifying how the Driver Manager uses the ODBC cursor
-library. 
-
-So I guess this means the message [above] was related to using a 3rd party
-odbc driver.
-
-Setting SQL_CUR_USE_ODBC
-========================
-To set SQL_CUR_USE_ODBC for drivers that require it, do this:
-
-$db = NewADOConnection('db2');
-$db->curMode = SQL_CUR_USE_ODBC;
-$db->Connect($dsn, $userid, $pwd);
-
-
-
-USING CLI INTERFACE
-===================
-
-I have had reports that the $host and $database params have to be reversed in 
-Connect() when using the CLI interface. From Halmai Csongor csongor.halmai#nexum.hu:
-
-> The symptom is that if I change the database engine from postgres or any other to DB2 then the following
-> connection command becomes wrong despite being described this version to be correct in the docs. 
->
-> $connection_object->Connect( $DATABASE_HOST, $DATABASE_AUTH_USER_NAME, $DATABASE_AUTH_PASSWORD, $DATABASE_NAME )
->
-> In case of DB2 I had to swap the first and last arguments in order to connect properly. 
-
-
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-if (!defined('ADODB_DB2')){
-define('ADODB_DB2',1);
-
-class ADODB_DB2 extends ADODB_odbc {
-       var $databaseType = "db2";      
-       var $concat_operator = '||';
-       var $sysDate = 'CURRENT_DATE';
-       var $sysTimeStamp = 'CURRENT TIMESTAMP';
-       // The complete string representation of a timestamp has the form 
-       // yyyy-mm-dd-hh.mm.ss.nnnnnn.
-       var $fmtTimeStamp = "'Y-m-d-H.i.s'";
-       var $ansiOuter = true;
-       var $identitySQL = 'values IDENTITY_VAL_LOCAL()';
-       var $_bindInputArray = false;
-       var $upperCase = 'upper';
-       
-       
-       function ADODB_DB2()
-       {
-               if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
-               $this->ADODB_odbc();
-       }
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " COALESCE($field, $ifNull) "; // if DB2 UDB
-       }
-       
-       function ServerInfo()
-       {
-               //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/);
-               $vers = $this->GetOne('select versionnumber from sysibm.sysversions');
-               //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/);
-               return array('description'=>'DB2 ODBC driver', 'version'=>$vers);
-       }
-       
-       function _insertid()
-       {
-               return $this->GetOne($this->identitySQL);
-       }
-       
-       function RowLock($tables,$where)
-       {
-               if ($this->_autocommit) $this->BeginTrans();
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");
-       }
-       
-       function &MetaTables($ttype=false,$showSchema=false)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $savem = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $qid = odbc_tables($this->_connectionID);
-               
-               $rs = new ADORecordSet_odbc($qid);
-               
-               $ADODB_FETCH_MODE = $savem;
-               if (!$rs) return false;
-               
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
-               
-               $arr =& $rs->GetArray();
-               //print_r($arr);
-               
-               $rs->Close();
-               $arr2 = array();
-               
-               if ($ttype) {
-                       $isview = strncmp($ttype,'V',1) === 0;
-               }
-               for ($i=0; $i < sizeof($arr); $i++) {
-               
-                       if (!$arr[$i][2]) continue;
-                       if (strncmp($arr[$i][1],'SYS',3) === 0) continue;
-                       
-                       $type = $arr[$i][3];
-                       
-                       if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2];
-                       
-                       if ($ttype) { 
-                               if ($isview) {
-                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
-                               } else if (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2];
-                       } else if (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2];
-               }
-               return $arr2;
-       }
-       
-       // 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;
-               $s = '';
-               
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       if ($s) $s .= '||';
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= "char(year($col))";
-                               break;
-                       case 'M':
-                               $s .= "substr(monthname($col),1,3)";
-                               break;
-                       case 'm':
-                               $s .= "right(digits(month($col)),2)";
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= "right(digits(day($col)),2)";
-                               break;
-                       case 'H':
-                       case 'h':
-                               if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";        
-                               else $s .= "''";
-                               break;
-                       case 'i':
-                       case 'I':
-                               if ($col != $this->sysDate)
-                                       $s .= "right(digits(minute($col)),2)";
-                                       else $s .= "''";
-                               break;
-                       case 'S':
-                       case 's':
-                               if ($col != $this->sysDate)
-                                       $s .= "right(digits(second($col)),2)";
-                               else $s .= "''";
-                               break;
-                       default:
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               $s .= $this->qstr($ch);
-                       }
-               }
-               return $s;
-       } 
-       
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)
-       {
-               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;
-       }
-       
-};
-
-class  ADORecordSet_db2 extends ADORecordSet_odbc {    
-       
-       var $databaseType = "db2";              
-       
-       function ADORecordSet_db2($id,$mode=false)
-       {
-               $this->ADORecordSet_odbc($id,$mode);
-       }
-
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               
-               switch (strtoupper($t)) {
-               case 'VARCHAR':
-               case 'CHAR':
-               case 'CHARACTER':
-                       if ($len <= $this->blobSize) return 'C';
-               
-               case 'LONGCHAR':
-               case 'TEXT':
-               case 'CLOB':
-               case 'DBCLOB': // double-byte
-                       return 'X';
-               
-               case 'BLOB':
-               case 'GRAPHIC':
-               case 'VARGRAPHIC':
-                       return 'B';
-                       
-               case 'DATE':
-                       return 'D';
-               
-               case 'TIME':
-               case 'TIMESTAMP':
-                       return 'T';
-               
-               //case 'BOOLEAN': 
-               //case 'BIT':
-               //      return 'L';
-                       
-               //case 'COUNTER':
-               //      return 'R';
-                       
-               case 'INT':
-               case 'INTEGER':
-               case 'BIGINT':
-               case 'SMALLINT':
-                       return 'I';
-                       
-               default: return 'N';
-               }
-       }
-}
-
-} //define
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  DB2 data driver. Requires ODBC.\r
\r
+From phpdb list:\r
+\r
+Hi Andrew,\r
+\r
+thanks a lot for your help. Today we discovered what\r
+our real problem was:\r
+\r
+After "playing" a little bit with the php-scripts that try\r
+to connect to the IBM DB2, we set the optional parameter\r
+Cursortype when calling odbc_pconnect(....).\r
+\r
+And the exciting thing: When we set the cursor type\r
+to SQL_CUR_USE_ODBC Cursor Type, then\r
+the whole query speed up from 1 till 10 seconds\r
+to 0.2 till 0.3 seconds for 100 records. Amazing!!!\r
+\r
+Therfore, PHP is just almost fast as calling the DB2\r
+from Servlets using JDBC (don't take too much care\r
+about the speed at whole: the database was on a\r
+completely other location, so the whole connection\r
+was made over a slow network connection).\r
+\r
+I hope this helps when other encounter the same\r
+problem when trying to connect to DB2 from\r
+PHP.\r
+\r
+Kind regards,\r
+Christian Szardenings\r
+\r
+2 Oct 2001\r
+Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by \r
+IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.\r
+\r
+From the IBM CLI Reference:\r
+\r
+SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) \r
+This connection attribute is defined by ODBC, but is not supported by DB2\r
+CLI. Any attempt to set or get this attribute will result in an SQLSTATE of\r
+HYC00 (Driver not capable). \r
+\r
+A 32-bit option specifying how the Driver Manager uses the ODBC cursor\r
+library. \r
+\r
+So I guess this means the message [above] was related to using a 3rd party\r
+odbc driver.\r
+\r
+Setting SQL_CUR_USE_ODBC\r
+========================\r
+To set SQL_CUR_USE_ODBC for drivers that require it, do this:\r
+\r
+$db = NewADOConnection('db2');\r
+$db->curMode = SQL_CUR_USE_ODBC;\r
+$db->Connect($dsn, $userid, $pwd);\r
+\r
+\r
+\r
+USING CLI INTERFACE\r
+===================\r
+\r
+I have had reports that the $host and $database params have to be reversed in \r
+Connect() when using the CLI interface. From Halmai Csongor csongor.halmai#nexum.hu:\r
+\r
+> The symptom is that if I change the database engine from postgres or any other to DB2 then the following\r
+> connection command becomes wrong despite being described this version to be correct in the docs. \r
+>\r
+> $connection_object->Connect( $DATABASE_HOST, $DATABASE_AUTH_USER_NAME, $DATABASE_AUTH_PASSWORD, $DATABASE_NAME )\r
+>\r
+> In case of DB2 I had to swap the first and last arguments in order to connect properly. \r
+\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+if (!defined('ADODB_DB2')){\r
+define('ADODB_DB2',1);\r
+\r
+class ADODB_DB2 extends ADODB_odbc {\r
+       var $databaseType = "db2";      \r
+       var $concat_operator = '||';\r
+       var $sysDate = 'CURRENT_DATE';\r
+       var $sysTimeStamp = 'CURRENT TIMESTAMP';\r
+       // The complete string representation of a timestamp has the form \r
+       // yyyy-mm-dd-hh.mm.ss.nnnnnn.\r
+       var $fmtTimeStamp = "'Y-m-d-H.i.s'";\r
+       var $ansiOuter = true;\r
+       var $identitySQL = 'values IDENTITY_VAL_LOCAL()';\r
+       var $_bindInputArray = false;\r
+       var $upperCase = 'upper';\r
+       \r
+       \r
+       function ADODB_DB2()\r
+       {\r
+               if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;\r
+               $this->ADODB_odbc();\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " COALESCE($field, $ifNull) "; // if DB2 UDB\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/);\r
+               $vers = $this->GetOne('select versionnumber from sysibm.sysversions');\r
+               //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/);\r
+               return array('description'=>'DB2 ODBC driver', 'version'=>$vers);\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+               return $this->GetOne($this->identitySQL);\r
+       }\r
+       \r
+       function RowLock($tables,$where)\r
+       {\r
+               if ($this->_autocommit) $this->BeginTrans();\r
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
+       }\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $qid = odbc_tables($this->_connectionID);\r
+               \r
+               $rs = new ADORecordSet_odbc($qid);\r
+               \r
+               $ADODB_FETCH_MODE = $savem;\r
+               if (!$rs) return false;\r
+               \r
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+               \r
+               $arr =& $rs->GetArray();\r
+               //print_r($arr);\r
+               \r
+               $rs->Close();\r
+               $arr2 = array();\r
+               \r
+               if ($ttype) {\r
+                       $isview = strncmp($ttype,'V',1) === 0;\r
+               }\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+               \r
+                       if (!$arr[$i][2]) continue;\r
+                       if (strncmp($arr[$i][1],'SYS',3) === 0) continue;\r
+                       \r
+                       $type = $arr[$i][3];\r
+                       \r
+                       if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2];\r
+                       \r
+                       if ($ttype) { \r
+                               if ($isview) {\r
+                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];\r
+                               } else if (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2];\r
+                       } else if (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+       // use right() and replace() ?\r
+               if (!$col) $col = $this->sysDate;\r
+               $s = '';\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       if ($s) $s .= '||';\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= "char(year($col))";\r
+                               break;\r
+                       case 'M':\r
+                               $s .= "substr(monthname($col),1,3)";\r
+                               break;\r
+                       case 'm':\r
+                               $s .= "right(digits(month($col)),2)";\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= "right(digits(day($col)),2)";\r
+                               break;\r
+                       case 'H':\r
+                       case 'h':\r
+                               if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";        \r
+                               else $s .= "''";\r
+                               break;\r
+                       case 'i':\r
+                       case 'I':\r
+                               if ($col != $this->sysDate)\r
+                                       $s .= "right(digits(minute($col)),2)";\r
+                                       else $s .= "''";\r
+                               break;\r
+                       case 'S':\r
+                       case 's':\r
+                               if ($col != $this->sysDate)\r
+                                       $s .= "right(digits(second($col)),2)";\r
+                               else $s .= "''";\r
+                               break;\r
+                       default:\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $this->qstr($ch);\r
+                       }\r
+               }\r
+               return $s;\r
+       } \r
\r
+       \r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)\r
+       {\r
+               if ($offset <= 0) {\r
+               // could also use " OPTIMIZE FOR $nrows ROWS "\r
+                       if ($nrows >= 0) $sql .=  " FETCH FIRST $nrows ROWS ONLY ";\r
+                       $rs =& $this->Execute($sql,$inputArr);\r
+               } else {\r
+                       if ($offset > 0 && $nrows < 0);\r
+                       else {\r
+                               $nrows += $offset;\r
+                               $sql .=  " FETCH FIRST $nrows ROWS ONLY ";\r
+                       }\r
+                       $rs =& ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);\r
+               }\r
+               \r
+               return $rs;\r
+       }\r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_db2 extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = "db2";              \r
+       \r
+       function ADORecordSet_db2($id,$mode=false)\r
+       {\r
+               $this->ADORecordSet_odbc($id,$mode);\r
+       }\r
+\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'CHAR':\r
+               case 'CHARACTER':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               \r
+               case 'LONGCHAR':\r
+               case 'TEXT':\r
+               case 'CLOB':\r
+               case 'DBCLOB': // double-byte\r
+                       return 'X';\r
+               \r
+               case 'BLOB':\r
+               case 'GRAPHIC':\r
+               case 'VARGRAPHIC':\r
+                       return 'B';\r
+                       \r
+               case 'DATE':\r
+                       return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'TIMESTAMP':\r
+                       return 'T';\r
+               \r
+               //case 'BOOLEAN': \r
+               //case 'BIT':\r
+               //      return 'L';\r
+                       \r
+               //case 'COUNTER':\r
+               //      return 'R';\r
+                       \r
+               case 'INT':\r
+               case 'INTEGER':\r
+               case 'BIGINT':\r
+               case 'SMALLINT':\r
+                       return 'I';\r
+                       \r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
+\r
+} //define\r
 ?>
\ No newline at end of file
index 4221070cd2e046e2601cad977c1e961557967ec4..308ebca3a4b7cda40e828facdddab6c3f848ba30 100644 (file)
-<?php
-/*
- @version V4.20 22 Feb 2004 (c) 2000-2004 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. 
- Contribution by Frank M. Kromann <frank@frontbase.com>. 
-  Set tabs to 8.
-*/ 
-
-if (! defined("_ADODB_FBSQL_LAYER")) {
- define("_ADODB_FBSQL_LAYER", 1 );
-
-class ADODB_fbsql extends ADOConnection {
-       var $databaseType = 'fbsql';
-       var $hasInsertID = true;
-       var $hasAffectedRows = true;    
-       var $metaTablesSQL = "SHOW TABLES";     
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       var $hasLimit = false;
-       
-       function ADODB_fbsql() 
-       {                       
-       }
-       
-       function _insertid()
-       {
-                       return fbsql_insert_id($this->_connectionID);
-       }
-       
-       function _affectedrows()
-       {
-                       return fbsql_affected_rows($this->_connectionID);
-       }
-  
-       function &MetaDatabases()
-       {
-               $qid = fbsql_list_dbs($this->_connectionID);
-               $arr = array();
-               $i = 0;
-               $max = fbsql_num_rows($qid);
-               while ($i < $max) {
-                       $arr[] = fbsql_tablename($qid,$i);
-                       $i += 1;
-               }
-               return $arr;
-       }
-
-       // returns concatenated string
-       function Concat()
-       {
-               $s = "";
-               $arr = func_get_args();
-               $first = true;
-
-               $s = implode(',',$arr);
-               if (sizeof($arr) > 0) return "CONCAT($s)";
-               else return '';
-       }
-       
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               $this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       function &MetaColumns($table) 
-       {
-               if ($this->metaColumnsSQL) {
-                       
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
-                       
-                       if ($rs === false) return false;
-                       
-                       $retarr = array();
-                       while (!$rs->EOF){
-                               $fld = new ADOFieldObject();
-                               $fld->name = $rs->fields[0];
-                               $fld->type = $rs->fields[1];
-                                       
-                               // split type into type(length):
-                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {
-                                       $fld->type = $query_array[1];
-                                       $fld->max_length = $query_array[2];
-                               } else {
-                                       $fld->max_length = -1;
-                               }
-                               $fld->not_null = ($rs->fields[2] != 'YES');
-                               $fld->primary_key = ($rs->fields[3] == 'PRI');
-                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
-                               $fld->binary = (strpos($fld->type,'blob') !== false);
-                               
-                               $retarr[strtoupper($fld->name)] = $fld; 
-                               $rs->MoveNext();
-                       }
-                       $rs->Close();
-                       return $retarr; 
-               }
-               return false;
-       }
-               
-       // returns true or false
-       function SelectDB($dbName) 
-       {
-               $this->databaseName = $dbName;
-               if ($this->_connectionID) {
-                       return @fbsql_select_db($dbName,$this->_connectionID);          
-               }
-               else return false;      
-       }
-       
-       
-       // returns queryID or false
-       function _query($sql,$inputarr)
-       {
-               return fbsql_query("$sql;",$this->_connectionID);
-       }
-
-       /*      Returns: the last error message from previous database operation        */      
-       function ErrorMsg() 
-       {
-               $this->_errorMsg = @fbsql_error($this->_connectionID);
-                       return $this->_errorMsg;
-       }
-       
-       /*      Returns: the last error number from previous database operation */      
-       function ErrorNo() 
-       {
-               return @fbsql_errno($this->_connectionID);
-       }
-       
-       // returns true or false
-       function _close()
-       {
-               return @fbsql_close($this->_connectionID);
-       }
-               
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_fbsql extends ADORecordSet{ 
-       
-       var $databaseType = "fbsql";
-       var $canSeek = true;
-       
-       function ADORecordSet_fbsql($queryID,$mode=false) 
-       {
-               if (!$mode) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               switch ($mode) {
-               case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
-               default:
-               case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;
-               case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
-               }
-               return $this->ADORecordSet($queryID);
-       }
-       
-       function _initrs()
-       {
-       GLOBAL $ADODB_COUNTRECS;
-               $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;
-               $this->_numOfFields = @fbsql_num_fields($this->_queryID);
-       }
-       
-
-
-       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
-                       $f = @fbsql_field_flags($this->_queryID,$fieldOffset);
-                       $o->binary = (strpos($f,'binary')!== false);
-               }
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
-                       $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable
-                       //$o->max_length = -1;
-               }
-               
-               return $o;
-       }
-               
-       function _seek($row)
-       {
-               return @fbsql_data_seek($this->_queryID,$row);
-       }
-       
-       function _fetch($ignore_fields=false)
-       {
-               $this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);
-               return ($this->fields == true);
-       }
-       
-       function _close() {
-               return @fbsql_free_result($this->_queryID);             
-       }
-       
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               $len = -1; // fbsql max_length is not accurate
-               switch (strtoupper($t)) {
-               case 'CHARACTER':
-               case 'CHARACTER VARYING': 
-               case 'BLOB': 
-               case 'CLOB': 
-               case 'BIT': 
-               case 'BIT VARYING': 
-                       if ($len <= $this->blobSize) return 'C';
-                       
-               // so we have to check whether binary...
-               case 'IMAGE':
-               case 'LONGBLOB': 
-               case 'BLOB':
-               case 'MEDIUMBLOB':
-                       return !empty($fieldobj->binary) ? 'B' : 'X';
-                       
-               case 'DATE': return 'D';
-               
-               case 'TIME':
-               case 'TIME WITH TIME ZONE':
-               case 'TIMESTAMP': 
-               case 'TIMESTAMP WITH TIME ZONE': return 'T';
-               
-               case 'PRIMARY_KEY':
-                       return 'R';
-               case 'INTEGER':
-               case 'SMALLINT': 
-               case 'BOOLEAN':
-                       
-                       if (!empty($fieldobj->primary_key)) return 'R';
-                       else return 'I';
-               
-               default: return 'N';
-               }
-       }
-
-} //class
-} // defined
+<?php\r
+/*\r
+ @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ Contribution by Frank M. Kromann <frank@frontbase.com>. \r
+  Set tabs to 8.\r
+*/ \r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (! defined("_ADODB_FBSQL_LAYER")) {\r
+ define("_ADODB_FBSQL_LAYER", 1 );\r
+\r
+class ADODB_fbsql extends ADOConnection {\r
+       var $databaseType = 'fbsql';\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;    \r
+       var $metaTablesSQL = "SHOW TABLES";     \r
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasLimit = false;\r
+       \r
+       function ADODB_fbsql() \r
+       {                       \r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+                       return fbsql_insert_id($this->_connectionID);\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+                       return fbsql_affected_rows($this->_connectionID);\r
+       }\r
+  \r
+       function &MetaDatabases()\r
+       {\r
+               $qid = fbsql_list_dbs($this->_connectionID);\r
+               $arr = array();\r
+               $i = 0;\r
+               $max = fbsql_num_rows($qid);\r
+               while ($i < $max) {\r
+                       $arr[] = fbsql_tablename($qid,$i);\r
+                       $i += 1;\r
+               }\r
+               return $arr;\r
+       }\r
+\r
+       // returns concatenated string\r
+       function Concat()\r
+       {\r
+               $s = "";\r
+               $arr = func_get_args();\r
+               $first = true;\r
+\r
+               $s = implode(',',$arr);\r
+               if (sizeof($arr) > 0) return "CONCAT($s)";\r
+               else return '';\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               if ($this->metaColumnsSQL) {\r
+                       \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
+                       \r
+                       if ($rs === false) return false;\r
+                       \r
+                       $retarr = array();\r
+                       while (!$rs->EOF){\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                                       \r
+                               // split type into type(length):\r
+                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = $query_array[2];\r
+                               } else {\r
+                                       $fld->max_length = -1;\r
+                               }\r
+                               $fld->not_null = ($rs->fields[2] != 'YES');\r
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
+                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                               \r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+               \r
+       // returns true or false\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @fbsql_select_db($dbName,$this->_connectionID);          \r
+               }\r
+               else return false;      \r
+       }\r
+       \r
+       \r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               return fbsql_query("$sql;",$this->_connectionID);\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               $this->_errorMsg = @fbsql_error($this->_connectionID);\r
+                       return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+               return @fbsql_errno($this->_connectionID);\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return @fbsql_close($this->_connectionID);\r
+       }\r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_fbsql extends ADORecordSet{ \r
+       \r
+       var $databaseType = "fbsql";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_fbsql($queryID,$mode=false) \r
+       {\r
+               if (!$mode) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode) {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;\r
+               default:\r
+               case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;\r
+               case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;\r
+               }\r
+               return $this->ADORecordSet($queryID);\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       GLOBAL $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @fbsql_num_fields($this->_queryID);\r
+       }\r
+       \r
+\r
+\r
+       function &FetchField($fieldOffset = -1) {\r
+               if ($fieldOffset != -1) {\r
+                       $o =  @fbsql_fetch_field($this->_queryID, $fieldOffset);\r
+                       //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable\r
+                       $f = @fbsql_field_flags($this->_queryID,$fieldOffset);\r
+                       $o->binary = (strpos($f,'binary')!== false);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable\r
+                       //$o->max_length = -1;\r
+               }\r
+               \r
+               return $o;\r
+       }\r
+               \r
+       function _seek($row)\r
+       {\r
+               return @fbsql_data_seek($this->_queryID,$row);\r
+       }\r
+       \r
+       function _fetch($ignore_fields=false)\r
+       {\r
+               $this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);\r
+               return ($this->fields == true);\r
+       }\r
+       \r
+       function _close() {\r
+               return @fbsql_free_result($this->_queryID);             \r
+       }\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               $len = -1; // fbsql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+               case 'CHARACTER':\r
+               case 'CHARACTER VARYING': \r
+               case 'BLOB': \r
+               case 'CLOB': \r
+               case 'BIT': \r
+               case 'BIT VARYING': \r
+                       if ($len <= $this->blobSize) return 'C';\r
+                       \r
+               // so we have to check whether binary...\r
+               case 'IMAGE':\r
+               case 'LONGBLOB': \r
+               case 'BLOB':\r
+               case 'MEDIUMBLOB':\r
+                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
+                       \r
+               case 'DATE': return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'TIME WITH TIME ZONE':\r
+               case 'TIMESTAMP': \r
+               case 'TIMESTAMP WITH TIME ZONE': return 'T';\r
+               \r
+               case 'PRIMARY_KEY':\r
+                       return 'R';\r
+               case 'INTEGER':\r
+               case 'SMALLINT': \r
+               case 'BOOLEAN':\r
+                       \r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       else return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+} //class\r
+} // defined\r
 ?>
\ No newline at end of file
index b5f10be2d68ae0b933fa4210e720fa5a2b796e23..f622263cec403338bf634858b28b82bc0a8a0fbe 100644 (file)
@@ -1,69 +1,75 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-
-*/
-
-
-include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
-
-class ADODB_firebird extends ADODB_ibase {
-       var $databaseType = "firebird"; 
-       function ADODB_firebird()
-       {       
-               $this->ADODB_ibase();
-       }
-       
-       function ServerInfo()
-       {
-               $arr['dialect'] = $this->dialect;
-               switch($arr['dialect']) {
-               case '': 
-               case '1': $s = 'Firebird Dialect 1'; break;
-               case '2': $s = 'Firebird Dialect 2'; break;
-               default:
-               case '3': $s = 'Firebird Dialect 3'; break;
-               }
-               $arr['version'] = ADOConnection::_findvers($s);
-               $arr['description'] = $s;
-               return $arr;
-       }
-       
-       // 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)
-       {
-               $str = 'SELECT ';
-               if ($nrows >= 0) $str .= "FIRST $nrows "; 
-               $str .=($offset>=0) ? "SKIP $offset " : '';
-               
-               $sql = preg_replace('/^[ \t]*select/i',$str,$sql); 
-               if ($secs)
-                       $rs =& $this->CacheExecute($secs,$sql,$inputarr);
-               else
-                       $rs =& $this->Execute($sql,$inputarr);
-                       
-               return $rs;
-       }
-       
-       
-};
-
-class  ADORecordSet_firebird extends ADORecordSet_ibase {      
-       
-       var $databaseType = "firebird";         
-       
-       function ADORecordSet_firebird($id,$mode=false)
-       {
-               $this->ADORecordSet_ibase($id,$mode);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");\r
+\r
+class ADODB_firebird extends ADODB_ibase {\r
+       var $databaseType = "firebird"; \r
+       var $dialect = 3;\r
+       \r
+       var $sysTimeStamp = "cast('NOW' as timestamp)";\r
+       \r
+       function ADODB_firebird()\r
+       {       \r
+               $this->ADODB_ibase();\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['dialect'] = $this->dialect;\r
+               switch($arr['dialect']) {\r
+               case '': \r
+               case '1': $s = 'Firebird Dialect 1'; break;\r
+               case '2': $s = 'Firebird Dialect 2'; break;\r
+               default:\r
+               case '3': $s = 'Firebird Dialect 3'; break;\r
+               }\r
+               $arr['version'] = ADOConnection::_findvers($s);\r
+               $arr['description'] = $s;\r
+               return $arr;\r
+       }\r
+       \r
+       // Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!\r
+       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows \r
+       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)\r
+       {\r
+               $str = 'SELECT ';\r
+               if ($nrows >= 0) $str .= "FIRST $nrows "; \r
+               $str .=($offset>=0) ? "SKIP $offset " : '';\r
+               \r
+               $sql = preg_replace('/^[ \t]*select/i',$str,$sql); \r
+               if ($secs)\r
+                       $rs =& $this->CacheExecute($secs,$sql,$inputarr);\r
+               else\r
+                       $rs =& $this->Execute($sql,$inputarr);\r
+                       \r
+               return $rs;\r
+       }\r
+       \r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_firebird extends ADORecordSet_ibase {      \r
+       \r
+       var $databaseType = "firebird";         \r
+       \r
+       function ADORecordSet_firebird($id,$mode=false)\r
+       {\r
+               $this->ADORecordSet_ibase($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index e9e7c94eea73caae2efc080e58a93ddcdb0a36b3..f0b52a6f89360854d87d5ddc7d9dc5575b4adf2c 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-  Latest version is available at http://php.weblogs.com/
-  
-  Interbase data driver. Requires interbase client. Works on Windows and Unix.
-
-  3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>
-       changed transaction handling and added experimental blob stuff
-  
-  Docs to interbase at the website
-   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html
-   
-  To use gen_id(), see
-   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen
-   
-   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');
-   $id = $rs->fields[0];
-   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");
-*/
-
-
-class ADODB_ibase extends ADOConnection {
-       var $databaseType = "ibase";
-       var $dataProvider = "ibase";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d, H:i:s'";
-       var $concat_operator='||';
-       var $_transactionID;
-       var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
-       //OPN STUFF start
-       var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";
-       //OPN STUFF end
-       var $ibasetrans;
-       var $hasGenID = true;
-       var $_bindInputArray = true;
-       var $buffers = 0;
-       var $dialect = 1;
-       var $sysDate = "cast('TODAY' as date)";
-       var $sysTimeStamp = "cast('NOW' as timestamp)";
-       var $ansiOuter = true;
-       var $hasAffectedRows = false;
-       var $poorAffectedRows = true;
-       var $blobEncodeType = 'C';
-       
-       function ADODB_ibase() 
-       {
-                if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
-       }
-       
-       function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
-       {       
-               if ($internalKey) return array('RDB$DB_KEY');
-               
-               $table = strtoupper($table);
-               
-               $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
-       FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME  
-       WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
-       ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
-
-               $a = $this->GetCol($sql,false,true);
-               if ($a && sizeof($a)>0) return $a;
-               return false;     
-       }
-       
-       function ServerInfo()
-       {
-               $arr['dialect'] = $this->dialect;
-               switch($arr['dialect']) {
-               case '': 
-               case '1': $s = 'Interbase 5.5 or earlier'; break;
-               case '2': $s = 'Interbase 5.6'; break;
-               default:
-               case '3': $s = 'Interbase 6.0'; break;
-               }
-               $arr['version'] = ADOConnection::_findvers($s);
-               $arr['description'] = $s;
-               return $arr;
-       }
-
-       function BeginTrans()
-       {        
-               if ($this->transOff) return true;
-               $this->transCnt += 1;
-               $this->autoCommit = false;
-               $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
-               return $this->_transactionID;
-       }
-       
-       function CommitTrans($ok=true) 
-       { 
-               if (!$ok) return $this->RollbackTrans();
-               if ($this->transOff) return true;
-               if ($this->transCnt) $this->transCnt -= 1;
-               $ret = false;
-               $this->autoCommit = true;
-               if ($this->_transactionID) {
-                                       //print ' commit ';
-                       $ret = ibase_commit($this->_transactionID);
-               }
-               $this->_transactionID = false;
-               return $ret;
-       }
-       
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true;
-               if ($this->transCnt) $this->transCnt -= 1;
-               $ret = false;
-               $this->autoCommit = true;
-               if ($this->_transactionID) 
-                                 $ret = ibase_rollback($this->_transactionID);
-               $this->_transactionID = false;   
-               
-               return $ret;
-       }
-       
-       function &MetaIndexes ($table, $primary = FALSE, $owner=false)
-       {
-        // save old fetch mode
-        global $ADODB_FETCH_MODE;
-        
-        $save = $ADODB_FETCH_MODE;
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-        if ($this->fetchMode !== FALSE) {
-               $savem = $this->SetFetchMode(FALSE);
-        }
-        $table = strtoupper($table);
-        $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
-        if (!$primary) {
-               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
-        } else {
-               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
-        }
-        // get index details
-        $rs = $this->Execute($sql);
-        if (!is_object($rs)) {
-               // restore fetchmode
-               if (isset($savem)) {
-                   $this->SetFetchMode($savem);
-               }
-               $ADODB_FETCH_MODE = $save;
-            return FALSE;
-        }
-        
-        $indexes = array ();
-               while ($row = $rs->FetchRow()) {
-                       $index = $row[0];
-             if (!isset($indexes[$index])) {
-                       if (is_null($row[3])) {$row[3] = 0;}
-                     $indexes[$index] = array(
-                             'unique' => ($row[3] == 1),
-                             'columns' => array()
-                     );
-             }
-                       $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";
-                       $rs1 = $this->Execute($sql);
-            while ($row1 = $rs1->FetchRow()) {
-               $indexes[$index]['columns'][$row1[2]] = $row1[1];
-               }
-               }
-        // restore fetchmode
-        if (isset($savem)) {
-            $this->SetFetchMode($savem);
-        }
-        $ADODB_FETCH_MODE = $save;
-        
-        return $indexes;
-       }
-
-       
-       // See http://community.borland.com/article/0,1410,25844,00.html
-       function RowLock($tables,$where,$col)
-       {
-               if ($this->autoCommit) $this->BeginTrans();
-               $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
-               return 1;
-       }
-       
-       
-       function CreateSequence($seqname,$startID=1)
-       {
-               $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
-               if (!$ok) return false;
-               return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
-       }
-       
-       function DropSequence($seqname)
-       {
-               $seqname = strtoupper($seqname);
-               $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
-       }
-       
-       function GenID($seqname='adodbseq',$startID=1)
-       {
-               $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
-               $rs = @$this->Execute($getnext);
-               if (!$rs) {
-                       $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
-                       $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
-                       $rs = $this->Execute($getnext);
-               }
-               if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
-               else $this->genID = 0; // false
-               
-               if ($rs) $rs->Close();
-               
-               return $this->genID;
-       }
-
-       function SelectDB($dbName) 
-       {
-                  return false;
-       }
-
-       function _handleerror()
-       {
-               $this->_errorMsg = ibase_errmsg();
-       }
-
-       function ErrorNo() 
-       {
-               if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
-               else return 0;
-       }
-
-       function ErrorMsg() 
-       {
-                       return $this->_errorMsg;
-       }
-
-          // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {  
-               if (!function_exists('ibase_pconnect')) return false;
-               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
-               $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
-               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
-                       $this->replaceQuote = "''";
-               }
-               if ($this->_connectionID === false) {
-                       $this->_handleerror();
-                       return false;
-               }
-               
-               ibase_timefmt($this->ibase_timefmt);    
-               return true;
-       }
-          // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('ibase_pconnect')) return false;
-               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
-               $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
-               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
-                       $this->replaceQuote = "''";
-               }
-               if ($this->_connectionID === false) {
-                       $this->_handleerror();
-                       return false;
-               }
-               
-               ibase_timefmt($this->ibase_timefmt);
-               return true;
-       }       
-       
-       function Prepare($sql)
-       {
-               $stmt = ibase_prepare($this->_connectionID,$sql);
-               if (!$stmt) return false;
-               return array($sql,$stmt);
-       }
-
-          // returns query ID if successful, otherwise false
-          // there have been reports of problems with nested queries - the code is probably not re-entrant?
-       function _query($sql,$iarr=false)
-       { 
-
-               if (!$this->autoCommit && $this->_transactionID) {
-                       $conn = $this->_transactionID;
-                       $docommit = false;
-               } else {
-                       $conn = $this->_connectionID;
-                       $docommit = true;
-               }
-               if (is_array($sql)) {
-                       $fn = 'ibase_execute';
-                       $sql = $sql[1];
-                       
-                       if (is_array($iarr)) {  
-                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
-                                       $fnarr =& array_merge( array($sql) , $iarr);
-                                       $ret = call_user_func_array($fn,$fnarr);
-                               } else {
-                                       switch(sizeof($iarr)) {
-                                       case 1: $ret = $fn($sql,$iarr[0]); break;
-                                       case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
-                                       case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
-                                       case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
-                                       case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
-                                       case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
-                                       case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
-                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");
-                                       case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
-                                       }
-                               }
-                       } else $ret = $fn($sql); 
-               } else {
-                       $fn = 'ibase_query';
-               
-                       if (is_array($iarr)) {  
-                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
-                                       $fnarr =& array_merge( array($conn,$sql) , $iarr);
-                                       $ret = call_user_func_array($fn,$fnarr);
-                               } else {
-                                       switch(sizeof($iarr)) {
-                                       case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
-                                       case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
-                                       case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
-                                       case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
-                                       case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
-                                       case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
-                                       case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
-                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");
-                                       case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
-                                       }
-                               }
-                       } else $ret = $fn($conn,$sql); 
-               }
-               if ($docommit && $ret === true) ibase_commit($this->_connectionID);
-
-               $this->_handleerror();
-               return $ret;
-       }
-
-        // returns true or false
-        function _close()
-        {         
-               if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
-               return @ibase_close($this->_connectionID);
-        }
-       
-       //OPN STUFF start
-       function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)
-       {
-               $fscale = abs($fscale);
-               $fld->max_length = $flen;
-               $fld->scale = null;
-               switch($ftype){
-                       case 7: 
-                       case 8:
-                               if ($isInterbase6) {
-                                   switch($fsubtype){
-                                       case 0: 
-                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
-                                               break;
-                                       case 1: 
-                                               $fld->type = 'numeric';
-                                                       $fld->max_length = $fprecision;
-                                                       $fld->scale = $fscale;
-                                               break;
-                                       case 2:
-                                               $fld->type = 'decimal';
-                                                       $fld->max_length = $fprecision;
-                                                       $fld->scale = $fscale;
-                                               break;
-                                   } // switch
-                               } else {
-                                       if ($fscale !=0) {
-                                           $fld->type = 'decimal';
-                                               $fld->scale = $fscale;
-                                               $fld->max_length = ($ftype == 7 ? 4 : 9);
-                                       } else {
-                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
-                                       }
-                               }
-                               break;
-                       case 16: 
-                               if ($isInterbase6) {
-                                   switch($fsubtype){
-                                       case 0: 
-                                               $fld->type = 'decimal';
-                                                       $fld->max_length = 18;
-                                                       $fld->scale = 0;
-                                               break;
-                                       case 1: 
-                                               $fld->type = 'numeric';
-                                                       $fld->max_length = $fprecision;
-                                                       $fld->scale = $fscale;
-                                               break;
-                                       case 2:
-                                               $fld->type = 'decimal';
-                                                       $fld->max_length = $fprecision;
-                                                       $fld->scale = $fscale;
-                                               break;
-                                   } // switch
-                               }
-                               break;
-                       case 10:
-                               $fld->type = 'float';
-                               break;
-                       case 14:
-                               $fld->type = 'char';
-                               break;
-                       case 27:
-                               if ($fscale !=0) {
-                                   $fld->type = 'decimal';
-                                       $fld->max_length = 15;
-                                       $fld->scale = 5;
-                               } else {
-                                       $fld->type = 'double';
-                               }
-                               break;
-                       case 35:
-                               if ($isInterbase6) {
-                                   $fld->type = 'timestamp';
-                               } else {
-                                       $fld->type = 'date';
-                               }
-                               break;
-                       case 12:
-                       case 13:
-                               $fld->type = 'date';
-                               break;
-                       case 37:
-                               $fld->type = 'varchar';
-                               break;
-                       case 40:
-                               $fld->type = 'cstring';
-                               break;
-                       case 261:
-                               $fld->type = 'blob';
-                               $fld->max_length = -1;
-                               break;
-               } // switch
-       }
-       //OPN STUFF end
-               // returns array of ADOFieldObjects for current table
-       function &MetaColumns($table) 
-       {
-       global $ADODB_FETCH_MODE;
-               
-               if ($this->metaColumnsSQL) {
-               
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
-               
-                       $ADODB_FETCH_MODE = $save;
-                       if ($rs === false) return false;
-
-                       $retarr = array();
-                       //OPN STUFF start
-                       $isInterbase6 = ($this->dialect==3 ? true : false);
-                       //OPN STUFF end
-                       while (!$rs->EOF) { //print_r($rs->fields);
-                               $fld = new ADOFieldObject();
-                               $fld->name = trim($rs->fields[0]);
-                               //OPN STUFF start
-                               $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);
-                               if (isset($rs->fields[1]) && $rs->fields[1]) {
-                                       $fld->not_null = true;
-                               }                               
-                               if (isset($rs->fields[2])) {
-                                       
-                                       $fld->has_default = true;
-                                       $d = substr($rs->fields[2],strlen('default '));
-                                       switch ($fld->type)
-                                       {
-                                       case 'smallint':
-                                       case 'integer': $fld->default_value = (int) $d; break;
-                                       case 'char': 
-                                       case 'blob':
-                                       case 'text':
-                                       case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
-                                       case 'double':
-                                       case 'float': $fld->default_value = (float) $d; break;
-                                       default: $fld->default_value = $d; break;
-                                       }
-                       //      case 35:$tt = 'TIMESTAMP'; break;
-                               }
-                               if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
-                                       $fld->sub_type = $rs->fields[5];
-                               } else {
-                                       $fld->sub_type = null;
-                               }
-                               //OPN STUFF end
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
-                               else $retarr[strtoupper($fld->name)] = $fld;
-                               
-                               $rs->MoveNext();
-                       }
-                       $rs->Close();
-                       return $retarr; 
-               }
-               return false;
-       }
-       
-       function BlobEncode( $blob ) 
-       {
-               $blobid = ibase_blob_create( $this->_connectionID);
-               ibase_blob_add( $blobid, $blob );
-               return ibase_blob_close( $blobid );
-       }
-       
-       // since we auto-decode all blob's since 2.42, 
-       // BlobDecode should not do any transforms
-       function BlobDecode($blob)
-       {
-               return $blob; 
-       }
-       
-       
-       
-       
-       // old blobdecode function
-       // still used to auto-decode all blob's
-       function _BlobDecode( $blob ) 
-       {
-               $blobid = ibase_blob_open( $blob );
-               $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
-               while($string = ibase_blob_get($blobid, 8192)){ 
-                       $realblob .= $string; 
-               }
-               ibase_blob_close( $blobid );
-
-               return( $realblob );
-       } 
-       
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
-       { 
-               $fd = fopen($path,'rb'); 
-               if ($fd === false) return false; 
-               $blob_id = ibase_blob_create($this->_connectionID); 
-               
-               /* fill with data */ 
-               
-               while ($val = fread($fd,32768)){ 
-                       ibase_blob_add($blob_id, $val); 
-               } 
-               
-               /* close and get $blob_id_str for inserting into table */ 
-               $blob_id_str = ibase_blob_close($blob_id); 
-               
-               fclose($fd); 
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
-       } 
-       
-       /*
-               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') 
-       { 
-       $blob_id = ibase_blob_create($this->_connectionID); 
-       
-       // ibase_blob_add($blob_id, $val); 
-       
-       // replacement that solves the problem by which only the first modulus 64K / 
-       // of $val are stored at the blob field //////////////////////////////////// 
-       // Thx Abel Berenstein  aberenstein#afip.gov.ar
-       $len = strlen($val); 
-       $chunk_size = 32768; 
-       $tail_size = $len % $chunk_size; 
-       $n_chunks = ($len - $tail_size) / $chunk_size; 
-       
-       for ($n = 0; $n < $n_chunks; $n++) { 
-               $start = $n * $chunk_size; 
-               $data = substr($val, $start, $chunk_size); 
-               ibase_blob_add($blob_id, $data); 
-       } 
-       
-       if ($tail_size) {
-               $start = $n_chunks * $chunk_size; 
-               $data = substr($val, $start, $tail_size); 
-               ibase_blob_add($blob_id, $data); 
-       }
-       // end replacement ///////////////////////////////////////////////////////// 
-       
-       $blob_id_str = ibase_blob_close($blob_id); 
-       
-       return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
-       
-       } 
-       
-       
-       function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
-       {
-               $blob_id = ibase_blob_create($this->_connectionID);
-               ibase_blob_add($blob_id, $val);
-               $blob_id_str = ibase_blob_close($blob_id);
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
-       }
-       
-       // Format date column in sql string given an input format that understands Y M D
-       // Only since Interbase 6.0 - uses EXTRACT
-       // problem - does not zero-fill the day and month yet
-       function SQLDate($fmt, $col=false)
-       {       
-               if (!$col) $col = $this->sysDate;
-               $s = '';
-               
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       if ($s) $s .= '||';
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= "extract(year from $col)";
-                               break;
-                       case 'M':
-                       case 'm':
-                               $s .= "extract(month from $col)";
-                               break;
-                       case 'Q':
-                       case 'q':
-                               $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= "(extract(day from $col))";
-                               break;
-                       case 'H':
-                       case 'h':
-                         $s .= "(extract(hour from $col))";
-                         break;                        
-                       case 'I':
-                       case 'i':
-                         $s .= "(extract(minute from $col))";
-                         break;                
-                       case 'S':
-                       case 's':
-                         $s .= "CAST((extract(second from $col)) AS INTEGER)";
-                         break;        
-
-                       default:
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               $s .= $this->qstr($ch);
-                               break;
-                       }
-               }
-               return $s;
-       }
-}
-
-/*--------------------------------------------------------------------------------------
-                Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_ibase extends ADORecordSet 
-{
-
-       var $databaseType = "ibase";
-       var $bind=false;
-       var $_cacheType;
-       
-       function ADORecordset_ibase($id,$mode=false)
-       {
-       global $ADODB_FETCH_MODE;
-       
-                       $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
-                       return $this->ADORecordSet($id);
-       }
-
-       /*              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)
-       {
-                        $fld = new ADOFieldObject;
-                        $ibf = ibase_field_info($this->_queryID,$fieldOffset);
-                        $fld->name = strtolower($ibf['alias']);
-                        if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
-                        $fld->type = $ibf['type'];
-                        $fld->max_length = $ibf['length'];
-                        return $fld;
-       }
-
-       function _initrs()
-       {
-                       $this->_numOfRows = -1;
-                       $this->_numOfFields = @ibase_num_fields($this->_queryID);
-                       
-                       // cache types for blob decode check
-                       for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
-                               $f1 = $this->FetchField($i); 
-                               $this->_cacheType[] = $f1->type;
-                       }                               
-       }
-
-       function _seek($row)
-       {
-               return false;
-       }
-
-       
-       
-       function _fetch() 
-       {
-               $f = @ibase_fetch_row($this->_queryID); 
-               if ($f === false) {
-                       $this->fields = false;
-                       return false;
-               }
-               // OPN stuff start - optimized
-               // fix missing nulls and decode blobs automatically
-       
-               global $ADODB_ANSI_PADDING_OFF;
-               //$ADODB_ANSI_PADDING_OFF=1;
-               $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
-               
-               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
-                       if ($this->_cacheType[$i]=="BLOB") {
-                               if (isset($f[$i])) { 
-                                       $f[$i] = $this->connection->_BlobDecode($f[$i]); 
-                               } else { 
-                                       $f[$i] = null; 
-                               } 
-                       } else { 
-                               if (!isset($f[$i])) { 
-                                       $f[$i] = null; 
-                               } else if ($rtrim && is_string($f[$i])) {
-                                       $f[$i] = rtrim($f[$i]);
-                               }
-                       } 
-               } 
-               // OPN stuff end 
-               
-               $this->fields = $f;
-               if ($this->fetchMode == ADODB_FETCH_ASSOC) {
-                       $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));
-               }
-               return true;
-       }
-
-       /* 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 _close() 
-       {
-                       return @ibase_free_result($this->_queryID);
-       }
-
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-               case 'CHAR':
-                       return 'C';
-                       
-               case 'TEXT':
-               case 'VARCHAR':
-               case 'VARYING':
-               if ($len <= $this->blobSize) return 'C';
-                       return 'X';
-               case 'BLOB':
-                       return 'B';
-                          
-               case 'TIMESTAMP':
-               case 'DATE': return 'D';
-                               
-                               //case 'T': return 'T';
-
-                               //case 'L': return 'L';
-               case 'INT': 
-               case 'SHORT':
-               case 'INTEGER': return 'I';
-               default: return 'N';
-               }
-       }
-
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.  \r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Interbase data driver. Requires interbase client. Works on Windows and Unix.\r
+\r
+  3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>\r
+       changed transaction handling and added experimental blob stuff\r
+  \r
+  Docs to interbase at the website\r
+   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html\r
+   \r
+  To use gen_id(), see\r
+   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen\r
+   \r
+   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');\r
+   $id = $rs->fields[0];\r
+   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB_ibase extends ADOConnection {\r
+       var $databaseType = "ibase";\r
+       var $dataProvider = "ibase";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $ibase_datefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $ibase_timestampfmt = "%Y-%m-%d %H:%M:%S";\r
+       var $ibase_timefmt = "%H:%M:%S";\r
+       var $fmtTimeStamp = "'Y-m-d, H:i:s'";\r
+       var $concat_operator='||';\r
+       var $_transactionID;\r
+       var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";\r
+       //OPN STUFF start\r
+       var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";\r
+       //OPN STUFF end\r
+       var $ibasetrans;\r
+       var $hasGenID = true;\r
+       var $_bindInputArray = true;\r
+       var $buffers = 0;\r
+       var $dialect = 1;\r
+       var $sysDate = "cast('TODAY' as timestamp)";\r
+       var $sysTimeStamp = "cast('NOW' as timestamp)";\r
+       var $ansiOuter = true;\r
+       var $hasAffectedRows = false;\r
+       var $poorAffectedRows = true;\r
+       var $blobEncodeType = 'C';\r
+       \r
+       function ADODB_ibase() \r
+       {\r
+                if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;\r
+       }\r
+       \r
+       function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)\r
+       {       \r
+               if ($internalKey) return array('RDB$DB_KEY');\r
+               \r
+               $table = strtoupper($table);\r
+               \r
+               $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME\r
+       FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME  \r
+       WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'\r
+       ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';\r
+\r
+               $a = $this->GetCol($sql,false,true);\r
+               if ($a && sizeof($a)>0) return $a;\r
+               return false;     \r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['dialect'] = $this->dialect;\r
+               switch($arr['dialect']) {\r
+               case '': \r
+               case '1': $s = 'Interbase 5.5 or earlier'; break;\r
+               case '2': $s = 'Interbase 5.6'; break;\r
+               default:\r
+               case '3': $s = 'Interbase 6.0'; break;\r
+               }\r
+               $arr['version'] = ADOConnection::_findvers($s);\r
+               $arr['description'] = $s;\r
+               return $arr;\r
+       }\r
+\r
+       function BeginTrans()\r
+       {        \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->autoCommit = false;\r
+               $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);\r
+               return $this->_transactionID;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $ret = false;\r
+               $this->autoCommit = true;\r
+               if ($this->_transactionID) {\r
+                                       //print ' commit ';\r
+                       $ret = ibase_commit($this->_transactionID);\r
+               }\r
+               $this->_transactionID = false;\r
+               return $ret;\r
+       }\r
+       \r
+       // there are some compat problems with ADODB_COUNTRECS=false and $this->_logsql currently.\r
+       // it appears that ibase extension cannot support multiple concurrent queryid's\r
+       function &_Execute($sql,$inputarr=false) \r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               if ($this->_logsql) {\r
+                       $savecrecs = $ADODB_COUNTRECS;\r
+                       $ADODB_COUNTRECS = true; // force countrecs\r
+                       $ret =& ADOConnection::_Execute($sql,$inputarr);\r
+                       $ADODB_COUNTRECS = $savecrecs;\r
+               } else {\r
+                       $ret =& ADOConnection::_Execute($sql,$inputarr);\r
+               }\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $ret = false;\r
+               $this->autoCommit = true;\r
+               if ($this->_transactionID) \r
+                                 $ret = ibase_rollback($this->_transactionID);\r
+               $this->_transactionID = false;   \r
+               \r
+               return $ret;\r
+       }\r
+       \r
+       function &MetaIndexes ($table, $primary = FALSE, $owner=false)\r
+       {\r
+        // save old fetch mode\r
+        global $ADODB_FETCH_MODE;\r
+        \r
+        $save = $ADODB_FETCH_MODE;\r
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+        if ($this->fetchMode !== FALSE) {\r
+               $savem = $this->SetFetchMode(FALSE);\r
+        }\r
+        $table = strtoupper($table);\r
+        $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";\r
+        if (!$primary) {\r
+               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";\r
+        } else {\r
+               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";\r
+        }\r
+        // get index details\r
+        $rs = $this->Execute($sql);\r
+        if (!is_object($rs)) {\r
+               // restore fetchmode\r
+               if (isset($savem)) {\r
+                   $this->SetFetchMode($savem);\r
+               }\r
+               $ADODB_FETCH_MODE = $save;\r
+            return FALSE;\r
+        }\r
+        \r
+        $indexes = array ();\r
+               while ($row = $rs->FetchRow()) {\r
+                       $index = $row[0];\r
+             if (!isset($indexes[$index])) {\r
+                       if (is_null($row[3])) {$row[3] = 0;}\r
+                     $indexes[$index] = array(\r
+                             'unique' => ($row[3] == 1),\r
+                             'columns' => array()\r
+                     );\r
+             }\r
+                       $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";\r
+                       $rs1 = $this->Execute($sql);\r
+            while ($row1 = $rs1->FetchRow()) {\r
+               $indexes[$index]['columns'][$row1[2]] = $row1[1];\r
+               }\r
+               }\r
+        // restore fetchmode\r
+        if (isset($savem)) {\r
+            $this->SetFetchMode($savem);\r
+        }\r
+        $ADODB_FETCH_MODE = $save;\r
+        \r
+        return $indexes;\r
+       }\r
+\r
+       \r
+       // See http://community.borland.com/article/0,1410,25844,00.html\r
+       function RowLock($tables,$where,$col)\r
+       {\r
+               if ($this->autoCommit) $this->BeginTrans();\r
+               $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?\r
+               return 1;\r
+       }\r
+       \r
+       \r
+       function CreateSequence($seqname,$startID=1)\r
+       {\r
+               $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));\r
+               if (!$ok) return false;\r
+               return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');\r
+       }\r
+       \r
+       function DropSequence($seqname)\r
+       {\r
+               $seqname = strtoupper($seqname);\r
+               $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");\r
+       }\r
+       \r
+       function GenID($seqname='adodbseq',$startID=1)\r
+       {\r
+               $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));\r
+                       $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);\r
+               else $this->genID = 0; // false\r
+               \r
+               if ($rs) $rs->Close();\r
+               \r
+               return $this->genID;\r
+       }\r
+\r
+       function SelectDB($dbName) \r
+       {\r
+                  return false;\r
+       }\r
+\r
+       function _handleerror()\r
+       {\r
+               $this->_errorMsg = ibase_errmsg();\r
+       }\r
+\r
+       function ErrorNo() \r
+       {\r
+               if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];\r
+               else return 0;\r
+       }\r
+\r
+       function ErrorMsg() \r
+       {\r
+                       return $this->_errorMsg;\r
+       }\r
+\r
+          // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false)\r
+       {  \r
+               if (!function_exists('ibase_pconnect')) return null;\r
+               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;\r
+               $fn = ($persist) ? 'ibase_pconnect':'ibase_connect';\r
+               $this->_connectionID = $fn($argHostname,$argUsername,$argPassword,\r
+                                       $this->charSet,$this->buffers,$this->dialect);\r
+               \r
+               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html\r
+                       $this->replaceQuote = "''";\r
+               }\r
+               if ($this->_connectionID === false) {\r
+                       $this->_handleerror();\r
+                       return false;\r
+               }\r
+               \r
+               // PHP5 change.\r
+               if (function_exists('ibase_timefmt')) {\r
+                       ibase_timefmt($this->ibase_datefmt,IBASE_DATE );\r
+                       if ($this->dialect == 1) ibase_timefmt($this->ibase_datefmt,IBASE_TIMESTAMP );\r
+                       else ibase_timefmt($this->ibase_timestampfmt,IBASE_TIMESTAMP );\r
+                       ibase_timefmt($this->ibase_timefmt,IBASE_TIME );\r
+               } else {\r
+                       ini_set("ibase.timestampformat", $this->base_timestampfmt);\r
+                       ini_set("ibase.dateformat", $this->ibase_datefmt);\r
+                       ini_set("ibase.timeformat", $this->ibase_timefmt);\r
+               }\r
+               //you can use\r
+               /*\r
+               ini_set("ibase.timestampformat", $this->ibase_timestampfmt);\r
+               ini_set("ibase.dateformat", $this->ibase_datefmt);\r
+               ini_set("ibase.timeformat", $this->ibase_timefmt);\r
+               */\r
+               return true;\r
+       }\r
+          // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,true);\r
+       }       \r
+       \r
+       function Prepare($sql)\r
+       {\r
+               $stmt = ibase_prepare($this->_connectionID,$sql);\r
+               if (!$stmt) return false;\r
+               return array($sql,$stmt);\r
+       }\r
+\r
+          // returns query ID if successful, otherwise false\r
+          // there have been reports of problems with nested queries - the code is probably not re-entrant?\r
+       function _query($sql,$iarr=false)\r
+       { \r
+\r
+               if (!$this->autoCommit && $this->_transactionID) {\r
+                       $conn = $this->_transactionID;\r
+                       $docommit = false;\r
+               } else {\r
+                       $conn = $this->_connectionID;\r
+                       $docommit = true;\r
+               }\r
+               if (is_array($sql)) {\r
+                       $fn = 'ibase_execute';\r
+                       $sql = $sql[1];\r
+                       if (is_array($iarr)) {\r
+                               if  (ADODB_PHPVER >= 0x4050) { // actually 4.0.4\r
+                                       if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack\r
+                                       $fnarr =& array_merge( array($sql) , $iarr);\r
+                                       $ret = call_user_func_array($fn,$fnarr);\r
+                               } else {\r
+                                       switch(sizeof($iarr)) {\r
+                                       case 1: $ret = $fn($sql,$iarr[0]); break;\r
+                                       case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;\r
+                                       case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
+                                       case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
+                                       case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
+                                       case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;\r
+                                       case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;\r
+                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");\r
+                                       case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;\r
+                                       }\r
+                               }\r
+                       } else $ret = $fn($sql); \r
+               } else {\r
+                       $fn = 'ibase_query';\r
+               \r
+                       if (is_array($iarr)) {  \r
+                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4\r
+                                       if (sizeof($iarr) == 0) $iarr[0] = ''; // PHP5 compat hack\r
+                                       $fnarr =& array_merge( array($conn,$sql) , $iarr);\r
+                                       $ret = call_user_func_array($fn,$fnarr);\r
+                               } else {\r
+                                       switch(sizeof($iarr)) {\r
+                                       case 1: $ret = $fn($conn,$sql,$iarr[0]); break;\r
+                                       case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;\r
+                                       case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
+                                       case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
+                                       case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
+                                       case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;\r
+                                       case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;\r
+                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");\r
+                                       case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;\r
+                                       }\r
+                               }\r
+                       } else $ret = $fn($conn,$sql); \r
+               }\r
+               if ($docommit && $ret === true) ibase_commit($this->_connectionID);\r
+\r
+               $this->_handleerror();\r
+               return $ret;\r
+       }\r
+\r
+        // returns true or false\r
+        function _close()\r
+        {         \r
+               if (!$this->autoCommit) @ibase_rollback($this->_connectionID);\r
+               return @ibase_close($this->_connectionID);\r
+        }\r
+       \r
+       //OPN STUFF start\r
+       function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $dialect3)\r
+       {\r
+               $fscale = abs($fscale);\r
+               $fld->max_length = $flen;\r
+               $fld->scale = null;\r
+               switch($ftype){\r
+                       case 7: \r
+                       case 8:\r
+                               if ($dialect3) {\r
+                                   switch($fsubtype){\r
+                                       case 0: \r
+                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');\r
+                                               break;\r
+                                       case 1: \r
+                                               $fld->type = 'numeric';\r
+                                                       $fld->max_length = $fprecision;\r
+                                                       $fld->scale = $fscale;\r
+                                               break;\r
+                                       case 2:\r
+                                               $fld->type = 'decimal';\r
+                                                       $fld->max_length = $fprecision;\r
+                                                       $fld->scale = $fscale;\r
+                                               break;\r
+                                   } // switch\r
+                               } else {\r
+                                       if ($fscale !=0) {\r
+                                           $fld->type = 'decimal';\r
+                                               $fld->scale = $fscale;\r
+                                               $fld->max_length = ($ftype == 7 ? 4 : 9);\r
+                                       } else {\r
+                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');\r
+                                       }\r
+                               }\r
+                               break;\r
+                       case 16: \r
+                               if ($dialect3) {\r
+                                   switch($fsubtype){\r
+                                       case 0: \r
+                                               $fld->type = 'decimal';\r
+                                                       $fld->max_length = 18;\r
+                                                       $fld->scale = 0;\r
+                                               break;\r
+                                       case 1: \r
+                                               $fld->type = 'numeric';\r
+                                                       $fld->max_length = $fprecision;\r
+                                                       $fld->scale = $fscale;\r
+                                               break;\r
+                                       case 2:\r
+                                               $fld->type = 'decimal';\r
+                                                       $fld->max_length = $fprecision;\r
+                                                       $fld->scale = $fscale;\r
+                                               break;\r
+                                   } // switch\r
+                               }\r
+                               break;\r
+                       case 10:\r
+                               $fld->type = 'float';\r
+                               break;\r
+                       case 14:\r
+                               $fld->type = 'char';\r
+                               break;\r
+                       case 27:\r
+                               if ($fscale !=0) {\r
+                                   $fld->type = 'decimal';\r
+                                       $fld->max_length = 15;\r
+                                       $fld->scale = 5;\r
+                               } else {\r
+                                       $fld->type = 'double';\r
+                               }\r
+                               break;\r
+                       case 35:\r
+                               if ($dialect3) {\r
+                                   $fld->type = 'timestamp';\r
+                               } else {\r
+                                       $fld->type = 'date';\r
+                               }\r
+                               break;\r
+                       case 12:\r
+                               $fld->type = 'date';\r
+                               break;\r
+                       case 13:\r
+                               $fld->type = 'time';\r
+                               break;\r
+                       case 37:\r
+                               $fld->type = 'varchar';\r
+                               break;\r
+                       case 40:\r
+                               $fld->type = 'cstring';\r
+                               break;\r
+                       case 261:\r
+                               $fld->type = 'blob';\r
+                               $fld->max_length = -1;\r
+                               break;\r
+               } // switch\r
+       }\r
+       //OPN STUFF end\r
+               // returns array of ADOFieldObjects for current table\r
+       function &MetaColumns($table) \r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               \r
+               if ($this->metaColumnsSQL) {\r
+               \r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+               \r
+                       $ADODB_FETCH_MODE = $save;\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       //OPN STUFF start\r
+                       $dialect3 = ($this->dialect==3 ? true : false);\r
+                       //OPN STUFF end\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = trim($rs->fields[0]);\r
+                               //OPN STUFF start\r
+                               $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3);\r
+                               if (isset($rs->fields[1]) && $rs->fields[1]) {\r
+                                       $fld->not_null = true;\r
+                               }                               \r
+                               if (isset($rs->fields[2])) {\r
+                                       \r
+                                       $fld->has_default = true;\r
+                                       $d = substr($rs->fields[2],strlen('default '));\r
+                                       switch ($fld->type)\r
+                                       {\r
+                                       case 'smallint':\r
+                                       case 'integer': $fld->default_value = (int) $d; break;\r
+                                       case 'char': \r
+                                       case 'blob':\r
+                                       case 'text':\r
+                                       case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;\r
+                                       case 'double':\r
+                                       case 'float': $fld->default_value = (float) $d; break;\r
+                                       default: $fld->default_value = $d; break;\r
+                                       }\r
+                       //      case 35:$tt = 'TIMESTAMP'; break;\r
+                               }\r
+                               if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {\r
+                                       $fld->sub_type = $rs->fields[5];\r
+                               } else {\r
+                                       $fld->sub_type = null;\r
+                               }\r
+                               //OPN STUFF end\r
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                               else $retarr[strtoupper($fld->name)] = $fld;\r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+       \r
+       function BlobEncode( $blob ) \r
+       {\r
+               $blobid = ibase_blob_create( $this->_connectionID);\r
+               ibase_blob_add( $blobid, $blob );\r
+               return ibase_blob_close( $blobid );\r
+       }\r
+       \r
+       // since we auto-decode all blob's since 2.42, \r
+       // BlobDecode should not do any transforms\r
+       function BlobDecode($blob)\r
+       {\r
+               return $blob; \r
+       }\r
+       \r
+       \r
+       \r
+       \r
+       // old blobdecode function\r
+       // still used to auto-decode all blob's\r
+       function _BlobDecode( $blob ) \r
+       {\r
+               $blobid = ibase_blob_open( $blob );\r
+               $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>\r
+               while($string = ibase_blob_get($blobid, 8192)){ \r
+                       $realblob .= $string; \r
+               }\r
+               ibase_blob_close( $blobid );\r
+\r
+               return( $realblob );\r
+       } \r
+       \r
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') \r
+       { \r
+               $fd = fopen($path,'rb'); \r
+               if ($fd === false) return false; \r
+               $blob_id = ibase_blob_create($this->_connectionID); \r
+               \r
+               /* fill with data */ \r
+               \r
+               while ($val = fread($fd,32768)){ \r
+                       ibase_blob_add($blob_id, $val); \r
+               } \r
+               \r
+               /* close and get $blob_id_str for inserting into table */ \r
+               $blob_id_str = ibase_blob_close($blob_id); \r
+               \r
+               fclose($fd); \r
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; \r
+       } \r
+       \r
+       /*\r
+               Insert a null into the blob field of the table first.\r
+               Then use UpdateBlob to store the blob.\r
+               \r
+               Usage:\r
+                \r
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') \r
+       { \r
+       $blob_id = ibase_blob_create($this->_connectionID); \r
+       \r
+       // ibase_blob_add($blob_id, $val); \r
+       \r
+       // replacement that solves the problem by which only the first modulus 64K / \r
+       // of $val are stored at the blob field //////////////////////////////////// \r
+       // Thx Abel Berenstein  aberenstein#afip.gov.ar\r
+       $len = strlen($val); \r
+       $chunk_size = 32768; \r
+       $tail_size = $len % $chunk_size; \r
+       $n_chunks = ($len - $tail_size) / $chunk_size; \r
+       \r
+       for ($n = 0; $n < $n_chunks; $n++) { \r
+               $start = $n * $chunk_size; \r
+               $data = substr($val, $start, $chunk_size); \r
+               ibase_blob_add($blob_id, $data); \r
+       } \r
+       \r
+       if ($tail_size) {\r
+               $start = $n_chunks * $chunk_size; \r
+               $data = substr($val, $start, $tail_size); \r
+               ibase_blob_add($blob_id, $data); \r
+       }\r
+       // end replacement ///////////////////////////////////////////////////////// \r
+       \r
+       $blob_id_str = ibase_blob_close($blob_id); \r
+       \r
+       return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; \r
+       \r
+       } \r
+       \r
+       \r
+       function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               $blob_id = ibase_blob_create($this->_connectionID);\r
+               ibase_blob_add($blob_id, $val);\r
+               $blob_id_str = ibase_blob_close($blob_id);\r
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;\r
+       }\r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       // Only since Interbase 6.0 - uses EXTRACT\r
+       // problem - does not zero-fill the day and month yet\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysDate;\r
+               $s = '';\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       if ($s) $s .= '||';\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= "extract(year from $col)";\r
+                               break;\r
+                       case 'M':\r
+                       case 'm':\r
+                               $s .= "extract(month from $col)";\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= "cast(((extract(month from $col)+2) / 3) as integer)";\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= "(extract(day from $col))";\r
+                               break;\r
+                       case 'H':\r
+                       case 'h':\r
+                         $s .= "(extract(hour from $col))";\r
+                         break;                        \r
+                       case 'I':\r
+                       case 'i':\r
+                         $s .= "(extract(minute from $col))";\r
+                         break;                \r
+                       case 'S':\r
+                       case 's':\r
+                         $s .= "CAST((extract(second from $col)) AS INTEGER)";\r
+                         break;        \r
+\r
+                       default:\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $this->qstr($ch);\r
+                               break;\r
+                       }\r
+               }\r
+               return $s;\r
+       }\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+                Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_ibase extends ADORecordSet\r
+{\r
+\r
+       var $databaseType = "ibase";\r
+       var $bind=false;\r
+       var $_cacheType;\r
+       \r
+       function ADORecordset_ibase($id,$mode=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+                       $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;\r
+                       $this->ADORecordSet($id);\r
+       }\r
+\r
+       /*              Returns: an object containing field information.\r
+                       Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                       fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                       fetchField() is retrieved.              */\r
+\r
+       function &FetchField($fieldOffset = -1)\r
+       {\r
+                        $fld = new ADOFieldObject;\r
+                        $ibf = ibase_field_info($this->_queryID,$fieldOffset);\r
+                        switch (ADODB_ASSOC_CASE) {\r
+                        case 2: // the default\r
+                               $fld->name = ($ibf['alias']);\r
+                                if (empty($fld->name)) $fld->name = ($ibf['name']);\r
+                                break;\r
+                        case 0: \r
+                                $fld->name = strtoupper($ibf['alias']);\r
+                                if (empty($fld->name)) $fld->name = strtoupper($ibf['name']);\r
+                                break;\r
+                        case 1: \r
+                               $fld->name = strtolower($ibf['alias']);\r
+                                if (empty($fld->name)) $fld->name = strtolower($ibf['name']);\r
+                                break;\r
+                        }\r
+                        \r
+                        $fld->type = $ibf['type'];\r
+                        $fld->max_length = $ibf['length'];\r
+                        \r
+                        /*       This needs to be populated from the metadata */ \r
+                        $fld->not_null = false;\r
+                        $fld->has_default = false;\r
+                        $fld->default_value = 'null';\r
+                        return $fld;\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+               $this->_numOfRows = -1;\r
+               $this->_numOfFields = @ibase_num_fields($this->_queryID);\r
+\r
+               // cache types for blob decode check\r
+               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { \r
+                       $f1 = $this->FetchField($i); \r
+                       $this->_cacheType[] = $f1->type;\r
+               }                               \r
+       }\r
+\r
+       function _seek($row)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function _fetch() \r
+       {\r
+               $f = @ibase_fetch_row($this->_queryID); \r
+               if ($f === false) {\r
+                       $this->fields = false;\r
+                       return false;\r
+               }\r
+               // OPN stuff start - optimized\r
+               // fix missing nulls and decode blobs automatically\r
+       \r
+               global $ADODB_ANSI_PADDING_OFF;\r
+               //$ADODB_ANSI_PADDING_OFF=1;\r
+               $rtrim = !empty($ADODB_ANSI_PADDING_OFF);\r
+               \r
+               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { \r
+                       if ($this->_cacheType[$i]=="BLOB") {\r
+                               if (isset($f[$i])) { \r
+                                       $f[$i] = $this->connection->_BlobDecode($f[$i]); \r
+                               } else { \r
+                                       $f[$i] = null; \r
+                               } \r
+                       } else { \r
+                               if (!isset($f[$i])) { \r
+                                       $f[$i] = null; \r
+                               } else if ($rtrim && is_string($f[$i])) {\r
+                                       $f[$i] = rtrim($f[$i]);\r
+                               }\r
+                       } \r
+               } \r
+               // OPN stuff end \r
+               \r
+               $this->fields = $f;\r
+               if ($this->fetchMode == ADODB_FETCH_ASSOC) {\r
+                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+               } else if ($this->fetchMode == ADODB_FETCH_BOTH) {\r
+                       $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));\r
+               }\r
+               return true;\r
+       }\r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+               return $this->fields[$this->bind[strtoupper($colname)]];\r
+               \r
+       }\r
+       \r
+\r
+       function _close() \r
+       {\r
+                       return @ibase_free_result($this->_queryID);\r
+       }\r
+\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+               case 'CHAR':\r
+                       return 'C';\r
+                       \r
+               case 'TEXT':\r
+               case 'VARCHAR':\r
+               case 'VARYING':\r
+               if ($len <= $this->blobSize) return 'C';\r
+                       return 'X';\r
+               case 'BLOB':\r
+                       return 'B';\r
+                          \r
+               case 'TIMESTAMP':\r
+               case 'DATE': return 'D';\r
+               case 'TIME': return 'T';\r
+                               //case 'T': return 'T';\r
+\r
+                               //case 'L': return 'L';\r
+               case 'INT': \r
+               case 'SHORT':\r
+               case 'INTEGER': return 'I';\r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+}\r
 ?>
\ No newline at end of file
index 2f1bd3256df1aadb562fc25934049f9dd688fe2f..95bdc1d318e6cad6d905ee7f7d9a908ab15d309f 100644 (file)
@@ -1,30 +1,34 @@
-<?php
-/**
-* @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-* Released under both BSD license and Lesser GPL library license.
-* Whenever there is any discrepancy between the two licenses,
-* the BSD license will take precedence.
-*
-* Set tabs to 4 for best viewing.
-*
-* Latest version is available at http://php.weblogs.com
-*
-* Informix 9 driver that supports SELECT FIRST
-*
-*/
-include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');
-
-class ADODB_informix extends ADODB_informix72 {
-       var $databaseType = "informix";
-       var $hasTop = 'FIRST';
-       var $ansiOuter = true;
-}
-
-class ADORecordset_informix extends ADORecordset_informix72 {
-       var $databaseType = "informix";
-       function ADORecordset_informix($id,$mode=false)
-       {
-               $this->ADORecordset_informix72($id,$mode);
-       }
-}
+<?php\r
+/**\r
+* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+* Released under both BSD license and Lesser GPL library license.\r
+* Whenever there is any discrepancy between the two licenses,\r
+* the BSD license will take precedence.\r
+*\r
+* Set tabs to 4 for best viewing.\r
+*\r
+* Latest version is available at http://php.weblogs.com\r
+*\r
+* Informix 9 driver that supports SELECT FIRST\r
+*\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');\r
+\r
+class ADODB_informix extends ADODB_informix72 {\r
+       var $databaseType = "informix";\r
+       var $hasTop = 'FIRST';\r
+       var $ansiOuter = true;\r
+}\r
+\r
+class ADORecordset_informix extends ADORecordset_informix72 {\r
+       var $databaseType = "informix";\r
+       function ADORecordset_informix($id,$mode=false)\r
+       {\r
+               $this->ADORecordset_informix72($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 78228168149df0e291f5d477021affef4ee96d3f..79f0198642e3c37c01eb4b1cf1e361da55a6d3e0 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-  Set tabs to 4 for best viewing.
-
-  Latest version is available at http://php.weblogs.com/
-
-  Informix port by Mitchell T. Young (mitch@youngfamily.org)
-
-  Further mods by "Samuel CARRIERE" <samuel_carriere@hotmail.com>
-
-*/
-
-if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1);
-
-class ADODB_informix72 extends ADOConnection {
-       var $databaseType = "informix72";
-       var $dataProvider = "informix";
-       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 $hasAffectedRows = true;
-       var $upperCase = 'upper';
-    var $substr = 'substr';
-       var $metaTablesSQL="select tabname from systables";
-       var $metaColumnsSQL = 
-"select c.colname, c.coltype, c.collength, d.default 
-       from syscolumns c, systables t,sysdefaults d 
-       where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno and tabname='%s'";
-
-//     var $metaColumnsSQL = "select colname, coltype, collength from syscolumns c, systables t where c.tabid=t.tabid and tabname='%s'";
-       var $concat_operator = '||';
-
-       var $lastQuery = false;
-       var $has_insertid = true;
-
-       var $_autocommit = true;
-       var $_bindInputArray = true;  // set to true if ADOConnection.Execute() permits binding of array parameters.
-       var $sysDate = 'TODAY';
-       var $sysTimeStamp = 'CURRENT';
-       var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0
-   
-       function ADODB_informix72()
-       {
-               // alternatively, use older method:
-               //putenv("DBDATE=Y4MD-");
-
-               // force ISO date format
-               putenv('GL_DATE=%Y-%m-%d');
-               
-               if (function_exists('ifx_byteasvarchar')) {
-                       ifx_byteasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
-               ifx_textasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
-               ifx_blobinfile_mode(0); // Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
-               }
-       }
-       
-       function ServerInfo()
-       {
-           if (isset($this->version)) return $this->version;
-       
-           $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1");
-           $arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1");
-           $this->version = $arr;
-           return $arr;
-       }
-
-
-
-       function _insertid()
-       {
-               $sqlca =ifx_getsqlca($this->lastQuery);
-               return @$sqlca["sqlerrd1"];
-       }
-
-       function _affectedrows()
-       {
-               if ($this->lastQuery) {
-                  return @ifx_affected_rows ($this->lastQuery);
-               }
-               return 0;
-       }
-
-       function BeginTrans()
-       {
-               if ($this->transOff) return true;
-               $this->transCnt += 1;
-               $this->Execute('BEGIN');
-               $this->_autocommit = false;
-               return true;
-       }
-
-       function CommitTrans($ok=true) 
-       { 
-               if (!$ok) return $this->RollbackTrans();
-               if ($this->transOff) return true;
-               if ($this->transCnt) $this->transCnt -= 1;
-               $this->Execute('COMMIT');
-               $this->_autocommit = true;
-               return true;
-       }
-
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true;
-               if ($this->transCnt) $this->transCnt -= 1;
-               $this->Execute('ROLLBACK');
-               $this->_autocommit = true;
-               return true;
-       }
-
-       function RowLock($tables,$where)
-       {
-               if ($this->_autocommit) $this->BeginTrans();
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");
-       }
-
-       /*      Returns: the last error message from previous database operation
-               Note: This function is NOT available for Microsoft SQL Server.  */
-
-       function ErrorMsg() 
-       {
-               if (!empty($this->_logsql)) return $this->_errorMsg;
-               $this->_errorMsg = ifx_errormsg();
-               return $this->_errorMsg;
-       }
-
-       function ErrorNo()
-       {
-               preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS
-               if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; 
-               return 0;
-       }
-
-   
-    function &MetaColumns($table)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               if (!empty($this->metaColumnsSQL)) {
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save;
-                       if ($rs === false) return false;
-
-                       $retarr = array();
-                       while (!$rs->EOF) { //print_r($rs->fields);
-                               $fld = new ADOFieldObject();
-                               $fld->name = $rs->fields[0];
-                               $fld->type = $rs->fields[1];
-                               $fld->max_length = $rs->fields[2];
-                               if (trim($rs->fields[3]) != "AAAAAA 0") {
-                                       $fld->has_default = 1;
-                                       $fld->default_value = $rs->fields[3];
-                               } else {
-                                       $fld->has_default = 0;
-                               }
-
-                $retarr[strtolower($fld->name)] = $fld;        
-                               $rs->MoveNext();
-                       }
-
-                       $rs->Close();
-                       return $retarr; 
-               }
-
-               return false;
-       }
-       
-   function &xMetaColumns($table)
-   {
-               return ADOConnection::MetaColumns($table,false);
-   }
-
-   function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
-   {
-               $type = ($blobtype == 'TEXT') ? 1 : 0;
-               $blobid = ifx_create_blob($type,0,$val);
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));
-   }
-
-   function BlobDecode($blobid)
-   {
-               return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid);
-   }
-   
-       // returns true or false
-   function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('ifx_connect')) return false;
-               
-               $dbs = $argDatabasename . "@" . $argHostname;
-               if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); 
-               putenv("INFORMIXSERVER=".trim($argHostname)); 
-               $this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               #if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;
-       }
-
-       // returns true or false
-   function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('ifx_connect')) return false;
-               
-               $dbs = $argDatabasename . "@" . $argHostname;
-               putenv("INFORMIXSERVER=".trim($argHostname)); 
-               $this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               #if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;
-       }
-/*
-       // ifx_do does not accept bind parameters - weird ???
-       function Prepare($sql)
-       {
-               $stmt = ifx_prepare($sql);
-               if (!$stmt) return $sql;
-               else return array($sql,$stmt);
-       }
-*/
-       // returns query ID if successful, otherwise false
-       function _query($sql,$inputarr)
-       {
-       global $ADODB_COUNTRECS;
-       
-         // String parameters have to be converted using ifx_create_char
-         if ($inputarr) {
-                foreach($inputarr as $v) {
-                       if (gettype($v) == 'string') {
-                          $tab[] = ifx_create_char($v);
-                       }
-                       else {
-                          $tab[] = $v;
-                       }
-                }
-         }
-
-         // In case of select statement, we use a scroll cursor in order
-         // to be able to call "move", or "movefirst" statements
-         if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {
-                if ($inputarr) {
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab);
-                }
-                else {
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType);
-                }
-         }
-         else {
-                if ($inputarr) {
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);
-                }
-                else {
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID);
-                }
-         }
-
-         // Following line have been commented because autocommit mode is
-         // not supported by informix SE 7.2
-
-         //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);
-
-               return $this->lastQuery;
-       }
-
-       // returns true or false
-       function _close()
-       {
-               $this->lastQuery = false;
-               return ifx_close($this->_connectionID);
-       }
-}
-
-
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_informix72 extends ADORecordSet {
-
-       var $databaseType = "informix72";
-       var $canSeek = true;
-       var $_fieldprops = false;
-
-       function ADORecordset_informix72($id,$mode=false)
-       {
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               $this->fetchMode = $mode;
-               return $this->ADORecordSet($id);
-       }
-
-
-
-       /*      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 (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"
-                               $o->type = $arr[0];
-                               $o->max_length = $arr[1];
-                               $this->_fieldprops[] = $o;
-                               $o->not_null = $arr[4]=="N";
-                       }
-               }
-               return $this->_fieldprops[$fieldOffset];
-       }
-
-       function _initrs()
-       {
-               $this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;
-               $this->_numOfFields = ifx_num_fields($this->_queryID);
-       }
-
-       function _seek($row)
-       {
-               return @ifx_fetch_row($this->_queryID, $row);
-       }
-
-   function MoveLast()
-   {
-         $this->fields = @ifx_fetch_row($this->_queryID, "LAST");
-         if ($this->fields) $this->EOF = false;
-         $this->_currentRow = -1;
-
-         if ($this->fetchMode == ADODB_FETCH_NUM) {
-                foreach($this->fields as $v) {
-                       $arr[] = $v;
-                }
-                $this->fields = $arr;
-         }
-
-         return true;
-   }
-
-   function MoveFirst()
-       {
-         $this->fields = @ifx_fetch_row($this->_queryID, "FIRST");
-         if ($this->fields) $this->EOF = false;
-         $this->_currentRow = 0;
-
-         if ($this->fetchMode == ADODB_FETCH_NUM) {
-                foreach($this->fields as $v) {
-                       $arr[] = $v;
-                }
-                $this->fields = $arr;
-         }
-
-         return true;
-   }
-
-   function _fetch($ignore_fields=false)
-   {
-
-               $this->fields = @ifx_fetch_row($this->_queryID);
-
-               if (!is_array($this->fields)) return false;
-
-               if ($this->fetchMode == ADODB_FETCH_NUM) {
-                       foreach($this->fields as $v) {
-                               $arr[] = $v;
-                       }
-                       $this->fields = $arr;
-               }
-               return true;
-       }
-
-       /*      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()
-       {
-               return ifx_free_result($this->_queryID);
-       }
-
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim. All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license.\r
+  Whenever there is any discrepancy between the two licenses,\r
+  the BSD license will take precedence.\r
+  Set tabs to 4 for best viewing.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+\r
+  Informix port by Mitchell T. Young (mitch@youngfamily.org)\r
+\r
+  Further mods by "Samuel CARRIERE" <samuel_carriere@hotmail.com>\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1);\r
+\r
+class ADODB_informix72 extends ADOConnection {\r
+       var $databaseType = "informix72";\r
+       var $dataProvider = "informix";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;\r
+       var $upperCase = 'upper';\r
+    var $substr = 'substr';\r
+       var $metaTablesSQL="select tabname from systables where tabtype!=' ' and owner!='informix'"; //Don't get informix tables and pseudo-tables\r
+\r
+\r
+       var $metaColumnsSQL = \r
+               "select c.colname, c.coltype, c.collength, d.default,c.colno\r
+               from syscolumns c, systables t,outer sysdefaults d\r
+               where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno\r
+               and tabname='%s' order by c.colno";\r
+\r
+       var $metaPrimaryKeySQL =\r
+               "select part1,part2,part3,part4,part5,part6,part7,part8 from\r
+               systables t,sysconstraints s,sysindexes i where t.tabname='%s'\r
+               and s.tabid=t.tabid and s.constrtype='P'\r
+               and i.idxname=s.idxname";\r
+\r
+       var $concat_operator = '||';\r
+\r
+       var $lastQuery = false;\r
+       var $has_insertid = true;\r
+\r
+       var $_autocommit = true;\r
+       var $_bindInputArray = true;  // set to true if ADOConnection.Execute() permits binding of array parameters.\r
+       var $sysDate = 'TODAY';\r
+       var $sysTimeStamp = 'CURRENT';\r
+       var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0\r
+   \r
+       function ADODB_informix72()\r
+       {\r
+               // alternatively, use older method:\r
+               //putenv("DBDATE=Y4MD-");\r
+\r
+               // force ISO date format\r
+               putenv('GL_DATE=%Y-%m-%d');\r
+               \r
+               if (function_exists('ifx_byteasvarchar')) {\r
+                       ifx_byteasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. \r
+               ifx_textasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. \r
+               ifx_blobinfile_mode(0); // Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.\r
+               }\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+           if (isset($this->version)) return $this->version;\r
+       \r
+           $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1");\r
+           $arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1");\r
+           $this->version = $arr;\r
+           return $arr;\r
+       }\r
+\r
+\r
+\r
+       function _insertid()\r
+       {\r
+               $sqlca =ifx_getsqlca($this->lastQuery);\r
+               return @$sqlca["sqlerrd1"];\r
+       }\r
+\r
+       function _affectedrows()\r
+       {\r
+               if ($this->lastQuery) {\r
+                  return @ifx_affected_rows ($this->lastQuery);\r
+               }\r
+               return 0;\r
+       }\r
+\r
+       function BeginTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->Execute('BEGIN');\r
+               $this->_autocommit = false;\r
+               return true;\r
+       }\r
+\r
+       function CommitTrans($ok=true) \r
+       { \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('COMMIT');\r
+               $this->_autocommit = true;\r
+               return true;\r
+       }\r
+\r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('ROLLBACK');\r
+               $this->_autocommit = true;\r
+               return true;\r
+       }\r
+\r
+       function RowLock($tables,$where)\r
+       {\r
+               if ($this->_autocommit) $this->BeginTrans();\r
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation\r
+               Note: This function is NOT available for Microsoft SQL Server.  */\r
+\r
+       function ErrorMsg() \r
+       {\r
+               if (!empty($this->_logsql)) return $this->_errorMsg;\r
+               $this->_errorMsg = ifx_errormsg();\r
+               return $this->_errorMsg;\r
+       }\r
+\r
+       function ErrorNo()\r
+       {\r
+               preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS\r
+               if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; \r
+               return 0;\r
+       }\r
+\r
+   \r
+    function &MetaColumns($table)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               if (!empty($this->metaColumnsSQL)) {\r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       if ($rs === false) return false;\r
+                       $rspkey = $this->Execute(sprintf($this->metaPrimaryKeySQL,$table)); //Added to get primary key colno items\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               $fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields); //Added to set primary key flag\r
+                               $fld->max_length = $rs->fields[2];\r
+                               if (trim($rs->fields[3]) != "AAAAAA 0") {\r
+                                       $fld->has_default = 1;\r
+                                       $fld->default_value = $rs->fields[3];\r
+                               } else {\r
+                                       $fld->has_default = 0;\r
+                               }\r
+\r
+                $retarr[strtolower($fld->name)] = $fld;        \r
+                               $rs->MoveNext();\r
+                       }\r
+\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+\r
+               return false;\r
+       }\r
+       \r
+   function &xMetaColumns($table)\r
+   {\r
+               return ADOConnection::MetaColumns($table,false);\r
+   }\r
+\r
+   function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')\r
+   {\r
+               $type = ($blobtype == 'TEXT') ? 1 : 0;\r
+               $blobid = ifx_create_blob($type,0,$val);\r
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));\r
+   }\r
+\r
+   function BlobDecode($blobid)\r
+   {\r
+               return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid);\r
+   }\r
+   \r
+       // returns true or false\r
+   function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('ifx_connect')) return null;\r
+               \r
+               $dbs = $argDatabasename . "@" . $argHostname;\r
+               if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); \r
+               putenv("INFORMIXSERVER=".trim($argHostname)); \r
+               $this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               #if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;\r
+       }\r
+\r
+       // returns true or false\r
+   function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('ifx_connect')) return null;\r
+               \r
+               $dbs = $argDatabasename . "@" . $argHostname;\r
+               putenv("INFORMIXSERVER=".trim($argHostname)); \r
+               $this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               #if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;\r
+       }\r
+/*\r
+       // ifx_do does not accept bind parameters - weird ???\r
+       function Prepare($sql)\r
+       {\r
+               $stmt = ifx_prepare($sql);\r
+               if (!$stmt) return $sql;\r
+               else return array($sql,$stmt);\r
+       }\r
+*/\r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+         // String parameters have to be converted using ifx_create_char\r
+         if ($inputarr) {\r
+                foreach($inputarr as $v) {\r
+                       if (gettype($v) == 'string') {\r
+                          $tab[] = ifx_create_char($v);\r
+                       }\r
+                       else {\r
+                          $tab[] = $v;\r
+                       }\r
+                }\r
+         }\r
+\r
+         // In case of select statement, we use a scroll cursor in order\r
+         // to be able to call "move", or "movefirst" statements\r
+         if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {\r
+                if ($inputarr) {\r
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab);\r
+                }\r
+                else {\r
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType);\r
+                }\r
+         }\r
+         else {\r
+                if ($inputarr) {\r
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);\r
+                }\r
+                else {\r
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID);\r
+                }\r
+         }\r
+\r
+         // Following line have been commented because autocommit mode is\r
+         // not supported by informix SE 7.2\r
+\r
+         //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);\r
+\r
+               return $this->lastQuery;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               $this->lastQuery = false;\r
+               return ifx_close($this->_connectionID);\r
+       }\r
+}\r
+\r
+\r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_informix72 extends ADORecordSet {\r
+\r
+       var $databaseType = "informix72";\r
+       var $canSeek = true;\r
+       var $_fieldprops = false;\r
+\r
+       function ADORecordset_informix72($id,$mode=false)\r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               return $this->ADORecordSet($id);\r
+       }\r
+\r
+\r
+\r
+       /*      Returns: an object containing field information.\r
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+               fetchField() is retrieved.      */\r
+       function &FetchField($fieldOffset = -1)\r
+       {\r
+               if (empty($this->_fieldprops)) {\r
+                       $fp = ifx_fieldproperties($this->_queryID);\r
+                       foreach($fp as $k => $v) {\r
+                               $o = new ADOFieldObject;\r
+                               $o->name = $k;\r
+                               $arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"\r
+                               $o->type = $arr[0];\r
+                               $o->max_length = $arr[1];\r
+                               $this->_fieldprops[] = $o;\r
+                               $o->not_null = $arr[4]=="N";\r
+                       }\r
+               }\r
+               return $this->_fieldprops[$fieldOffset];\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+               $this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;\r
+               $this->_numOfFields = ifx_num_fields($this->_queryID);\r
+       }\r
+\r
+       function _seek($row)\r
+       {\r
+               return @ifx_fetch_row($this->_queryID, $row);\r
+       }\r
+\r
+   function MoveLast()\r
+   {\r
+         $this->fields = @ifx_fetch_row($this->_queryID, "LAST");\r
+         if ($this->fields) $this->EOF = false;\r
+         $this->_currentRow = -1;\r
+\r
+         if ($this->fetchMode == ADODB_FETCH_NUM) {\r
+                foreach($this->fields as $v) {\r
+                       $arr[] = $v;\r
+                }\r
+                $this->fields = $arr;\r
+         }\r
+\r
+         return true;\r
+   }\r
+\r
+   function MoveFirst()\r
+       {\r
+         $this->fields = @ifx_fetch_row($this->_queryID, "FIRST");\r
+         if ($this->fields) $this->EOF = false;\r
+         $this->_currentRow = 0;\r
+\r
+         if ($this->fetchMode == ADODB_FETCH_NUM) {\r
+                foreach($this->fields as $v) {\r
+                       $arr[] = $v;\r
+                }\r
+                $this->fields = $arr;\r
+         }\r
+\r
+         return true;\r
+   }\r
+\r
+   function _fetch($ignore_fields=false)\r
+   {\r
+\r
+               $this->fields = @ifx_fetch_row($this->_queryID);\r
+\r
+               if (!is_array($this->fields)) return false;\r
+\r
+               if ($this->fetchMode == ADODB_FETCH_NUM) {\r
+                       foreach($this->fields as $v) {\r
+                               $arr[] = $v;\r
+                       }\r
+                       $this->fields = $arr;\r
+               }\r
+               return true;\r
+       }\r
+\r
+       /*      close() only needs to be called if you are worried about using too much memory while your script\r
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
+       function _close()\r
+       {\r
+               return ifx_free_result($this->_queryID);\r
+       }\r
+\r
+}\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/drivers/adodb-ldap.inc.php b/lib/adodb/drivers/adodb-ldap.inc.php
new file mode 100644 (file)
index 0000000..7ff2ccf
--- /dev/null
@@ -0,0 +1,311 @@
+<?php\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.\r
+   Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  \r
+  Joshua Eldridge (joshuae74#hotmail.com)\r
+*/ \r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB_ldap extends ADOConnection {\r
+    var $databaseType = 'ldap';\r
+       var $dataProvider = 'ldap';\r
+       \r
+       # Connection information\r
+    var $username = false;\r
+    var $password = false;\r
+    \r
+    # Used during searches\r
+    var $filter;\r
+    var $dn;\r
+\r
+\r
+       function ADODB_ldap() \r
+       {               \r
+\r
+       }\r
+               \r
+       // returns true or false\r
+       \r
+       function _connect( $host, $username, $password, $ldapbase )\r
+       {\r
+\r
+          if ( !function_exists( 'ldap_connect' ) ) return null;\r
+          \r
+          $conn_info = array( $host );\r
+          \r
+          if ( strstr( $host, ':' ) ) {\r
+              $conn_info = split( ':', $host );\r
+          } \r
+\r
+          $this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] ) \r
+              or die( 'Could not connect to ' . $this->_connectionID );\r
+          if ($username && $password) {\r
+              $bind = ldap_bind( $this->_connectionID, $username, $password ) \r
+                  or die( 'Could not bind to ' . $this->_connectionID . ' with $username & $password');\r
+          } else {\r
+              $bind = ldap_bind( $this->_connectionID ) \r
+                  or die( 'Could not bind anonymously to ' . $this->_connectionID );\r
+          }\r
+          return $this->_connectionID;\r
+    }\r
+    \r
+       \r
+       /* returns _queryID or false */\r
+       function _query($sql,$inputarr)\r
+       {\r
+          $rs = ldap_search( $this->_connectionID, $this->database, $sql );\r
+       return $rs; \r
+               \r
+       }\r
+\r
+    /* closes the LDAP connection */\r
+       function _close()\r
+       {\r
+               @ldap_close( $this->_connectionID );\r
+               $this->_connectionID = false;\r
+       }\r
+    \r
+    function ServerInfo()\r
+    {\r
+        if( is_array( $this->version ) ) return $this->version;\r
+        $version = array();\r
+        /*\r
+        Determines how aliases are handled during search. \r
+        LDAP_DEREF_NEVER (0x00)\r
+        LDAP_DEREF_SEARCHING (0x01)\r
+        LDAP_DEREF_FINDING (0x02)\r
+        LDAP_DEREF_ALWAYS (0x03)\r
+        The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but \r
+        not when locating the base object of the search. The LDAP_DEREF_FINDING value means \r
+        aliases are dereferenced when locating the base object but not during the search.  \r
+        Default: LDAP_DEREF_NEVER\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF'] ) ;\r
+        switch ( $version['LDAP_OPT_DEREF'] ) {\r
+          case 0:\r
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER';\r
+          case 1:\r
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING';\r
+          case 2:\r
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING';\r
+          case 3:\r
+            $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS';\r
+        }\r
+        \r
+        /* \r
+        A limit on the number of entries to return from a search. \r
+        LDAP_NO_LIMIT (0) means no limit.\r
+        Default: LDAP_NO_LIMIT\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT'] );\r
+        if ( $version['LDAP_OPT_SIZELIMIT'] == 0 ) {\r
+           $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT';\r
+        }\r
+        \r
+        /*\r
+        A limit on the number of seconds to spend on a search. \r
+        LDAP_NO_LIMIT (0) means no limit.\r
+        Default: LDAP_NO_LIMIT\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT'] );\r
+        if ( $version['LDAP_OPT_TIMELIMIT'] == 0 ) {\r
+           $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT';\r
+        }\r
+        \r
+        /*\r
+        Determines whether the LDAP library automatically follows referrals returned by LDAP servers or not. \r
+        LDAP_OPT_ON\r
+        LDAP_OPT_OFF\r
+        Default: ON\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS'] );\r
+        if ( $version['LDAP_OPT_REFERRALS'] == 0 ) {\r
+           $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF';\r
+        } else {\r
+           $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON';\r
+        \r
+        }\r
+        /*\r
+        Determines whether LDAP I/O operations are automatically restarted if they abort prematurely. \r
+        LDAP_OPT_ON\r
+        LDAP_OPT_OFF\r
+        Default: OFF\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART'] );\r
+        if ( $version['LDAP_OPT_RESTART'] == 0 ) {\r
+           $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF';\r
+        } else {\r
+           $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON';\r
+        \r
+        }\r
+        /*\r
+        This option indicates the version of the LDAP protocol used when communicating with the primary LDAP server.\r
+        LDAP_VERSION2 (2)\r
+        LDAP_VERSION3 (3)\r
+        Default: LDAP_VERSION2 (2)\r
+        */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION'] );\r
+        if ( $version['LDAP_OPT_PROTOCOL_VERSION'] == 2 ) {\r
+           $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2';\r
+        } else {\r
+           $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3';\r
+        \r
+        }\r
+        /* The host name (or list of hosts) for the primary LDAP server. */\r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); \r
+        ldap_get_option( $this->_connectionID, OPT_ERROR_NUMBER, $version['OPT_ERROR_NUMBER'] ); \r
+        ldap_get_option( $this->_connectionID, OPT_ERROR_STRING, $version['OPT_ERROR_STRING'] ); \r
+        ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); \r
+        \r
+        return $this->version = $version;\r
+    \r
+    }\r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_ldap extends ADORecordSet{  \r
+       \r
+       var $databaseType = "ldap";\r
+       var $canSeek = false;\r
+       var $_entryID; /* keeps track of the entry resource identifier */\r
+       \r
+       function ADORecordSet_ldap($queryID,$mode=false) \r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode)\r
+               {\r
+               case ADODB_FETCH_NUM: \r
+                 $this->fetchMode = LDAP_NUM; \r
+               break;\r
+               case ADODB_FETCH_ASSOC: \r
+                 $this->fetchMode = LDAP_ASSOC; \r
+               break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH: \r
+                 $this->fetchMode = LDAP_BOTH; \r
+               break;\r
+               }\r
+       \r
+               $this->ADORecordSet($queryID);  \r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+          /* \r
+          This could be teaked to respect the $COUNTRECS directive from ADODB\r
+          It's currently being used in the _fetch() function and the\r
+          GetAssoc() function\r
+       */\r
+           $this->_numOfRows = ldap_count_entries( $this->connection->_connectionID, $this->_queryID );\r
+\r
+       }\r
+\r
+    /*\r
+    Return whole recordset as a multi-dimensional associative array\r
+       */\r
+       function &GetAssoc($force_array = false, $first2cols = false) \r
+       {\r
+               $records = $this->_numOfRows;\r
+        $results = array();\r
+            for ( $i=0; $i < $records; $i++ ) {\r
+                foreach ( $this->fields as $k=>$v ) {\r
+                    if ( is_array( $v ) ) {\r
+                        if ( $v['count'] == 1 ) {\r
+                            $results[$i][$k] = $v[0];\r
+                        } else {\r
+                            array_shift( $v );\r
+                            $results[$i][$k] = $v;\r
+                        } \r
+                    }\r
+                }\r
+            }\r
+        \r
+               return $results; \r
+       }\r
+    \r
+    function &GetRowAssoc()\r
+       {\r
+        $results = array();\r
+        foreach ( $this->fields as $k=>$v ) {\r
+            if ( is_array( $v ) ) {\r
+                if ( $v['count'] == 1 ) {\r
+                    $results[$k] = $v[0];\r
+                } else {\r
+                    array_shift( $v );\r
+                    $results[$k] = $v;\r
+                } \r
+            }\r
+        }\r
\r
+               return $results; \r
+       }\r
+               \r
+    function GetRowNums()\r
+    {\r
+        $results = array();\r
+        foreach ( $this->fields as $k=>$v ) {\r
+        static $i = 0;\r
+            if (is_array( $v )) {\r
+                if ( $v['count'] == 1 ) {\r
+                    $results[$i] = $v[0];\r
+                } else {\r
+                    array_shift( $v );\r
+                    $results[$i] = $v;\r
+                } \r
+            $i++;\r
+            }\r
+        }\r
+        return $results;\r
+    }\r
+       \r
+       function _fetch()\r
+       {               \r
+               if ( $this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0 )\r
+               return false;\r
+               \r
+        if ( $this->_currentRow == 0 ) {\r
+                 $this->_entryID = ldap_first_entry( $this->connection->_connectionID, $this->_queryID );\r
+        } else {\r
+          $this->_entryID = ldap_next_entry( $this->connection->_connectionID, $this->_entryID );\r
+        }\r
+           \r
+           $this->fields = ldap_get_attributes( $this->connection->_connectionID, $this->_entryID );\r
+           $this->_numOfFields = $this->fields['count'];       \r
+           switch ( $this->fetchMode ) {\r
+            \r
+            case LDAP_ASSOC:\r
+            $this->fields = $this->GetRowAssoc();\r
+            break;\r
+            \r
+            case LDAP_NUM:\r
+            $this->fields = $this->GetRowNums();\r
+            break;\r
+            \r
+            case LDAP_BOTH:\r
+            default:\r
+            break;\r
+        }\r
+        return ( is_array( $this->fields ) );        \r
+       }\r
+       \r
+       function _close() {\r
+               @ldap_free_result( $this->_queryID );   \r
+               $this->_queryID = false;\r
+       }\r
+       \r
+}\r
+?>
\ No newline at end of file
index 30325f39848d8f6da24cd15cece7492e5c32ed68..2e3ffce8550503b0ada13d2877ce967bb8618e2c 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Native mssql driver. Requires mssql client. Works on Windows. 
-  To configure for Unix, see 
-       http://phpbuilder.com/columns/alberto20000919.php3
-       
-*/
-
-//----------------------------------------------------------------
-// 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)
-//----------------------------------------------------------------
-
-
-// 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_mssql extends ADOConnection {
-       var $databaseType = "mssql";    
-       var $dataProvider = "mssql";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
-       var $hasInsertID = true;
-       var $substr = "substring";
-       var $length = 'len';
-       var $upperCase = 'upper';
-       var $hasAffectedRows = 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','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 $_has_mssql_init;
-       var $maxParameterLen = 4000;
-       var $arrayClass = 'ADORecordSet_array_mssql';
-       var $uniqueSort = true;
-       var $leftOuter = '*=';
-       var $rightOuter = '=*';
-       var $ansiOuter = true; // for mssql7 or later
-       var $poorAffectedRows = true;
-       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
-       var $uniqueOrderBy = true;
-       var $_bindInputArray = true;
-       
-       
-       function ADODB_mssql() 
-       {               
-               $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);
-       }
-
-       function ServerInfo()
-       {
-       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);
-               
-               
-               $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
-                       $this->SetFetchMode($savem);
-               
-               $arr['description'] = $row[2];
-               $arr['version'] = 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 $this->GetOne('select @@rowcount');
-       }
-
-       var $_dropSeqSQL = "drop table %s";
-       
-       function CreateSequence($seq='adodbseq',$start=1)
-       {
-               $start -= 1;
-               $this->Execute("create table $seq (id float(53))");
-               $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
-               if (!$ok) {
-                               $this->Execute('ROLLBACK TRANSACTION adodbseq');
-                               return false;
-               }
-               $this->Execute('COMMIT TRANSACTION adodbseq'); 
-               return true;
-       }
-
-       function GenID($seq='adodbseq',$start=1)
-       {
-               //$this->debug=1;
-               $this->Execute('BEGIN TRANSACTION adodbseq');
-               $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
-               if (!$ok) {
-                       $this->Execute("create table $seq (id float(53))");
-                       $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
-                       if (!$ok) {
-                               $this->Execute('ROLLBACK TRANSACTION adodbseq');
-                               return false;
-                       }
-                       $this->Execute('COMMIT TRANSACTION adodbseq'); 
-                       return $start;
-               }
-               $num = $this->GetOne("select id from $seq");
-               $this->Execute('COMMIT TRANSACTION adodbseq'); 
-               return $num;
-               
-               // in old implementation, pre 1.90, we returned GUID...
-               //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");
-       }
-       
-
-       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);
-               } else
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-       
-               return $rs;
-       }
-       
-       
-       // 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;
-               $this->Execute('BEGIN TRAN');
-               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 TRAN');
-               return true;
-       }
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true; 
-               if ($this->transCnt) $this->transCnt -= 1;
-               $this->Execute('ROLLBACK TRAN');
-               return true;
-       }
-       
-       /*
-               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) 
-       {
-               if (!$this->transCnt) $this->BeginTrans();
-               return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where");
-       }
-       
-       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() 
-       { 
-               if(@mssql_select_db("master")) { 
-                                $qry=$this->metaDatabasesSQL; 
-                                if($rs=@mssql_query($qry)){ 
-                                                $tmpAr=$ar=array(); 
-                                                while($tmpAr=@mssql_fetch_row($rs)) 
-                                                                $ar[]=$tmpAr[0]; 
-                                               @mssql_select_db($this->databaseName); 
-                                                if(sizeof($ar)) 
-                                                                return($ar); 
-                                                else 
-                                                                return(false); 
-                                } else { 
-                                                @mssql_select_db($this->databaseName); 
-                                                return(false); 
-                                } 
-                } 
-                return(false); 
-       } 
-
-       // "Stein-Aksel Basma" <basma@accelero.no>
-       // tested with MSSQL 2000
-       function MetaPrimaryKeys($table)
-       {
-               $sql = "select k.column_name 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'";
-               
-               $a = $this->GetCol($sql);
-               if ($a && sizeof($a)>0) return $a;
-               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;
-       }
-       function SelectDB($dbName) 
-       {
-               $this->databaseName = $dbName;
-               if ($this->_connectionID) {
-                       return @mssql_select_db($dbName);               
-               }
-               else return false;      
-       }
-       
-       function ErrorMsg() 
-       {
-               if (empty($this->_errorMsg)){
-                       $this->_errorMsg = mssql_get_last_message();
-               }
-               return $this->_errorMsg;
-       }
-       
-       function ErrorNo() 
-       {
-               if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
-               if (empty($this->_errorMsg)) {
-                       $this->_errorMsg = mssql_get_last_message();
-               }
-               $id = @mssql_query("select @@ERROR",$this->_connectionID);
-               if (!$id) return false;
-               $arr = mssql_fetch_array($id);
-               @mssql_free_result($id);
-               if (is_array($arr)) return $arr[0];
-          else return -1;
-       }
-       
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('mssql_pconnect')) return false;
-               $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('mssql_pconnect')) return false;
-               $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               
-               // persistent connections can forget to rollback on crash, so we do it here.
-               if ($this->autoRollback) {
-                       $cnt = $this->GetOne('select @@TRANCOUNT');
-                       while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN'); 
-               }
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       function Prepare($sql)
-       {
-               $sqlarr = explode('?',$sql);
-               if (sizeof($sqlarr) <= 1) return $sql;
-               $sql2 = $sqlarr[0];
-               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
-                       $sql2 .=  '@P'.($i-1) . $sqlarr[$i];
-               } 
-               return array($sql,$this->qstr($sql2),$max);
-       }
-       
-       function PrepareSP($sql)
-       {
-               if (!$this->_has_mssql_init) {
-                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
-                       return $sql;
-               }
-               $stmt = mssql_init($sql,$this->_connectionID);
-               if (!$stmt)  return $sql;
-               return array($sql,$stmt);
-       }
-       
-       /* 
-       Usage:
-               $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
-               
-               # note that the parameter does not have @ in front!
-               $db->Parameter($stmt,$id,'myid');
-               $db->Parameter($stmt,$group,'group',false,64);
-               $db->Execute($stmt);
-               
-               @param $stmt Statement returned by Prepare() or PrepareSP().
-               @param $var PHP variable to bind to. Can set to null (for isNull support).
-               @param $name Name of stored procedure variable name to bind to.
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
-               @param [$maxLen] Holds an maximum length of the variable.
-               @param [$type] The data type of $var. Legal values depend on driver.
-               
-               See mssql_bind documentation at php.net.
-       */
-       function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)
-       {
-               if (!$this->_has_mssql_init) {
-                       ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");
-                       return $sql;
-               }
-
-               $isNull = is_null($var); // php 4.0.4 and above...
-                       
-               if ($type === false) 
-                       switch(gettype($var)) {
-                       default:
-                       case 'string': $type = SQLCHAR; break;
-                       case 'double': $type = SQLFLT8; break;
-                       case 'integer': $type = SQLINT4; break;
-                       case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0
-                       }
-               
-               if  ($this->debug) {
-                       $prefix = ($isOutput) ? 'Out' : 'In';
-                       $ztype = (empty($type)) ? 'false' : $type;
-                       ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
-               }
-               /*
-                       See http://phplens.com/lens/lensforum/msgs.php?id=7231
-                       
-                       RETVAL is HARD CODED into php_mssql extension:
-                       The return value (a long integer value) is treated like a special OUTPUT parameter, 
-                       called "RETVAL" (without the @). See the example at mssql_execute to 
-                       see how it works. - type: one of this new supported PHP constants. 
-                               SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 
-               */
-               if ($name !== 'RETVAL') $name = '@'.$name;
-               return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);
-       }
-       
-       /* 
-               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')
-       {
-               $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)
-       {
-               $this->_errorMsg = false;
-               if (is_array($inputarr)) {
-                       
-                       # 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
-                       if (!is_array($sql)) $sql = $this->Prepare($sql);
-                       $params = '';
-                       $decl = '';
-                       $i = 0;
-                       foreach($inputarr as $v) {
-                               if ($decl) {
-                                       $decl .= ', ';
-                                       $params .= ', ';
-                               }       
-                               if (is_string($v)) {
-                                       $len = strlen($v);
-                                       if ($len == 0) $len = 1;
-                                       
-                                       if ($len > 4000 ) {
-                                               // NVARCHAR is max 4000 chars. Let's use NTEXT
-                                               $decl .= "@P$i NTEXT";
-                                       } else {
-                                               $decl .= "@P$i NVARCHAR($len)";
-                                       }
-
-                                       $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
-                               } else if (is_integer($v)) {
-                                       $decl .= "@P$i INT";
-                                       $params .= "@P$i=".$v;
-                               } else {
-                                       $decl .= "@P$i FLOAT";
-                                       $params .= "@P$i=".$v;
-                               }
-                               $i += 1;
-                       }
-                       $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");
-                       
-               } else if (is_array($sql)) {
-                       # PrepareSP()
-                       $rez = mssql_execute($sql[1]);
-                       
-               } else {
-                       $rez = mssql_query($sql,$this->_connectionID);
-               }
-               return $rez;
-       }
-       
-       // returns true or false
-       function _close()
-       { 
-               if ($this->transCnt) $this->RollbackTrans();
-               $rez = @mssql_close($this->_connectionID);
-               $this->_connectionID = false;
-               return $rez;
-       }
-       
-       // mssql uses a default date like Dec 30 2000 12:00AM
-       function UnixDate($v)
-       {
-               return ADORecordSet_array_mssql::UnixDate($v);
-       }
-       
-       function UnixTimeStamp($v)
-       {
-               return ADORecordSet_array_mssql::UnixTimeStamp($v);
-       }       
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_mssql extends ADORecordSet {        
-
-       var $databaseType = "mssql";
-       var $canSeek = true;
-       var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083
-       // _mths works only in non-localised system
-       
-       function ADORecordset_mssql($id,$mode=false)
-       {
-               // freedts check...
-               $this->hasFetchAssoc = function_exists('mssql_fetch_assoc');
-
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               $this->fetchMode = $mode;
-               return $this->ADORecordSet($id,$mode);
-       }
-       
-       
-       function _initrs()
-       {
-       GLOBAL $ADODB_COUNTRECS;        
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;
-               $this->_numOfFields = @mssql_num_fields($this->_queryID);
-       }
-       
-
-       //Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>
-       // get next resultset - requires PHP 4.0.5 or later
-       function NextRecordSet()
-       {
-               if (!mssql_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 ($fieldOffset != -1) {
-                       return @mssql_fetch_field($this->_queryID, $fieldOffset);
-               }
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
-                       return @mssql_fetch_field($this->_queryID);
-               }
-               return null;
-       }
-       
-       function _seek($row) 
-       {
-               return @mssql_data_seek($this->_queryID, $row);
-       }
-
-       // speedup
-       function MoveNext() 
-       {
-               if ($this->EOF) return false;
-               
-               $this->_currentRow++;
-               
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
-                       if ($this->fetchMode & ADODB_FETCH_NUM) {
-                               //ADODB_FETCH_BOTH mode
-                               $this->fields = @mssql_fetch_array($this->_queryID);
-                       }
-                       else {
-                               if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later
-                                        $this->fields = @mssql_fetch_assoc($this->_queryID);
-                               } else {
-                                       $flds = @mssql_fetch_array($this->_queryID);
-                                       if (is_array($flds)) {
-                                               $fassoc = array();
-                                               foreach($flds as $k => $v) {
-                                                       if (is_numeric($k)) continue;
-                                                       $fassoc[$k] = $v;
-                                               }
-                                               $this->fields = $fassoc;
-                                       } else
-                                               $this->fields = false;
-                               }
-                       }
-                       
-                       if (is_array($this->fields)) {
-                               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 {
-                       $this->fields = @mssql_fetch_row($this->_queryID);
-               }
-               if ($this->fields) return true;
-               $this->EOF = true;
-               
-               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->fetchMode & ADODB_FETCH_ASSOC) {
-                       if ($this->fetchMode & ADODB_FETCH_NUM) {
-                               //ADODB_FETCH_BOTH mode
-                               $this->fields = @mssql_fetch_array($this->_queryID);
-                       } else {
-                               if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later
-                                       $this->fields = @mssql_fetch_assoc($this->_queryID);
-                               else {
-                                       $this->fields = @mssql_fetch_array($this->_queryID);
-                                       if (is_array($$this->fields)) {
-                                               $fassoc = array();
-                                               foreach($$this->fields as $k => $v) {
-                                                       if (is_integer($k)) continue;
-                                                       $fassoc[$k] = $v;
-                                               }
-                                               $this->fields = $fassoc;
-                                       }
-                               }
-                       }
-                       
-                       if (!$this->fields) {
-                       } else 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 {
-                       $this->fields = @mssql_fetch_row($this->_queryID);
-               }
-               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 = mssql_free_result($this->_queryID);      
-               $this->_queryID = false;
-               return $rez;
-       }
-       // mssql uses a default date like Dec 30 2000 12:00AM
-       function UnixDate($v)
-       {
-               return ADORecordSet_array_mssql::UnixDate($v);
-       }
-       
-       function UnixTimeStamp($v)
-       {
-               return ADORecordSet_array_mssql::UnixTimeStamp($v);
-       }
-       
-}
-
-
-class ADORecordSet_array_mssql extends ADORecordSet_array {
-       function ADORecordSet_array_mssql($id=-1,$mode=false) 
-       {
-               $this->ADORecordSet_array($id,$mode);
-       }
-       
-               // mssql uses a default date like Dec 30 2000 12:00AM
-       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]);
-       }
-       
-       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
-*/
-
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Native mssql driver. Requires mssql client. Works on Windows. \r
+  To configure for Unix, see \r
+       http://phpbuilder.com/columns/alberto20000919.php3\r
+       \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+//----------------------------------------------------------------\r
+// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002\r
+// and this causes tons of problems because localized versions of \r
+// MSSQL will return the dates in dmy or  mdy order; and also the \r
+// month strings depends on what language has been configured. The \r
+// following two variables allow you to control the localization\r
+// settings - Ugh.\r
+//\r
+// MORE LOCALIZATION INFO\r
+// ----------------------\r
+// To configure datetime, look for and modify sqlcommn.loc, \r
+//     typically found in c:\mssql\install\r
+// Also read :\r
+//      http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918\r
+// Alternatively use:\r
+//        CONVERT(char(12),datecol,120)\r
+//----------------------------------------------------------------\r
+\r
+\r
+// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc\r
+if (ADODB_PHPVER >= 0x4300) {\r
+// docs say 4.2.0, but testing shows only since 4.3.0 does it work!\r
+       ini_set('mssql.datetimeconvert',0); \r
+} else {\r
+global $ADODB_mssql_mths;              // array, months must be upper-case\r
+\r
+\r
+       $ADODB_mssql_date_order = 'mdy'; \r
+       $ADODB_mssql_mths = array(\r
+               'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,\r
+               'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);\r
+}\r
+\r
+//---------------------------------------------------------------------------\r
+// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,\r
+// just after you connect to the database. Supports mdy and dmy only.\r
+// Not required for PHP 4.2.0 and above.\r
+function AutoDetect_MSSQL_Date_Order($conn)\r
+{\r
+global $ADODB_mssql_date_order;\r
+       $adate = $conn->GetOne('select getdate()');\r
+       if ($adate) {\r
+               $anum = (int) $adate;\r
+               if ($anum > 0) {\r
+                       if ($anum > 31) {\r
+                               //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");\r
+                       } else\r
+                               $ADODB_mssql_date_order = 'dmy';\r
+               } else\r
+                       $ADODB_mssql_date_order = 'mdy';\r
+       }\r
+}\r
+\r
+class ADODB_mssql extends ADOConnection {\r
+       var $databaseType = "mssql";    \r
+       var $dataProvider = "mssql";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $hasInsertID = true;\r
+       var $substr = "substring";\r
+       var $length = 'len';\r
+       var $upperCase = 'upper';\r
+       var $hasAffectedRows = true;\r
+       var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'";\r
+       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'))";\r
+       var $metaColumnsSQL = # xtype==61 is datetime\r
+"select c.name,t.name,c.length,\r
+       (case when c.xusertype=61 then 0 else c.xprec end),\r
+       (case when c.xusertype=61 then 0 else c.xscale end) \r
+       from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";\r
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $hasGenID = true;\r
+       var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';\r
+       var $sysTimeStamp = 'GetDate()';\r
+       var $_has_mssql_init;\r
+       var $maxParameterLen = 4000;\r
+       var $arrayClass = 'ADORecordSet_array_mssql';\r
+       var $uniqueSort = true;\r
+       var $leftOuter = '*=';\r
+       var $rightOuter = '=*';\r
+       var $ansiOuter = true; // for mssql7 or later\r
+       var $poorAffectedRows = true;\r
+       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000\r
+       var $uniqueOrderBy = true;\r
+       var $_bindInputArray = true;\r
+       \r
+       \r
+       function ADODB_mssql() \r
+       {               \r
+               $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);\r
+       }\r
+\r
+       function ServerInfo()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $stmt = $this->PrepareSP('sp_server_info');\r
+               $val = 2;\r
+               if ($this->fetchMode === false) {\r
+                       $savem = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               } else \r
+                       $savem = $this->SetFetchMode(ADODB_FETCH_NUM);\r
+               \r
+               \r
+               $this->Parameter($stmt,$val,'attribute_id');\r
+               $row = $this->GetRow($stmt);\r
+               \r
+               //$row = $this->GetRow("execute sp_server_info 2");\r
+               \r
+               if ($this->fetchMode === false) {\r
+                       $ADODB_FETCH_MODE = $savem;\r
+               } else\r
+                       $this->SetFetchMode($savem);\r
+               \r
+               $arr['description'] = $row[2];\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               return $arr;\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " ISNULL($field, $ifNull) "; // if MS SQL Server\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+       // SCOPE_IDENTITY()\r
+       // Returns the last IDENTITY value inserted into an IDENTITY column in \r
+       // the same scope. A scope is a module -- a stored procedure, trigger, \r
+       // function, or batch. Thus, two statements are in the same scope if \r
+       // they are in the same stored procedure, function, or batch.\r
+                       return $this->GetOne($this->identitySQL);\r
+       }\r
+\r
+       function _affectedrows()\r
+       {\r
+               return $this->GetOne('select @@rowcount');\r
+       }\r
+\r
+       var $_dropSeqSQL = "drop table %s";\r
+       \r
+       function CreateSequence($seq='adodbseq',$start=1)\r
+       {\r
+               $start -= 1;\r
+               $this->Execute("create table $seq (id float(53))");\r
+               $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");\r
+               if (!$ok) {\r
+                               $this->Execute('ROLLBACK TRANSACTION adodbseq');\r
+                               return false;\r
+               }\r
+               $this->Execute('COMMIT TRANSACTION adodbseq'); \r
+               return true;\r
+       }\r
+\r
+       function GenID($seq='adodbseq',$start=1)\r
+       {\r
+               //$this->debug=1;\r
+               $this->Execute('BEGIN TRANSACTION adodbseq');\r
+               $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");\r
+               if (!$ok) {\r
+                       $this->Execute("create table $seq (id float(53))");\r
+                       $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");\r
+                       if (!$ok) {\r
+                               $this->Execute('ROLLBACK TRANSACTION adodbseq');\r
+                               return false;\r
+                       }\r
+                       $this->Execute('COMMIT TRANSACTION adodbseq'); \r
+                       return $start;\r
+               }\r
+               $num = $this->GetOne("select id from $seq");\r
+               $this->Execute('COMMIT TRANSACTION adodbseq'); \r
+               return $num;\r
+               \r
+               // in old implementation, pre 1.90, we returned GUID...\r
+               //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");\r
+       }\r
+       \r
+\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               if ($nrows > 0 && $offset <= 0) {\r
+                       $sql = preg_replace(\r
+                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);\r
+                       $rs =& $this->Execute($sql,$inputarr);\r
+               } else\r
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+       \r
+               return $rs;\r
+       }\r
+       \r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = '';\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       if ($s) $s .= '+';\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= "datename(yyyy,$col)";\r
+                               break;\r
+                       case 'M':\r
+                               $s .= "convert(char(3),$col,0)";\r
+                               break;\r
+                       case 'm':\r
+                               $s .= "replace(str(month($col),2),' ','0')";\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= "datename(quarter,$col)";\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= "replace(str(day($col),2),' ','0')";\r
+                               break;\r
+                       case 'h':\r
+                               $s .= "substring(convert(char(14),$col,0),13,2)";\r
+                               break;\r
+                       \r
+                       case 'H':\r
+                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
+                               break;\r
+                       case 's':\r
+                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
+                               break;\r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= "substring(convert(char(19),$col,0),18,2)";\r
+                               break;\r
+                               \r
+                       default:\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $this->qstr($ch);\r
+                               break;\r
+                       }\r
+               }\r
+               return $s;\r
+       }\r
+\r
+       \r
+       function BeginTrans()\r
+       {\r
+               if ($this->transOff) return true; \r
+               $this->transCnt += 1;\r
+               $this->Execute('BEGIN TRAN');\r
+               return true;\r
+       }\r
+               \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('COMMIT TRAN');\r
+               return true;\r
+       }\r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true; \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('ROLLBACK TRAN');\r
+               return true;\r
+       }\r
+       \r
+       /*\r
+               Usage:\r
+               \r
+               $this->BeginTrans();\r
+               $this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables\r
+               \r
+               # some operation on both tables table1 and table2\r
+               \r
+               $this->CommitTrans();\r
+               \r
+               See http://www.swynk.com/friends/achigrik/SQL70Locks.asp\r
+       */\r
+       function RowLock($tables,$where) \r
+       {\r
+               if (!$this->transCnt) $this->BeginTrans();\r
+               return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where");\r
+       }\r
+       \r
+       function MetaForeignKeys($table, $owner=false, $upper=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $table = $this->qstr(strtoupper($table));\r
+               \r
+               $sql = \r
+"select object_name(constid) as constraint_name,\r
+       col_name(fkeyid, fkey) as column_name,\r
+       object_name(rkeyid) as referenced_table_name,\r
+       col_name(rkeyid, rkey) as referenced_column_name\r
+from sysforeignkeys\r
+where upper(object_name(fkeyid)) = $table\r
+order by constraint_name, referenced_table_name, keyno";\r
+               \r
+               $constraints =& $this->GetArray($sql);\r
+               \r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               $arr = false;\r
+               foreach($constraints as $constr) {\r
+                       //print_r($constr);\r
+                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; \r
+               }\r
+               if (!$arr) return false;\r
+               \r
+               $arr2 = false;\r
+               \r
+               foreach($arr as $k => $v) {\r
+                       foreach($v as $a => $b) {\r
+                               if ($upper) $a = strtoupper($a);\r
+                               $arr2[$a] = $b;\r
+                       }\r
+               }\r
+               return $arr2;\r
+       }\r
+\r
+       //From: Fernando Moreira <FMoreira@imediata.pt>\r
+       function MetaDatabases() \r
+       { \r
+               if(@mssql_select_db("master")) { \r
+                                $qry=$this->metaDatabasesSQL; \r
+                                if($rs=@mssql_query($qry)){ \r
+                                                $tmpAr=$ar=array(); \r
+                                                while($tmpAr=@mssql_fetch_row($rs)) \r
+                                                                $ar[]=$tmpAr[0]; \r
+                                               @mssql_select_db($this->databaseName); \r
+                                                if(sizeof($ar)) \r
+                                                                return($ar); \r
+                                                else \r
+                                                                return(false); \r
+                                } else { \r
+                                                @mssql_select_db($this->databaseName); \r
+                                                return(false); \r
+                                } \r
+                } \r
+                return(false); \r
+       } \r
+\r
+       // "Stein-Aksel Basma" <basma@accelero.no>\r
+       // tested with MSSQL 2000\r
+       function MetaPrimaryKeys($table)\r
+       {\r
+               $sql = "select k.column_name from information_schema.key_column_usage k,\r
+               information_schema.table_constraints tc \r
+               where tc.constraint_name = k.constraint_name and tc.constraint_type =\r
+               'PRIMARY KEY' and k.table_name = '$table'";\r
+               \r
+               $a = $this->GetCol($sql);\r
+               if ($a && sizeof($a)>0) return $a;\r
+               return false;     \r
+       }\r
+\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {\r
+               if ($mask) {\r
+                       $save = $this->metaTablesSQL;\r
+                       $mask = $this->qstr(($mask));\r
+                       $this->metaTablesSQL .= " AND name like $mask";\r
+               }\r
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
+               \r
+               if ($mask) {\r
+                       $this->metaTablesSQL = $save;\r
+               }\r
+               return $ret;\r
+       }\r
\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @mssql_select_db($dbName);               \r
+               }\r
+               else return false;      \r
+       }\r
+       \r
+       function ErrorMsg() \r
+       {\r
+               if (empty($this->_errorMsg)){\r
+                       $this->_errorMsg = mssql_get_last_message();\r
+               }\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       function ErrorNo() \r
+       {\r
+               if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;\r
+               if (empty($this->_errorMsg)) {\r
+                       $this->_errorMsg = mssql_get_last_message();\r
+               }\r
+               $id = @mssql_query("select @@ERROR",$this->_connectionID);\r
+               if (!$id) return false;\r
+               $arr = mssql_fetch_array($id);\r
+               @mssql_free_result($id);\r
+               if (is_array($arr)) return $arr[0];\r
+          else return -1;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('mssql_pconnect')) return null;\r
+               $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('mssql_pconnect')) return null;\r
+               $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               \r
+               // persistent connections can forget to rollback on crash, so we do it here.\r
+               if ($this->autoRollback) {\r
+                       $cnt = $this->GetOne('select @@TRANCOUNT');\r
+                       while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN'); \r
+               }\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       function Prepare($sql)\r
+       {\r
+               $sqlarr = explode('?',$sql);\r
+               if (sizeof($sqlarr) <= 1) return $sql;\r
+               $sql2 = $sqlarr[0];\r
+               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {\r
+                       $sql2 .=  '@P'.($i-1) . $sqlarr[$i];\r
+               } \r
+               return array($sql,$this->qstr($sql2),$max);\r
+       }\r
+       \r
+       function PrepareSP($sql)\r
+       {\r
+               if (!$this->_has_mssql_init) {\r
+                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");\r
+                       return $sql;\r
+               }\r
+               $stmt = mssql_init($sql,$this->_connectionID);\r
+               if (!$stmt)  return $sql;\r
+               return array($sql,$stmt);\r
+       }\r
+       \r
+       /* \r
+       Usage:\r
+               $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group\r
+               \r
+               # note that the parameter does not have @ in front!\r
+               $db->Parameter($stmt,$id,'myid');\r
+               $db->Parameter($stmt,$group,'group',false,64);\r
+               $db->Execute($stmt);\r
+               \r
+               @param $stmt Statement returned by Prepare() or PrepareSP().\r
+               @param $var PHP variable to bind to. Can set to null (for isNull support).\r
+               @param $name Name of stored procedure variable name to bind to.\r
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
+               @param [$maxLen] Holds an maximum length of the variable.\r
+               @param [$type] The data type of $var. Legal values depend on driver.\r
+               \r
+               See mssql_bind documentation at php.net.\r
+       */\r
+       function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)\r
+       {\r
+               if (!$this->_has_mssql_init) {\r
+                       ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");\r
+                       return $sql;\r
+               }\r
+\r
+               $isNull = is_null($var); // php 4.0.4 and above...\r
+                       \r
+               if ($type === false) \r
+                       switch(gettype($var)) {\r
+                       default:\r
+                       case 'string': $type = SQLCHAR; break;\r
+                       case 'double': $type = SQLFLT8; break;\r
+                       case 'integer': $type = SQLINT4; break;\r
+                       case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0\r
+                       }\r
+               \r
+               if  ($this->debug) {\r
+                       $prefix = ($isOutput) ? 'Out' : 'In';\r
+                       $ztype = (empty($type)) ? 'false' : $type;\r
+                       ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");\r
+               }\r
+               /*\r
+                       See http://phplens.com/lens/lensforum/msgs.php?id=7231\r
+                       \r
+                       RETVAL is HARD CODED into php_mssql extension:\r
+                       The return value (a long integer value) is treated like a special OUTPUT parameter, \r
+                       called "RETVAL" (without the @). See the example at mssql_execute to \r
+                       see how it works. - type: one of this new supported PHP constants. \r
+                               SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 \r
+               */\r
+               if ($name !== 'RETVAL') $name = '@'.$name;\r
+               return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);\r
+       }\r
+       \r
+       /* \r
+               Unfortunately, it appears that mssql cannot handle varbinary > 255 chars\r
+               So all your blobs must be of type "image".\r
+               \r
+               Remember to set in php.ini the following...\r
+               \r
+               ; Valid range 0 - 2147483647. Default = 4096. \r
+               mssql.textlimit = 0 ; zero to pass through \r
+\r
+               ; Valid range 0 - 2147483647. Default = 4096. \r
+               mssql.textsize = 0 ; zero to pass through \r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";\r
+               return $this->Execute($sql) != false;\r
+       }\r
+       \r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               $this->_errorMsg = false;\r
+               if (is_array($inputarr)) {\r
+                       \r
+                       # bind input params with sp_executesql: \r
+                       # see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm\r
+                       # works only with sql server 7 and newer\r
+                       if (!is_array($sql)) $sql = $this->Prepare($sql);\r
+                       $params = '';\r
+                       $decl = '';\r
+                       $i = 0;\r
+                       foreach($inputarr as $v) {\r
+                               if ($decl) {\r
+                                       $decl .= ', ';\r
+                                       $params .= ', ';\r
+                               }       \r
+                               if (is_string($v)) {\r
+                                       $len = strlen($v);\r
+                                       if ($len == 0) $len = 1;\r
+                                       \r
+                                       if ($len > 4000 ) {\r
+                                               // NVARCHAR is max 4000 chars. Let's use NTEXT\r
+                                               $decl .= "@P$i NTEXT";\r
+                                       } else {\r
+                                               $decl .= "@P$i NVARCHAR($len)";\r
+                                       }\r
+\r
+                                       $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));\r
+                               } else if (is_integer($v)) {\r
+                                       $decl .= "@P$i INT";\r
+                                       $params .= "@P$i=".$v;\r
+                               } else {\r
+                                       $decl .= "@P$i FLOAT";\r
+                                       $params .= "@P$i=".$v;\r
+                               }\r
+                               $i += 1;\r
+                       }\r
+                       $decl = $this->qstr($decl);\r
+                       if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");\r
+                       $rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params");\r
+                       \r
+               } else if (is_array($sql)) {\r
+                       # PrepareSP()\r
+                       $rez = mssql_execute($sql[1]);\r
+                       \r
+               } else {\r
+                       $rez = mssql_query($sql,$this->_connectionID);\r
+               }\r
+               return $rez;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       { \r
+               if ($this->transCnt) $this->RollbackTrans();\r
+               $rez = @mssql_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+               return $rez;\r
+       }\r
+       \r
+       // mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+               return ADORecordSet_array_mssql::UnixDate($v);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+               return ADORecordSet_array_mssql::UnixTimeStamp($v);\r
+       }       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_mssql extends ADORecordSet {        \r
+\r
+       var $databaseType = "mssql";\r
+       var $canSeek = true;\r
+       var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083\r
+       // _mths works only in non-localised system\r
+       \r
+       function ADORecordset_mssql($id,$mode=false)\r
+       {\r
+               // freedts check...\r
+               $this->hasFetchAssoc = function_exists('mssql_fetch_assoc');\r
+\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               return $this->ADORecordSet($id,$mode);\r
+       }\r
+       \r
+       \r
+       function _initrs()\r
+       {\r
+       GLOBAL $ADODB_COUNTRECS;        \r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @mssql_num_fields($this->_queryID);\r
+       }\r
+       \r
+\r
+       //Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>\r
+       // get next resultset - requires PHP 4.0.5 or later\r
+       function NextRecordSet()\r
+       {\r
+               if (!mssql_next_result($this->_queryID)) return false;\r
+               $this->_inited = false;\r
+               $this->bind = false;\r
+               $this->_currentRow = -1;\r
+               $this->Init();\r
+               return true;\r
+       }\r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+       /*      Returns: an object containing field information. \r
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+               fetchField() is retrieved.      */\r
+\r
+       function FetchField($fieldOffset = -1) \r
+       {\r
+               if ($fieldOffset != -1) {\r
+                       return @mssql_fetch_field($this->_queryID, $fieldOffset);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       return @mssql_fetch_field($this->_queryID);\r
+               }\r
+               return null;\r
+       }\r
+       \r
+       function _seek($row) \r
+       {\r
+               return @mssql_data_seek($this->_queryID, $row);\r
+       }\r
+\r
+       // speedup\r
+       function MoveNext() \r
+       {\r
+               if ($this->EOF) return false;\r
+               \r
+               $this->_currentRow++;\r
+               \r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                       if ($this->fetchMode & ADODB_FETCH_NUM) {\r
+                               //ADODB_FETCH_BOTH mode\r
+                               $this->fields = @mssql_fetch_array($this->_queryID);\r
+                       }\r
+                       else {\r
+                               if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later\r
+                                        $this->fields = @mssql_fetch_assoc($this->_queryID);\r
+                               } else {\r
+                                       $flds = @mssql_fetch_array($this->_queryID);\r
+                                       if (is_array($flds)) {\r
+                                               $fassoc = array();\r
+                                               foreach($flds as $k => $v) {\r
+                                                       if (is_numeric($k)) continue;\r
+                                                       $fassoc[$k] = $v;\r
+                                               }\r
+                                               $this->fields = $fassoc;\r
+                                       } else\r
+                                               $this->fields = false;\r
+                               }\r
+                       }\r
+                       \r
+                       if (is_array($this->fields)) {\r
+                               if (ADODB_ASSOC_CASE == 0) {\r
+                                       foreach($this->fields as $k=>$v) {\r
+                                               $this->fields[strtolower($k)] = $v;\r
+                                       }\r
+                               } else if (ADODB_ASSOC_CASE == 1) {\r
+                                       foreach($this->fields as $k=>$v) {\r
+                                               $this->fields[strtoupper($k)] = $v;\r
+                                       }\r
+                               }\r
+                       }\r
+               } else {\r
+                       $this->fields = @mssql_fetch_row($this->_queryID);\r
+               }\r
+               if ($this->fields) return true;\r
+               $this->EOF = true;\r
+               \r
+               return false;\r
+       }\r
+\r
+       \r
+       // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4\r
+       // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!\r
+       function _fetch($ignore_fields=false) \r
+       {\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                       if ($this->fetchMode & ADODB_FETCH_NUM) {\r
+                               //ADODB_FETCH_BOTH mode\r
+                               $this->fields = @mssql_fetch_array($this->_queryID);\r
+                       } else {\r
+                               if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later\r
+                                       $this->fields = @mssql_fetch_assoc($this->_queryID);\r
+                               else {\r
+                                       $this->fields = @mssql_fetch_array($this->_queryID);\r
+                                       if (@is_array($$this->fields)) {\r
+                                               $fassoc = array();\r
+                                               foreach($$this->fields as $k => $v) {\r
+                                                       if (is_integer($k)) continue;\r
+                                                       $fassoc[$k] = $v;\r
+                                               }\r
+                                               $this->fields = $fassoc;\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                       if (!$this->fields) {\r
+                       } else if (ADODB_ASSOC_CASE == 0) {\r
+                               foreach($this->fields as $k=>$v) {\r
+                                       $this->fields[strtolower($k)] = $v;\r
+                               }\r
+                       } else if (ADODB_ASSOC_CASE == 1) {\r
+                               foreach($this->fields as $k=>$v) {\r
+                                       $this->fields[strtoupper($k)] = $v;\r
+                               }\r
+                       }\r
+               } else {\r
+                       $this->fields = @mssql_fetch_row($this->_queryID);\r
+               }\r
+               return $this->fields;\r
+       }\r
+       \r
+       /*      close() only needs to be called if you are worried about using too much memory while your script\r
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
+\r
+       function _close() \r
+       {\r
+               $rez = mssql_free_result($this->_queryID);      \r
+               $this->_queryID = false;\r
+               return $rez;\r
+       }\r
+       // mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+               return ADORecordSet_array_mssql::UnixDate($v);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+               return ADORecordSet_array_mssql::UnixTimeStamp($v);\r
+       }\r
+       \r
+}\r
+\r
+\r
+class ADORecordSet_array_mssql extends ADORecordSet_array {\r
+       function ADORecordSet_array_mssql($id=-1,$mode=false) \r
+       {\r
+               $this->ADORecordSet_array($id,$mode);\r
+       }\r
+       \r
+               // mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+       \r
+               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);\r
+               \r
+       global $ADODB_mssql_mths,$ADODB_mssql_date_order;\r
+       \r
+               //Dec 30 2000 12:00AM \r
+               if ($ADODB_mssql_date_order == 'dmy') {\r
+                       if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {\r
+                               return parent::UnixDate($v);\r
+                       }\r
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+                       \r
+                       $theday = $rr[1];\r
+                       $themth =  substr(strtoupper($rr[2]),0,3);\r
+               } else {\r
+                       if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {\r
+                               return parent::UnixDate($v);\r
+                       }\r
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+                       \r
+                       $theday = $rr[2];\r
+                       $themth = substr(strtoupper($rr[1]),0,3);\r
+               }\r
+               $themth = $ADODB_mssql_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime(0,0,0,$themth,$theday,$rr[3]);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+       \r
+               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);\r
+               \r
+       global $ADODB_mssql_mths,$ADODB_mssql_date_order;\r
+       \r
+               //Dec 30 2000 12:00AM\r
+                if ($ADODB_mssql_date_order == 'dmy') {\r
+                        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})|"\r
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+               \r
+                       $theday = $rr[1];\r
+                       $themth =  substr(strtoupper($rr[2]),0,3);\r
+               } else {\r
+                       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})|"\r
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+               \r
+                       $theday = $rr[2];\r
+                       $themth = substr(strtoupper($rr[1]),0,3);\r
+               }\r
+               \r
+               $themth = $ADODB_mssql_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               \r
+               switch (strtoupper($rr[6])) {\r
+               case 'P':\r
+                       if ($rr[4]<12) $rr[4] += 12;\r
+                       break;\r
+               case 'A':\r
+                       if ($rr[4]==12) $rr[4] = 0;\r
+                       break;\r
+               default:\r
+                       break;\r
+               }\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);\r
+       }\r
+}\r
+\r
+/*\r
+Code Example 1:\r
+\r
+select         object_name(constid) as constraint_name,\r
+               object_name(fkeyid) as table_name, \r
+        col_name(fkeyid, fkey) as column_name,\r
+       object_name(rkeyid) as referenced_table_name,\r
+       col_name(rkeyid, rkey) as referenced_column_name\r
+from sysforeignkeys\r
+where object_name(fkeyid) = x\r
+order by constraint_name, table_name, referenced_table_name,  keyno\r
+\r
+Code Example 2:\r
+select         constraint_name,\r
+       column_name,\r
+       ordinal_position\r
+from information_schema.key_column_usage\r
+where constraint_catalog = db_name()\r
+and table_name = x\r
+order by constraint_name, ordinal_position\r
+\r
+http://www.databasejournal.com/scripts/article.php/1440551\r
+*/\r
+\r
 ?>
\ No newline at end of file
index 4eca722672434f6d7e817d8cd791d28cc909d443..0cd801c89bc8e098745bb645a696270e03021ac1 100644 (file)
@@ -1,59 +1,62 @@
-<?php
-/**
-* @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-* Released under both BSD license and Lesser GPL library license.
-* Whenever there is any discrepancy between the two licenses,
-* the BSD license will take precedence.
-*
-* Set tabs to 4 for best viewing.
-*
-* Latest version is available at http://php.weblogs.com
-*
-*  Portable MSSQL Driver that supports || instead of +
-*
-*/
-
-
-/*
-       The big difference between mssqlpo and it's parent mssql is that mssqlpo supports
-       the more standard || string concatenation operator.
-*/
-       
-include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
-
-class ADODB_mssqlpo extends ADODB_mssql {
-       var $databaseType = "mssqlpo";
-       var $concat_operator = '||'; 
-       
-       function ADODB_mssqlpo()
-       {
-               ADODB_mssql::ADODB_mssql();
-       }
-
-       function PrepareSP($sql)
-       {
-               if (!$this->_has_mssql_init) {
-                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
-                       return $sql;
-               }
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);
-               $stmt = mssql_init($sql,$this->_connectionID);
-               if (!$stmt)  return $sql;
-               return array($sql,$stmt);
-       }
-       
-       function _query($sql,$inputarr)
-       {
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);
-               return ADODB_mssql::_query($sql,$inputarr);
-       }
-}
-
-class ADORecordset_mssqlpo extends ADORecordset_mssql {
-       var $databaseType = "mssqlpo";
-       function ADORecordset_mssqlpo($id,$mode=false)
-       {
-               $this->ADORecordset_mssql($id,$mode);
-       }
-}
+<?php\r
+/**\r
+* @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+* Released under both BSD license and Lesser GPL library license.\r
+* Whenever there is any discrepancy between the two licenses,\r
+* the BSD license will take precedence.\r
+*\r
+* Set tabs to 4 for best viewing.\r
+*\r
+* Latest version is available at http://php.weblogs.com\r
+*\r
+*  Portable MSSQL Driver that supports || instead of +\r
+*\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+\r
+/*\r
+       The big difference between mssqlpo and it's parent mssql is that mssqlpo supports\r
+       the more standard || string concatenation operator.\r
+*/\r
+       \r
+include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');\r
+\r
+class ADODB_mssqlpo extends ADODB_mssql {\r
+       var $databaseType = "mssqlpo";\r
+       var $concat_operator = '||'; \r
+       \r
+       function ADODB_mssqlpo()\r
+       {\r
+               ADODB_mssql::ADODB_mssql();\r
+       }\r
+\r
+       function PrepareSP($sql)\r
+       {\r
+               if (!$this->_has_mssql_init) {\r
+                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");\r
+                       return $sql;\r
+               }\r
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
+               $stmt = mssql_init($sql,$this->_connectionID);\r
+               if (!$stmt)  return $sql;\r
+               return array($sql,$stmt);\r
+       }\r
+       \r
+       function _query($sql,$inputarr)\r
+       {\r
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
+               return ADODB_mssql::_query($sql,$inputarr);\r
+       }\r
+}\r
+\r
+class ADORecordset_mssqlpo extends ADORecordset_mssql {\r
+       var $databaseType = "mssqlpo";\r
+       function ADORecordset_mssqlpo($id,$mode=false)\r
+       {\r
+               $this->ADORecordset_mssql($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 354845a010a391d8ab46f05f5f3e1c6e7294b43e..796033477e6941a04d99046861c023a8cf74e674 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
-  
-  MySQL code that does not support transactions. Use mysqlt if you need transactions.
-  Requires mysql client. Works on Windows and Unix.
-  
- 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)
-*/ 
-
-if (! defined("_ADODB_MYSQL_LAYER")) {
- define("_ADODB_MYSQL_LAYER", 1 );
-
-class ADODB_mysql extends ADOConnection {
-       var $databaseType = 'mysql';
-       var $dataProvider = 'mysql';
-       var $hasInsertID = true;
-       var $hasAffectedRows = true;    
-       var $metaTablesSQL = "SHOW TABLES";     
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       var $hasLimit = true;
-       var $hasMoveFirst = true;
-       var $hasGenID = true;
-       var $upperCase = 'upper';
-       var $isoDates = true; // accepts dates in ISO format
-       var $sysDate = 'CURDATE()';
-       var $sysTimeStamp = 'NOW()';
-       var $hasTransactions = false;
-       var $forceNewConnect = false;
-       var $poorAffectedRows = true;
-       var $clientFlags = 0;
-       var $substr = "substring";
-       var $nameQuote = '`';           /// string to use to quote identifiers and names
-       
-       function ADODB_mysql() 
-       {                       
-       }
-       
-       function ServerInfo()
-       {
-               $arr['description'] = ADOConnection::GetOne("select version()");
-               $arr['version'] = ADOConnection::_findvers($arr['description']);
-               return $arr;
-       }
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " IFNULL($field, $ifNull) "; // if MySQL
-       }
-       
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
-       {       
-               if ($mask) {
-                       $save = $this->metaTablesSQL;
-                       $mask = $this->qstr($mask);
-                       $this->metaTablesSQL .= " like $mask";
-               }
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
-               
-               if ($mask) {
-                       $this->metaTablesSQL = $save;
-               }
-               return $ret;
-       }
-       
-       
-       function &MetaIndexes ($table, $primary = FALSE, $owner=false)
-       {
-        // save old fetch mode
-        global $ADODB_FETCH_MODE;
-        
-        $save = $ADODB_FETCH_MODE;
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-        if ($this->fetchMode !== FALSE) {
-               $savem = $this->SetFetchMode(FALSE);
-        }
-        
-        // get index details
-        $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
-        
-        // restore fetchmode
-        if (isset($savem)) {
-                $this->SetFetchMode($savem);
-        }
-        $ADODB_FETCH_MODE = $save;
-        
-        if (!is_object($rs)) {
-                return FALSE;
-        }
-        
-        $indexes = array ();
-        
-        // parse index data into array
-        while ($row = $rs->FetchRow()) {
-                if ($primary == FALSE AND $row[2] == 'PRIMARY') {
-                        continue;
-                }
-                
-                if (!isset($indexes[$row[2]])) {
-                        $indexes[$row[2]] = array(
-                                'unique' => ($row[1] == 0),
-                                'columns' => array()
-                        );
-                }
-                
-                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
-        }
-        
-        // sort columns by order in the index
-        foreach ( array_keys ($indexes) as $index )
-        {
-                ksort ($indexes[$index]['columns']);
-        }
-        
-        return $indexes;
-       }
-
-       
-       // if magic quotes disabled, use mysql_real_escape_string()
-       function qstr($s,$magic_quotes=false)
-       {
-               if (!$magic_quotes) {
-               
-                       if (ADODB_PHPVER >= 0x4300) {
-                               if (is_resource($this->_connectionID))
-                                       return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
-                       }
-                       if ($this->replaceQuote[0] == '\\'){
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-                       }
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
-               }
-               
-               // undo magic quotes for "
-               $s = str_replace('\\"','"',$s);
-               return "'$s'";
-       }
-       
-       function _insertid()
-       {
-               return mysql_insert_id($this->_connectionID);
-       }
-       
-       function GetOne($sql,$inputarr=false)
-       {
-               $rs =& $this->SelectLimit($sql,1,-1,$inputarr);
-               if ($rs) {
-                       $rs->Close();
-                       if ($rs->EOF) return false;
-                       return reset($rs->fields);
-               }
-               
-               return false;
-       }
-       
-       function _affectedrows()
-       {
-                       return mysql_affected_rows($this->_connectionID);
-       }
-  
-       // 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 $_genSeq2SQL = "insert into %s values (%s)";
-       var $_dropSeqSQL = "drop table %s";
-       
-       function CreateSequence($seqname='adodbseq',$startID=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
-               $u = strtoupper($seqname);
-               
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
-               if (!$ok) return false;
-               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
-       }
-       
-
-       function GenID($seqname='adodbseq',$startID=1)
-       {
-               // post-nuke sets hasGenID to false
-               if (!$this->hasGenID) return false;
-               
-               $savelog = $this->_logsql;
-               $this->_logsql = false;
-               $getnext = sprintf($this->_genIDSQL,$seqname);
-               $holdtransOK = $this->_transOK; // save the current status
-               $rs = @$this->Execute($getnext);
-               if (!$rs) {
-                       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));
-                       $rs = $this->Execute($getnext);
-               }
-               $this->genID = mysql_insert_id($this->_connectionID);
-               
-               if ($rs) $rs->Close();
-               
-               $this->_logsql = $savelog;
-               return $this->genID;
-       }
-       
-       function &MetaDatabases()
-       {
-               $qid = mysql_list_dbs($this->_connectionID);
-               $arr = array();
-               $i = 0;
-               $max = mysql_num_rows($qid);
-               while ($i < $max) {
-                       $db = mysql_tablename($qid,$i);
-                       if ($db != 'mysql') $arr[] = $db;
-                       $i += 1;
-               }
-               return $arr;
-       }
-       
-               
-       // 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 = 'DATE_FORMAT('.$col.",'";
-               $concat = false;
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= '%Y';
-                               break;
-                       case 'Q':
-                       case 'q':
-                               $s .= "'),Quarter($col)";
-                               
-                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
-                               else $s .= ",('";
-                               $concat = true;
-                               break;
-                       case 'M':
-                               $s .= '%b';
-                               break;
-                               
-                       case 'm':
-                               $s .= '%m';
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= '%d';
-                               break;
-                       
-                       case 'H': 
-                               $s .= '%H';
-                               break;
-                               
-                       case 'h':
-                               $s .= '%I';
-                               break;
-                               
-                       case 'i':
-                               $s .= '%i';
-                               break;
-                               
-                       case 's':
-                               $s .= '%s';
-                               break;
-                               
-                       case 'a':
-                       case 'A':
-                               $s .= '%p';
-                               break;
-                               
-                       default:
-                               
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               $s .= $ch;
-                               break;
-                       }
-               }
-               $s.="')";
-               if ($concat) $s = "CONCAT($s)";
-               return $s;
-       }
-       
-
-       // returns concatenated string
-       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
-       function Concat()
-       {
-               $s = "";
-               $arr = func_get_args();
-               
-               // suggestion by andrew005@mnogo.ru
-               $s = implode(',',$arr); 
-               if (strlen($s) > 0) return "CONCAT($s)";
-               else return '';
-       }
-       
-       function OffsetDate($dayFraction,$date=false)
-       {               
-               if (!$date) $date = $this->sysDate;
-               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
-       }
-       
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (ADODB_PHPVER >= 0x4300)
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
-                                                                                               $this->forceNewConnect,$this->clientFlags);
-               else if (ADODB_PHPVER >= 0x4200)
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
-                                                                                               $this->forceNewConnect);
-               else
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
-       
-               if ($this->_connectionID === false) return false;
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (ADODB_PHPVER >= 0x4300)
-                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
-               else
-                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               if ($this->autoRollback) $this->RollbackTrans();
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               $this->forceNewConnect = true;
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
-       }
-       
-       function &MetaColumns($table) 
-       {
-       
-               if ($this->metaColumnsSQL) {
-               global $ADODB_FETCH_MODE;
-               
-                       $save = $ADODB_FETCH_MODE;
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-                       
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
-                       
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save;
-                       
-                       if ($rs === false) return false;
-                       
-                       $retarr = array();
-                       while (!$rs->EOF){
-                               $fld = new ADOFieldObject();
-                               $fld->name = $rs->fields[0];
-                               $type = $rs->fields[1];
-                               
-                               
-                               // split type into type(length):
-                               $fld->scale = null;
-                               if (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
-                                       $fld->type = $query_array[1];
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
-                                       $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
-                               } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
-                                       $fld->type = $query_array[1];
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
-                               } else {
-                                       $fld->max_length = -1;
-                                       $fld->type = $type;
-                               }
-                               /*
-                               // split type into type(length):
-                               if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
-                                       $fld->type = $query_array[1];
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
-                               } else {
-                                       $fld->max_length = -1;
-                                       $fld->type = $type;
-                               }*/
-                               $fld->not_null = ($rs->fields[2] != 'YES');
-                               $fld->primary_key = ($rs->fields[3] == 'PRI');
-                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
-                               $fld->binary = (strpos($fld->type,'blob') !== false);
-                               
-                               if (!$fld->binary) {
-                                       $d = $rs->fields[4];
-                                       if ($d != "" && $d != "NULL") {
-                                               $fld->has_default = true;
-                                               $fld->default_value = $d;
-                                       } else {
-                                               $fld->has_default = false;
-                                       }
-                               }
-                               if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; 
-                               else $retarr[strtoupper($fld->name)] = $fld;
-                               $rs->MoveNext();
-                       }
-                       $rs->Close();
-                       return $retarr; 
-               }
-               return false;
-       }
-               
-       // returns true or false
-       function SelectDB($dbName) 
-       {
-               $this->databaseName = $dbName;
-               if ($this->_connectionID) {
-                       return @mysql_select_db($dbName,$this->_connectionID);          
-               }
-               else return false;      
-       }
-       
-       // parameters use PostgreSQL convention, not MySQL
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
-       {
-               $offsetStr =($offset>=0) ? "$offset," : '';
-               
-               if ($secs)
-                       $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
-               else
-                       $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
-               return $rs;
-       }
-       
-       
-       // returns queryID or false
-       function _query($sql,$inputarr)
-       {
-       //global $ADODB_COUNTRECS;
-               //if($ADODB_COUNTRECS) 
-               return mysql_query($sql,$this->_connectionID);
-               //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
-       }
-
-       /*      Returns: the last error message from previous database operation        */      
-       function ErrorMsg() 
-       {
-       
-               if ($this->_logsql) return $this->_errorMsg;
-               if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
-               else $this->_errorMsg = @mysql_error($this->_connectionID);
-               return $this->_errorMsg;
-       }
-       
-       /*      Returns: the last error number from previous database operation */      
-       function ErrorNo() 
-       {
-               if ($this->_logsql) return $this->_errorCode;
-               if (empty($this->_connectionID))  return @mysql_errno();
-               else return @mysql_errno($this->_connectionID);
-       }
-       
-
-       
-       // returns true or false
-       function _close()
-       {
-               @mysql_close($this->_connectionID);
-               $this->_connectionID = false;
-       }
-
-       
-       /*
-       * Maximum size of C field
-       */
-       function CharMax()
-       {
-               return 255; 
-       }
-       
-       /*
-       * Maximum size of X field
-       */
-       function TextMax()
-       {
-               return 4294967295; 
-       }
-       
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_mysql extends ADORecordSet{ 
-       
-       var $databaseType = "mysql";
-       var $canSeek = true;
-       
-       function ADORecordSet_mysql($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;
-               default:
-               case ADODB_FETCH_DEFAULT:
-               case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
-               }
-       
-               $this->ADORecordSet($queryID);  
-       }
-       
-       function _initrs()
-       {
-       //GLOBAL $ADODB_COUNTRECS;
-       //      $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
-               $this->_numOfRows = @mysql_num_rows($this->_queryID);
-               $this->_numOfFields = @mysql_num_fields($this->_queryID);
-       }
-       
-       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)
-                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
-                       $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)
-                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
-               }
-                       
-               return $o;
-       }
-
-       function &GetRowAssoc($upper=true)
-       {
-               if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;
-               $row =& ADORecordSet::GetRowAssoc($upper);
-               return $row;
-       }
-       
-       /* Use associative array to get fields array */
-       function Fields($colname)
-       {       
-               // added @ by "Michael William Miller" <mille562@pilot.msu.edu>
-               if ($this->fetchMode != MYSQL_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)]];
-       }
-       
-       function _seek($row)
-       {
-               if ($this->_numOfRows == 0) return false;
-               return @mysql_data_seek($this->_queryID,$row);
-       }
-       
-       
-       // 10% speedup to move MoveNext to child class
-       function MoveNext() 
-       {
-       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);
-       
-               if ($this->EOF) return false;
-                               
-               $this->_currentRow++;
-               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
-               if (is_array($this->fields)) return true;
-               
-               $this->EOF = true;
-               
-               /* -- tested raising an error -- appears pointless
-               $conn = $this->connection;
-               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
-                       $fn = $conn->raiseErrorFn;
-                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
-               }
-               */
-               return false;
-       }       
-       
-       function _fetch()
-       {
-               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
-               return is_array($this->fields);
-       }
-       
-       function _close() {
-               @mysql_free_result($this->_queryID);    
-               $this->_queryID = false;        
-       }
-       
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               
-               $len = -1; // mysql max_length is not accurate
-               switch (strtoupper($t)) {
-               case 'STRING': 
-               case 'CHAR':
-               case 'VARCHAR': 
-               case 'TINYBLOB': 
-               case 'TINYTEXT': 
-               case 'ENUM': 
-               case 'SET': 
-                       if ($len <= $this->blobSize) return 'C';
-                       
-               case 'TEXT':
-               case 'LONGTEXT': 
-               case 'MEDIUMTEXT':
-                       return 'X';
-                       
-               // php_mysql extension always returns 'blob' even if 'text'
-               // so we have to check whether binary...
-               case 'IMAGE':
-               case 'LONGBLOB': 
-               case 'BLOB':
-               case 'MEDIUMBLOB':
-                       return !empty($fieldobj->binary) ? 'B' : 'X';
-                       
-               case 'YEAR':
-               case 'DATE': return 'D';
-               
-               case 'TIME':
-               case 'DATETIME':
-               case 'TIMESTAMP': return 'T';
-               
-               case 'INT': 
-               case 'INTEGER':
-               case 'BIGINT':
-               case 'TINYINT':
-               case 'MEDIUMINT':
-               case 'SMALLINT': 
-                       
-                       if (!empty($fieldobj->primary_key)) return 'R';
-                       else return 'I';
-               
-               default: return 'N';
-               }
-       }
-
-}
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.\r
+  Requires mysql client. Works on Windows and Unix.\r
+  \r
+ 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)\r
+*/ \r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (! defined("_ADODB_MYSQL_LAYER")) {\r
+ define("_ADODB_MYSQL_LAYER", 1 );\r
+\r
+class ADODB_mysql extends ADOConnection {\r
+       var $databaseType = 'mysql';\r
+       var $dataProvider = 'mysql';\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;    \r
+       var $metaTablesSQL = "SHOW TABLES";     \r
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasLimit = true;\r
+       var $hasMoveFirst = true;\r
+       var $hasGenID = true;\r
+       var $upperCase = 'upper';\r
+       var $isoDates = true; // accepts dates in ISO format\r
+       var $sysDate = 'CURDATE()';\r
+       var $sysTimeStamp = 'NOW()';\r
+       var $hasTransactions = false;\r
+       var $forceNewConnect = false;\r
+       var $poorAffectedRows = true;\r
+       var $clientFlags = 0;\r
+       var $substr = "substring";\r
+       var $nameQuote = '`';           /// string to use to quote identifiers and names\r
+       \r
+       function ADODB_mysql() \r
+       {                       \r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['description'] = ADOConnection::GetOne("select version()");\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               return $arr;\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " IFNULL($field, $ifNull) "; // if MySQL\r
+       }\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {       \r
+               $save = $this->metaTablesSQL;\r
+               if ($showSchema && is_string($showSchema)) {\r
+                       $this->metaTablesSQL .= " from $showSchema";\r
+               }\r
+               \r
+               if ($mask) {\r
+                       $mask = $this->qstr($mask);\r
+                       $this->metaTablesSQL .= " like $mask";\r
+               }\r
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
+               \r
+               $this->metaTablesSQL = $save;\r
+               return $ret;\r
+       }\r
+       \r
+       \r
+       function &MetaIndexes ($table, $primary = FALSE, $owner=false)\r
+       {\r
+        // save old fetch mode\r
+        global $ADODB_FETCH_MODE;\r
+        \r
+        $save = $ADODB_FETCH_MODE;\r
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+        if ($this->fetchMode !== FALSE) {\r
+               $savem = $this->SetFetchMode(FALSE);\r
+        }\r
+        \r
+        // get index details\r
+        $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));\r
+        \r
+        // restore fetchmode\r
+        if (isset($savem)) {\r
+                $this->SetFetchMode($savem);\r
+        }\r
+        $ADODB_FETCH_MODE = $save;\r
+        \r
+        if (!is_object($rs)) {\r
+                return FALSE;\r
+        }\r
+        \r
+        $indexes = array ();\r
+        \r
+        // parse index data into array\r
+        while ($row = $rs->FetchRow()) {\r
+                if ($primary == FALSE AND $row[2] == 'PRIMARY') {\r
+                        continue;\r
+                }\r
+                \r
+                if (!isset($indexes[$row[2]])) {\r
+                        $indexes[$row[2]] = array(\r
+                                'unique' => ($row[1] == 0),\r
+                                'columns' => array()\r
+                        );\r
+                }\r
+                \r
+                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];\r
+        }\r
+        \r
+        // sort columns by order in the index\r
+        foreach ( array_keys ($indexes) as $index )\r
+        {\r
+                ksort ($indexes[$index]['columns']);\r
+        }\r
+        \r
+        return $indexes;\r
+       }\r
+\r
+       \r
+       // if magic quotes disabled, use mysql_real_escape_string()\r
+       function qstr($s,$magic_quotes=false)\r
+       {\r
+               if (!$magic_quotes) {\r
+               \r
+                       if (ADODB_PHPVER >= 0x4300) {\r
+                               if (is_resource($this->_connectionID))\r
+                                       return "'".mysql_real_escape_string($s,$this->_connectionID)."'";\r
+                       }\r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
+                       }\r
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               return "'$s'";\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+               return mysql_insert_id($this->_connectionID);\r
+       }\r
+       \r
+       function GetOne($sql,$inputarr=false)\r
+       {\r
+               if (strncasecmp($sql,'sele',4) == 0) {\r
+                       $rs =& $this->SelectLimit($sql,1,-1,$inputarr);\r
+                       if ($rs) {\r
+                               $rs->Close();\r
+                               if ($rs->EOF) return false;\r
+                               return reset($rs->fields);\r
+                       }\r
+               } else {\r
+                       return ADOConnection::GetOne($sql,$inputarr);\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+                       return mysql_affected_rows($this->_connectionID);\r
+       }\r
+  \r
+       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html\r
+       // Reference on Last_Insert_ID on the recommended way to simulate sequences\r
+       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";\r
+       var $_genSeqSQL = "create table %s (id int not null)";\r
+       var $_genSeq2SQL = "insert into %s values (%s)";\r
+       var $_dropSeqSQL = "drop table %s";\r
+       \r
+       function CreateSequence($seqname='adodbseq',$startID=1)\r
+       {\r
+               if (empty($this->_genSeqSQL)) return false;\r
+               $u = strtoupper($seqname);\r
+               \r
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+               if (!$ok) return false;\r
+               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
+       }\r
+       \r
+\r
+       function GenID($seqname='adodbseq',$startID=1)\r
+       {\r
+               // post-nuke sets hasGenID to false\r
+               if (!$this->hasGenID) return false;\r
+               \r
+               $savelog = $this->_logsql;\r
+               $this->_logsql = false;\r
+               $getnext = sprintf($this->_genIDSQL,$seqname);\r
+               $holdtransOK = $this->_transOK; // save the current status\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset\r
+                       $u = strtoupper($seqname);\r
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               $this->genID = mysql_insert_id($this->_connectionID);\r
+               \r
+               if ($rs) $rs->Close();\r
+               \r
+               $this->_logsql = $savelog;\r
+               return $this->genID;\r
+       }\r
+       \r
+       function &MetaDatabases()\r
+       {\r
+               $qid = mysql_list_dbs($this->_connectionID);\r
+               $arr = array();\r
+               $i = 0;\r
+               $max = mysql_num_rows($qid);\r
+               while ($i < $max) {\r
+                       $db = mysql_tablename($qid,$i);\r
+                       if ($db != 'mysql') $arr[] = $db;\r
+                       $i += 1;\r
+               }\r
+               return $arr;\r
+       }\r
+       \r
+               \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = 'DATE_FORMAT('.$col.",'";\r
+               $concat = false;\r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= '%Y';\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= "'),Quarter($col)";\r
+                               \r
+                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";\r
+                               else $s .= ",('";\r
+                               $concat = true;\r
+                               break;\r
+                       case 'M':\r
+                               $s .= '%b';\r
+                               break;\r
+                               \r
+                       case 'm':\r
+                               $s .= '%m';\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= '%d';\r
+                               break;\r
+                       \r
+                       case 'H': \r
+                               $s .= '%H';\r
+                               break;\r
+                               \r
+                       case 'h':\r
+                               $s .= '%I';\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= '%i';\r
+                               break;\r
+                               \r
+                       case 's':\r
+                               $s .= '%s';\r
+                               break;\r
+                               \r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= '%p';\r
+                               break;\r
+                               \r
+                       default:\r
+                               \r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $ch;\r
+                               break;\r
+                       }\r
+               }\r
+               $s.="')";\r
+               if ($concat) $s = "CONCAT($s)";\r
+               return $s;\r
+       }\r
+       \r
+\r
+       // returns concatenated string\r
+       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator\r
+       function Concat()\r
+       {\r
+               $s = "";\r
+               $arr = func_get_args();\r
+               \r
+               // suggestion by andrew005@mnogo.ru\r
+               $s = implode(',',$arr); \r
+               if (strlen($s) > 0) return "CONCAT($s)";\r
+               else return '';\r
+       }\r
+       \r
+       function OffsetDate($dayFraction,$date=false)\r
+       {               \r
+               if (!$date) $date = $this->sysDate;\r
+               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";\r
+       }\r
+       \r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (ADODB_PHPVER >= 0x4300)\r
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,\r
+                                                                                               $this->forceNewConnect,$this->clientFlags);\r
+               else if (ADODB_PHPVER >= 0x4200)\r
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,\r
+                                                                                               $this->forceNewConnect);\r
+               else\r
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);\r
+       \r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (ADODB_PHPVER >= 0x4300)\r
+                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);\r
+               else\r
+                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($this->autoRollback) $this->RollbackTrans();\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               $this->forceNewConnect = true;\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);\r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+       \r
+               if ($this->metaColumnsSQL) {\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+                       $save = $ADODB_FETCH_MODE;\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+                       \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
+                       \r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       \r
+                       if ($rs === false) return false;\r
+                       \r
+                       $retarr = array();\r
+                       while (!$rs->EOF){\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $type = $rs->fields[1];\r
+                               \r
+                               \r
+                               // split type into type(length):\r
+                               $fld->scale = null;\r
+                               if (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
+                                       $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;\r
+                               } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
+                               } else {\r
+                                       $fld->max_length = -1;\r
+                                       $fld->type = $type;\r
+                               }\r
+                               /*\r
+                               // split type into type(length):\r
+                               if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {\r
+                                       $fld->type = $query_array[1];\r
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
+                               } else {\r
+                                       $fld->max_length = -1;\r
+                                       $fld->type = $type;\r
+                               }*/\r
+                               $fld->not_null = ($rs->fields[2] != 'YES');\r
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
+                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                               \r
+                               if (!$fld->binary) {\r
+                                       $d = $rs->fields[4];\r
+                                       if ($d != "" && $d != "NULL") {\r
+                                               $fld->has_default = true;\r
+                                               $fld->default_value = $d;\r
+                                       } else {\r
+                                               $fld->has_default = false;\r
+                                       }\r
+                               }\r
+                               if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; \r
+                               else $retarr[strtoupper($fld->name)] = $fld;\r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+               \r
+       // returns true or false\r
+       function SelectDB($dbName) \r
+       {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @mysql_select_db($dbName,$this->_connectionID);          \r
+               }\r
+               else return false;      \r
+       }\r
+       \r
+       // parameters use PostgreSQL convention, not MySQL\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)\r
+       {\r
+               $offsetStr =($offset>=0) ? "$offset," : '';\r
+               // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220\r
+               if ($nrows < 0) $nrows = '18446744073709551615'; \r
+               \r
+               if ($secs)\r
+                       $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);\r
+               else\r
+                       $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);\r
+               return $rs;\r
+       }\r
+       \r
+       \r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+       //global $ADODB_COUNTRECS;\r
+               //if($ADODB_COUNTRECS) \r
+               return mysql_query($sql,$this->_connectionID);\r
+               //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+       \r
+               if ($this->_logsql) return $this->_errorMsg;\r
+               if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();\r
+               else $this->_errorMsg = @mysql_error($this->_connectionID);\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+       {\r
+               if ($this->_logsql) return $this->_errorCode;\r
+               if (empty($this->_connectionID))  return @mysql_errno();\r
+               else return @mysql_errno($this->_connectionID);\r
+       }\r
+       \r
+\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               @mysql_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+       }\r
+\r
+       \r
+       /*\r
+       * Maximum size of C field\r
+       */\r
+       function CharMax()\r
+       {\r
+               return 255; \r
+       }\r
+       \r
+       /*\r
+       * Maximum size of X field\r
+       */\r
+       function TextMax()\r
+       {\r
+               return 4294967295; \r
+       }\r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_mysql extends ADORecordSet{ \r
+       \r
+       var $databaseType = "mysql";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_mysql($queryID,$mode=false) \r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode)\r
+               {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;\r
+               }\r
+       \r
+               $this->ADORecordSet($queryID);  \r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       //GLOBAL $ADODB_COUNTRECS;\r
+       //      $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;\r
+               $this->_numOfRows = @mysql_num_rows($this->_queryID);\r
+               $this->_numOfFields = @mysql_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function &FetchField($fieldOffset = -1) \r
+       {       \r
+               if ($fieldOffset != -1) {\r
+                       $o = @mysql_fetch_field($this->_queryID, $fieldOffset);\r
+                       $f = @mysql_field_flags($this->_queryID,$fieldOffset);\r
+                       $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)\r
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
+                       $o->binary = (strpos($f,'binary')!== false);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @mysql_fetch_field($this->_queryID);\r
+                       $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)\r
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
+               }\r
+                       \r
+               return $o;\r
+       }\r
+\r
+       function &GetRowAssoc($upper=true)\r
+       {\r
+               if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;\r
+               $row =& ADORecordSet::GetRowAssoc($upper);\r
+               return $row;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {       \r
+               // added @ by "Michael William Miller" <mille562@pilot.msu.edu>\r
+               if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];\r
+               \r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+       function _seek($row)\r
+       {\r
+               if ($this->_numOfRows == 0) return false;\r
+               return @mysql_data_seek($this->_queryID,$row);\r
+       }\r
+       \r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);\r
+       \r
+               if ($this->EOF) return false;\r
+                               \r
+               $this->_currentRow++;\r
+               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+               if (is_array($this->fields)) return true;\r
+               \r
+               $this->EOF = true;\r
+               \r
+               /* -- tested raising an error -- appears pointless\r
+               $conn = $this->connection;\r
+               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {\r
+                       $fn = $conn->raiseErrorFn;\r
+                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);\r
+               }\r
+               */\r
+               return false;\r
+       }       \r
+       \r
+       function _fetch()\r
+       {\r
+               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+               return is_array($this->fields);\r
+       }\r
+       \r
+       function _close() {\r
+               @mysql_free_result($this->_queryID);    \r
+               $this->_queryID = false;        \r
+       }\r
+       \r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               $len = -1; // mysql max_length is not accurate\r
+               switch (strtoupper($t)) {\r
+               case 'STRING': \r
+               case 'CHAR':\r
+               case 'VARCHAR': \r
+               case 'TINYBLOB': \r
+               case 'TINYTEXT': \r
+               case 'ENUM': \r
+               case 'SET': \r
+                       if ($len <= $this->blobSize) return 'C';\r
+                       \r
+               case 'TEXT':\r
+               case 'LONGTEXT': \r
+               case 'MEDIUMTEXT':\r
+                       return 'X';\r
+                       \r
+               // php_mysql extension always returns 'blob' even if 'text'\r
+               // so we have to check whether binary...\r
+               case 'IMAGE':\r
+               case 'LONGBLOB': \r
+               case 'BLOB':\r
+               case 'MEDIUMBLOB':\r
+                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
+                       \r
+               case 'YEAR':\r
+               case 'DATE': return 'D';\r
+               \r
+               case 'TIME':\r
+               case 'DATETIME':\r
+               case 'TIMESTAMP': return 'T';\r
+               \r
+               case 'INT': \r
+               case 'INTEGER':\r
+               case 'BIGINT':\r
+               case 'TINYINT':\r
+               case 'MEDIUMINT':\r
+               case 'SMALLINT': \r
+                       \r
+                       if (!empty($fieldobj->primary_key)) return 'R';\r
+                       else return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+\r
+}\r
+}\r
 ?>
\ No newline at end of file
index 28ecd5947933d3fc5fe10cace728da8a05868e85..587083329d0b863862c6a6e4d3b88f4543808c0d 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
-  
-  MySQL code that does not support transactions. Use mysqlt if you need transactions.
-  Requires mysql client. Works on Windows and Unix.
-21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)
-Based on adodb 3.40
-*/ 
-if (! defined("_ADODB_MYSQL_LAYER")) {
- define("_ADODB_MYSQL_LAYER", 1 );
-class ADODB_mysqli extends ADOConnection {
-       var $databaseType = 'mysqli';
-       var $dataProvider = 'native';
-       var $hasInsertID = true;
-       var $hasAffectedRows = true;    
-       var $metaTablesSQL = "SHOW TABLES";     
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       var $hasLimit = true;
-       var $hasMoveFirst = true;
-       var $hasGenID = true;
-       var $upperCase = 'upper';
-       var $isoDates = true; // accepts dates in ISO format
-       var $sysDate = 'CURDATE()';
-       var $sysTimeStamp = 'NOW()';
-       var $hasTransactions = false;
-       var $forceNewConnect = false;
-       var $poorAffectedRows = true;
-       var $clientFlags = 0;
-       var $executeOnly = true;
-       var $substr = "substring";
-       var $nameQuote = '`';           /// string to use to quote identifiers and names
-       //var $_bindInputArray = true;
-       
-       function ADODB_mysqli() 
-       {                       
-         if(!extension_loaded("mysqli"))
-           {
-             trigger_error("You must have the MySQLi extension.", E_USER_ERROR);
-           }
-       }
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " IFNULL($field, $ifNull) "; // if MySQL
-       }
-       
-       function ServerInfo()
-       {
-               $arr['description'] = $this->GetOne("select version()");
-               $arr['version'] = ADOConnection::_findvers($arr['description']);
-               return $arr;
-       }
-       
-       
-       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;
-       }
-       
-       // if magic quotes disabled, use mysql_real_escape_string()
-       // From readme.htm:
-       // Quotes a string to be sent to the database. The $magic_quotes_enabled
-       // parameter may look funny, but the idea is if you are quoting a 
-       // string extracted from a POST/GET variable, then 
-       // pass get_magic_quotes_gpc() as the second parameter. This will 
-       // ensure that the variable is not quoted twice, once by qstr and once 
-       // by the magic_quotes_gpc.
-       //
-       //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());
-       function qstr($s, $magic_quotes = false)
-       {
-         if (!$magic_quotes) {
-           if (ADODB_PHPVER >= 0x5000) {
-           //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
-             return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
-           }
-           else
-             {
-               trigger_error("phpver < 5 not implemented", E_USER_ERROR);
-             }
-           
-           if ($this->replaceQuote[0] == '\\')
-             {
-               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-             }
-           return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
-         }
-         // undo magic quotes for "
-         $s = str_replace('\\"','"',$s);
-         return "'$s'";
-       }
-       
-       function _insertid()
-       {
-//       $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
-         $result = @mysqli_insert_id($this->_connectionID);
-         if ($result == -1){
-             if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());
-         }
-         return $result;
-       }
-       
-       // Only works for INSERT, UPDATE and DELETE query's
-       function _affectedrows()
-       {
-       //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
-         $result =  @mysqli_affected_rows($this->_connectionID);
-         if ($result == -1) {
-             if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());
-         }
-         return $result;
-       }
-  
-       // 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 $_genSeq2SQL = "insert into %s values (%s)";
-       var $_dropSeqSQL = "drop table %s";
-       
-       function CreateSequence($seqname='adodbseq',$startID=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
-               $u = strtoupper($seqname);
-               
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
-               if (!$ok) return false;
-               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
-       }
-       
-       function GenID($seqname='adodbseq',$startID=1)
-       {
-               // post-nuke sets hasGenID to false
-               if (!$this->hasGenID) return false;
-               
-               $getnext = sprintf($this->_genIDSQL,$seqname);
-               $holdtransOK = $this->_transOK; // save the current status
-               $rs = @$this->Execute($getnext);
-               if (!$rs) {
-                       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));
-                       $rs = $this->Execute($getnext);
-               }
-               $this->genID = mysqli_insert_id($this->_connectionID);
-               
-               if ($rs) $rs->Close();
-               
-               return $this->genID;
-       }
-       
-       function &MetaDatabases()
-         {
-           $query = "SHOW DATABASES";
-           $ret =& $this->Execute($query);
-               return $ret;
-         }
-
-         
-       function &MetaIndexes ($table, $primary = FALSE)
-       {
-               // save old fetch mode
-               global $ADODB_FETCH_MODE;
-               
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               if ($this->fetchMode !== FALSE) {
-                      $savem = $this->SetFetchMode(FALSE);
-               }
-               
-               // get index details
-               $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));
-               
-               // restore fetchmode
-               if (isset($savem)) {
-                       $this->SetFetchMode($savem);
-               }
-               $ADODB_FETCH_MODE = $save;
-               
-               if (!is_object($rs)) {
-                       return FALSE;
-               }
-               
-               $indexes = array ();
-               
-               // parse index data into array
-               while ($row = $rs->FetchRow()) {
-                       if ($primary == FALSE AND $row[2] == 'PRIMARY') {
-                               continue;
-                       }
-                       
-                       if (!isset($indexes[$row[2]])) {
-                               $indexes[$row[2]] = array(
-                                       'unique' => ($row[1] == 0),
-                                       'columns' => array()
-                               );
-                       }
-                       
-                       $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
-               }
-               
-               // sort columns by order in the index
-               foreach ( array_keys ($indexes) as $index )
-               {
-                       ksort ($indexes[$index]['columns']);
-               }
-               
-               return $indexes;
-       }
-
-       
-       // 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 = 'DATE_FORMAT('.$col.",'";
-               $concat = false;
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= '%Y';
-                               break;
-                       case 'Q':
-                       case 'q':
-                               $s .= "'),Quarter($col)";
-                               
-                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
-                               else $s .= ",('";
-                               $concat = true;
-                               break;
-                       case 'M':
-                               $s .= '%b';
-                               break;
-                               
-                       case 'm':
-                               $s .= '%m';
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= '%d';
-                               break;
-                       
-                       case 'H': 
-                               $s .= '%H';
-                               break;
-                               
-                       case 'h':
-                               $s .= '%I';
-                               break;
-                               
-                       case 'i':
-                               $s .= '%i';
-                               break;
-                               
-                       case 's':
-                               $s .= '%s';
-                               break;
-                               
-                       case 'a':
-                       case 'A':
-                               $s .= '%p';
-                               break;
-                               
-                       default:
-                               
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               $s .= $ch;
-                               break;
-                       }
-               }
-               $s.="')";
-               if ($concat) $s = "CONCAT($s)";
-               return $s;
-       }
-       
-       // returns concatenated string
-       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
-       function Concat()
-       {
-               $s = "";
-               $arr = func_get_args();
-               
-               // suggestion by andrew005@mnogo.ru
-               $s = implode(',',$arr); 
-               if (strlen($s) > 0) return "CONCAT($s)";
-               else return '';
-       }
-       
-       // 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)";
-       }
-       
-       // returns true or false
-       // To add: parameter int $port,
-       //         parameter string $socket
-       function _connect($argHostname = NULL, 
-                         $argUsername = NULL, 
-                         $argPassword = NULL, 
-                         $argDatabasename = NULL)
-         {
-           // @ means: error surpression on
-           $this->_connectionID = @mysqli_init();
-           
-           if (is_null($this->_connectionID))
-           {
-             // mysqli_init only fails if insufficient memory
-             if ($this->debug) 
-               ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());
-             return false;
-           }
-           // Set connection options
-           // Not implemented now
-           // mysqli_options($this->_connection,,);
-           if (mysqli_real_connect($this->_connectionID,
-                                   $argHostname,
-                                   $argUsername,
-                                   $argPassword,
-                                   $argDatabasename))
-             {
-               if ($argDatabasename) 
-                 {
-                   return $this->SelectDB($argDatabasename);
-                 }
-               
-               return true;
-             }
-           else
-             {
-               if ($this->debug) 
-                 ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
-               return false;
-             }
-         }
-       
-       // returns true or false
-       // How to force a persistent connection
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-         {
-           // not implemented in mysqli (yet)?
-           $this->_connectionID = mysqli_connect($argHostname,
-                                                 $argUsername,
-                                                 $argPassword,
-                                                 $argDatabasename);
-           if ($this->_connectionID === false) return false;
-           //      if ($this->autoRollback) $this->RollbackTrans();
-           if ($argDatabasename) return $this->SelectDB($argDatabasename);
-           return true;        
-         }
-       
-       // When is this used? Close old connection first?
-       // In _connect(), check $this->forceNewConnect? 
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-         {
-           $this->forceNewConnect = true;
-           $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
-         }
-       
-       function &MetaColumns($table) 
-       {
-         if ($this->metaColumnsSQL) {
-           global $ADODB_FETCH_MODE;
-           $save = $ADODB_FETCH_MODE;
-           $rs = false;
-           switch($ADODB_FETCH_MODE)
-             {
-             case ADODB_FETCH_NUM:
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,
-                                            $table));
-               
-               $ADODB_FETCH_MODE = $save;
-               if ($rs === false) break;
-               $retarr = array();
-               while (!$rs->EOF){
-                 $fld = new ADOFieldObject();
-                 $fld->name = $rs->fields[0];
-                 $fld->type = $rs->fields[1];
-                 // split type into type(length):
-                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
-                   {
-                     $fld->type = $query_array[1];
-                     $fld->max_length = $query_array[2];
-                   }
-                 else
-                   {
-                     $fld->max_length = -1;
-                   }
-                 $fld->not_null = ($rs->fields[2] != 'YES');
-                 $fld->primary_key = ($rs->fields[3] == 'PRI');
-                 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
-                 $fld->binary = (strpos($fld->type,'blob') !== false);
-                 if (!$fld->binary) 
-                   {
-                     $d = $rs->fields[4];
-                     $d = $rs->fields['Default'];
-                     if ($d != "" && $d != "NULL")
-                       {
-                         $fld->has_default = true;
-                         $fld->default_value = $d;
-                       } 
-                     else 
-                       {
-                         $fld->has_default = false;
-                       }
-                   }
-                 $retarr[strtoupper($fld->name)] = $fld;       
-                 $rs->MoveNext();
-               }
-               break;
-             case ADODB_FETCH_ASSOC:
-             case ADODB_FETCH_DEFAULT:
-             case ADODB_FETCH_BOTH:
-               $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,
-                                            $table));
-               $ADODB_FETCH_MODE = $save;
-               if ($rs === false) break;
-               $retarr = array();
-               while (!$rs->EOF){
-                 $fld = new ADOFieldObject();
-                 $fld->name = $rs->fields['Field'];
-                 $fld->type = $rs->fields['Type'];
-                               
-                 // split type into type(length):
-                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
-                   {
-                     $fld->type = $query_array[1];
-                     $fld->max_length = $query_array[2];
-                   }
-                 else
-                   {
-                     $fld->max_length = -1;
-                   }
-                 $fld->not_null = ($rs->fields['Null'] != 'YES');
-                 $fld->primary_key = ($rs->fields['Key'] == 'PRI');
-                 $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false);
-                 $fld->binary = (strpos($fld->type,'blob') !== false);
-                 if (!$fld->binary) 
-                   {
-                     $d = $rs->fields['Default'];
-                     if ($d != "" && $d != "NULL")
-                       {
-                         $fld->has_default = true;
-                         $fld->default_value = $d;
-                       } 
-                     else 
-                       {
-                         $fld->has_default = false;
-                       }
-                   }
-                 $retarr[strtoupper($fld->name)] = $fld;       
-                 $rs->MoveNext();
-               }
-               break;
-             default:
-             }
-           
-           if ($rs === false) return false;
-           $rs->Close();
-           return $retarr;     
-         }
-         return false;
-       }
-               
-       // returns true or false
-       function SelectDB($dbName) 
-       {
-//         $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
-           $this->databaseName = $dbName;
-           if ($this->_connectionID) {
-               $result = @mysqli_select_db($this->_connectionID, $dbName);
-                       if (!$result) {
-                       ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
-                       }
-                       return $result;         
-               }
-           return false;       
-       }
-       
-       // parameters use PostgreSQL convention, not MySQL
-       function &SelectLimit($sql,
-                             $nrows = -1,
-                             $offset = -1,
-                             $inputarr = false, 
-                             $arg3 = false,
-                             $secs = 0)
-       {
-               $offsetStr = ($offset >= 0) ? "$offset," : '';
-               
-               if ($secs)
-                       $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
-               else
-                       $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
-                       
-               return $rs;
-       }
-       
-       
-       function Prepare($sql)
-       {
-               return $sql;
-               
-               $stmt = mysqli_prepare($this->_connectionID,$sql);
-               if (!$stmt) return false;
-               return array($sql,$stmt);
-       }
-       
-       
-       // returns queryID or false
-       function _query($sql, $inputarr)
-       {
-       global $ADODB_COUNTRECS;
-       
-               if (is_array($sql)) {
-                       $stmt = $sql[1];
-                       foreach($inputarr as $k => $v) {
-                               if (is_string($v)) $a[] = MYSQLI_BIND_STRING;
-                               else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; 
-                               else $a[] = MYSQLI_BIND_DOUBLE;
-                               
-                               $fnarr =& array_merge( array($stmt,$a) , $inputarr);
-                               $ret = call_user_func_array('mysqli_bind_param',$fnarr);
-                       }
-                       $ret = mysqli_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;
-       }
-
-       /*      Returns: the last error message from previous database operation        */      
-       function ErrorMsg() 
-         {
-           if (empty($this->_connectionID)) 
-             $this->_errorMsg = @mysqli_error();
-           else 
-             $this->_errorMsg = @mysqli_error($this->_connectionID);
-           return $this->_errorMsg;
-         }
-       
-       /*      Returns: the last error number from previous database operation */      
-       function ErrorNo() 
-         {
-           if (empty($this->_connectionID))  
-             return @mysqli_errno();
-           else 
-             return @mysqli_errno($this->_connectionID);
-         }
-       
-       // returns true or false
-       function _close()
-         {
-           @mysqli_close($this->_connectionID);
-           $this->_connectionID = false;
-         }
-
-       /*
-       * Maximum size of C field
-       */
-       function CharMax()
-       {
-               return 255; 
-       }
-       
-       /*
-       * Maximum size of X field
-       */
-       function TextMax()
-       {
-         return 4294967295; 
-       }
-
-
-}
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_mysqli extends ADORecordSet{        
-       
-       var $databaseType = "mysqli";
-       var $canSeek = true;
-       
-       function ADORecordSet_mysqli($queryID, $mode = false) 
-       {
-         if ($mode === false) 
-           { 
-             global $ADODB_FETCH_MODE;
-             $mode = $ADODB_FETCH_MODE;
-           }
-         switch ($mode)
-           {
-           case ADODB_FETCH_NUM: 
-             $this->fetchMode = MYSQLI_NUM; 
-             break;
-           case ADODB_FETCH_ASSOC:
-             $this->fetchMode = MYSQLI_ASSOC; 
-             break;
-           case ADODB_FETCH_DEFAULT:
-           case ADODB_FETCH_BOTH:
-           default:
-             $this->fetchMode = MYSQLI_ASSOC; 
-             break;
-           }
-         $this->ADORecordSet($queryID);        
-       }
-       
-       function _initrs()
-       {
-           // mysqli_num_rows only return correct number, depens
-           // on the use of mysql_store_result and mysql_use_result
-           if (!$this->Connection->executeOnly) {
-                       $this->_numOfRows = @mysqli_num_rows($this->_queryID);
-                       $this->_numOfFields = @mysqli_num_fields($this->_queryID);
-           }
-           else {
-                       $this->_numOfRows = 0;
-                       $this->_numOfFields = 0;
-           }
-       }
-       
-       function &FetchField($fieldOffset = -1) 
-       {       
-         $fieldnr = $fieldOffset;
-         if ($fieldOffset != -1) {
-           $fieldOffset = mysqi_field_seek($this->_queryID, $fieldnr);
-         }
-         $o = mysqli_fetch_field($this->_queryID);
-         return $o;
-       }
-
-       function &GetRowAssoc($upper = true)
-       {
-         if ($this->fetchMode == MYSQLI_ASSOC && !$upper) 
-           return $this->fields;
-         $row =& ADORecordSet::GetRowAssoc($upper);
-         return $row;
-       }
-       
-       /* Use associative array to get fields array */
-       function Fields($colname)
-       {       
-         if ($this->fetchMode != MYSQLI_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)]];
-       }
-       
-       function _seek($row)
-       {
-         if ($this->_numOfRows == 0) 
-           return false;
-
-         if ($row < 0)
-           return false;
-
-         mysqli_data_seek($this->_queryID, $row);
-         $this->EOF = false;
-         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.
-       function MoveNext() 
-       {
-         if ($this->EOF) 
-           return false;
-         $this->_currentRow++;
-         switch($this->fetchMode)
-           {
-           case MYSQLI_NUM:
-             $this->fields = mysqli_fetch_array($this->_queryID);
-             break;
-           case MYSQLI_ASSOC:
-           case MYSQLI_BOTH:
-             $this->fields = mysqli_fetch_assoc($this->_queryID);
-             break;
-           default:
-           }
-         if (is_array($this->fields)) 
-           return true;
-         $this->EOF = true;
-         return false;
-       }       
-       
-       function _fetch()
-       {
-         // mysqli_fetch_array($this->_queryID, MYSQLI_NUM) does not
-         // work (22-10-2003). But mysqli_fetch_array($this->_queryID) gives
-         // int resulttype should default to MYSQLI_BOTH,but give MYSQLI_NUM.
-
-         //      $this->fields =  mysqli_fetch_fields($this->_queryID);
-         //      $this->fields =  mysqli_fetch_array($this->_queryID); //, $this->fetchMode);
-                 
-         $this->fields =  mysqli_fetch_assoc($this->_queryID); // $this->fetchMode);
-         return is_array($this->fields);
-       }
-       
-       function _close() 
-       {
-         mysqli_free_result($this->_queryID); 
-         $this->_queryID = false;      
-       }
-       
-       function MetaType($t, $len = -1, $fieldobj = false)
-       {
-         if (is_object($t)) 
-           {
-             $fieldobj = $t;
-             $t = $fieldobj->type;
-             $len = $fieldobj->max_length;
-           }
-               
-         $len = -1; // mysql max_length is not accurate
-         switch (strtoupper($t)) {
-         case 'STRING': 
-         case 'CHAR':
-         case 'VARCHAR': 
-         case 'TINYBLOB': 
-         case 'TINYTEXT': 
-         case 'ENUM': 
-         case 'SET': 
-           if ($len <= $this->blobSize) return 'C';
-           
-         case 'TEXT':
-         case 'LONGTEXT': 
-         case 'MEDIUMTEXT':
-           return 'X';
-                       
-           // php_mysql extension always returns 'blob' even if 'text'
-           // so we have to check whether binary...
-         case 'IMAGE':
-         case 'LONGBLOB': 
-         case 'BLOB':
-         case 'MEDIUMBLOB':
-           return !empty($fieldobj->binary) ? 'B' : 'X';
-         case 'YEAR':
-         case 'DATE': 
-           return 'D';
-               
-         case 'TIME':
-         case 'DATETIME':
-         case 'TIMESTAMP': return 'T';
-               
-         case 'INT': 
-         case 'INTEGER':
-         case 'BIGINT':
-         case 'TINYINT':
-         case 'MEDIUMINT':
-         case 'SMALLINT': 
-                       
-           if (!empty($fieldobj->primary_key)) return 'R';
-           else return 'I';
-           // Added floating-point types
-           // Maybe not necessery.
-         case 'FLOAT':
-         case 'DOUBLE':
-           //          case 'DOUBLE PRECISION':
-         case 'DECIMAL':
-         case 'DEC':
-         case 'FIXED':
-         default: 
-           return 'N';
-         }
-       }
-       
-
-}
-}
-
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.\r
+  Requires mysql client. Works on Windows and Unix.\r
\r
+21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)\r
+Based on adodb 3.40\r
+*/ \r
+\r
+// security - hide paths\r
+//if (!defined('ADODB_DIR')) die();\r
+\r
+if (! defined("_ADODB_MYSQLI_LAYER")) {\r
+ define("_ADODB_MYSQLI_LAYER", 1 );\r
\r
+class ADODB_mysqli extends ADOConnection {\r
+       var $databaseType = 'mysqli';\r
+       var $dataProvider = 'native';\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;    \r
+       var $metaTablesSQL = "SHOW TABLES";     \r
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasLimit = true;\r
+       var $hasMoveFirst = true;\r
+       var $hasGenID = true;\r
+       var $upperCase = 'upper';\r
+       var $isoDates = true; // accepts dates in ISO format\r
+       var $sysDate = 'CURDATE()';\r
+       var $sysTimeStamp = 'NOW()';\r
+       var $hasTransactions = false;\r
+       var $forceNewConnect = false;\r
+       var $poorAffectedRows = true;\r
+       var $clientFlags = 0;\r
+       var $substr = "substring";\r
+       //var $poorAffectedRows = true;\r
+       var $nameQuote = '`';           /// string to use to quote identifiers and names\r
+       //var $_bindInputArray = true;\r
+       \r
+       function ADODB_mysqli() \r
+       {                       \r
+         if(!extension_loaded("mysqli"))\r
+           {\r
+             trigger_error("You must have the MySQLi extension.", E_USER_ERROR);\r
+           }\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " IFNULL($field, $ifNull) "; // if MySQL\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['description'] = $this->GetOne("select version()");\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               return $arr;\r
+       }\r
+       \r
+       \r
+       function BeginTrans()\r
+       {         \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->Execute('SET AUTOCOMMIT=0');\r
+               $this->Execute('BEGIN');\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       {\r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('COMMIT');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('ROLLBACK');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+       // if magic quotes disabled, use mysql_real_escape_string()\r
+       // From readme.htm:\r
+       // Quotes a string to be sent to the database. The $magic_quotes_enabled\r
+       // parameter may look funny, but the idea is if you are quoting a \r
+       // string extracted from a POST/GET variable, then \r
+       // pass get_magic_quotes_gpc() as the second parameter. This will \r
+       // ensure that the variable is not quoted twice, once by qstr and once \r
+       // by the magic_quotes_gpc.\r
+       //\r
+       //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());\r
+       function qstr($s, $magic_quotes = false)\r
+       {\r
+               if (!$magic_quotes) {\r
+               if (PHP_VERSION >= 5)\r
+                       return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";   \r
+           \r
+               if ($this->replaceQuote[0] == '\\')\r
+                       $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
+           return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
+         }\r
+         // undo magic quotes for "\r
+         $s = str_replace('\\"','"',$s);\r
+         return "'$s'";\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+//       $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
+         $result = @mysqli_insert_id($this->_connectionID);\r
+         if ($result == -1){\r
+             if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());\r
+         }\r
+         return $result;\r
+       }\r
+       \r
+       // Only works for INSERT, UPDATE and DELETE query's\r
+       function _affectedrows()\r
+       {\r
+       //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
+         $result =  @mysqli_affected_rows($this->_connectionID);\r
+         if ($result == -1) {\r
+             if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());\r
+         }\r
+         return $result;\r
+       }\r
+  \r
+       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html\r
+       // Reference on Last_Insert_ID on the recommended way to simulate sequences\r
+       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";\r
+       var $_genSeqSQL = "create table %s (id int not null)";\r
+       var $_genSeq2SQL = "insert into %s values (%s)";\r
+       var $_dropSeqSQL = "drop table %s";\r
+       \r
+       function CreateSequence($seqname='adodbseq',$startID=1)\r
+       {\r
+               if (empty($this->_genSeqSQL)) return false;\r
+               $u = strtoupper($seqname);\r
+               \r
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+               if (!$ok) return false;\r
+               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
+       }\r
+       \r
+       function GenID($seqname='adodbseq',$startID=1)\r
+       {\r
+               // post-nuke sets hasGenID to false\r
+               if (!$this->hasGenID) return false;\r
+               \r
+               $getnext = sprintf($this->_genIDSQL,$seqname);\r
+               $holdtransOK = $this->_transOK; // save the current status\r
+               $rs = @$this->Execute($getnext);\r
+               if (!$rs) {\r
+                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset\r
+                       $u = strtoupper($seqname);\r
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
+                       $rs = $this->Execute($getnext);\r
+               }\r
+               $this->genID = mysqli_insert_id($this->_connectionID);\r
+               \r
+               if ($rs) $rs->Close();\r
+               \r
+               return $this->genID;\r
+       }\r
+       \r
+       function &MetaDatabases()\r
+         {\r
+           $query = "SHOW DATABASES";\r
+           $ret =& $this->Execute($query);\r
+               return $ret;\r
+         }\r
+\r
+         \r
+       function &MetaIndexes ($table, $primary = FALSE)\r
+       {\r
+               // save old fetch mode\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               if ($this->fetchMode !== FALSE) {\r
+                      $savem = $this->SetFetchMode(FALSE);\r
+               }\r
+               \r
+               // get index details\r
+               $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));\r
+               \r
+               // restore fetchmode\r
+               if (isset($savem)) {\r
+                       $this->SetFetchMode($savem);\r
+               }\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               if (!is_object($rs)) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               $indexes = array ();\r
+               \r
+               // parse index data into array\r
+               while ($row = $rs->FetchRow()) {\r
+                       if ($primary == FALSE AND $row[2] == 'PRIMARY') {\r
+                               continue;\r
+                       }\r
+                       \r
+                       if (!isset($indexes[$row[2]])) {\r
+                               $indexes[$row[2]] = array(\r
+                                       'unique' => ($row[1] == 0),\r
+                                       'columns' => array()\r
+                               );\r
+                       }\r
+                       \r
+                       $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];\r
+               }\r
+               \r
+               // sort columns by order in the index\r
+               foreach ( array_keys ($indexes) as $index )\r
+               {\r
+                       ksort ($indexes[$index]['columns']);\r
+               }\r
+               \r
+               return $indexes;\r
+       }\r
+\r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = 'DATE_FORMAT('.$col.",'";\r
+               $concat = false;\r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= '%Y';\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= "'),Quarter($col)";\r
+                               \r
+                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";\r
+                               else $s .= ",('";\r
+                               $concat = true;\r
+                               break;\r
+                       case 'M':\r
+                               $s .= '%b';\r
+                               break;\r
+                               \r
+                       case 'm':\r
+                               $s .= '%m';\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= '%d';\r
+                               break;\r
+                       \r
+                       case 'H': \r
+                               $s .= '%H';\r
+                               break;\r
+                               \r
+                       case 'h':\r
+                               $s .= '%I';\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= '%i';\r
+                               break;\r
+                               \r
+                       case 's':\r
+                               $s .= '%s';\r
+                               break;\r
+                               \r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= '%p';\r
+                               break;\r
+                               \r
+                       default:\r
+                               \r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $ch;\r
+                               break;\r
+                       }\r
+               }\r
+               $s.="')";\r
+               if ($concat) $s = "CONCAT($s)";\r
+               return $s;\r
+       }\r
+       \r
+       // returns concatenated string\r
+       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator\r
+       function Concat()\r
+       {\r
+               $s = "";\r
+               $arr = func_get_args();\r
+               \r
+               // suggestion by andrew005@mnogo.ru\r
+               $s = implode(',',$arr); \r
+               if (strlen($s) > 0) return "CONCAT($s)";\r
+               else return '';\r
+       }\r
+       \r
+       // dayFraction is a day in floating point\r
+       function OffsetDate($dayFraction,$date=false)\r
+       {               \r
+               if (!$date) \r
+                 $date = $this->sysDate;\r
+               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";\r
+       }\r
+       \r
+       // returns true or false\r
+       // To add: parameter int $port,\r
+       //         parameter string $socket\r
+       function _connect($argHostname = NULL, \r
+                         $argUsername = NULL, \r
+                         $argPassword = NULL, \r
+                         $argDatabasename = NULL)\r
+         {\r
+           // @ means: error surpression on\r
+           $this->_connectionID = @mysqli_init();\r
+           \r
+           if (is_null($this->_connectionID))\r
+           {\r
+             // mysqli_init only fails if insufficient memory\r
+             if ($this->debug) \r
+               ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());\r
+             return false;\r
+           }\r
+           // Set connection options\r
+           // Not implemented now\r
+           // mysqli_options($this->_connection,,);\r
+           if (mysqli_real_connect($this->_connectionID,\r
+                                   $argHostname,\r
+                                   $argUsername,\r
+                                   $argPassword,\r
+                                   $argDatabasename))\r
+             {\r
+               if ($argDatabasename) \r
+                 {\r
+                   return $this->SelectDB($argDatabasename);\r
+                 }\r
+               \r
+               return true;\r
+             }\r
+           else\r
+             {\r
+               if ($this->debug) \r
+                 ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());\r
+               return false;\r
+             }\r
+         }\r
+       \r
+       // returns true or false\r
+       // How to force a persistent connection\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+         {\r
+           // not implemented in mysqli (yet)?\r
+           $this->_connectionID = mysqli_connect($argHostname,\r
+                                                 $argUsername,\r
+                                                 $argPassword,\r
+                                                 $argDatabasename);\r
+           if ($this->_connectionID === false) return false;\r
+           //      if ($this->autoRollback) $this->RollbackTrans();\r
+           if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+           return true;        \r
+         }\r
+       \r
+       // When is this used? Close old connection first?\r
+       // In _connect(), check $this->forceNewConnect? \r
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+         {\r
+           $this->forceNewConnect = true;\r
+           $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);\r
+         }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+         if ($this->metaColumnsSQL) {\r
+           global $ADODB_FETCH_MODE;\r
+           $save = $ADODB_FETCH_MODE;\r
+           $rs = false;\r
+           switch($ADODB_FETCH_MODE)\r
+             {\r
+             case ADODB_FETCH_NUM:\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,\r
+                                            $table));\r
+               \r
+               $ADODB_FETCH_MODE = $save;\r
+               if ($rs === false) break;\r
+               $retarr = array();\r
+               while (!$rs->EOF){\r
+                 $fld = new ADOFieldObject();\r
+                 $fld->name = $rs->fields[0];\r
+                 $fld->type = $rs->fields[1];\r
+                 // split type into type(length):\r
+                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))\r
+                   {\r
+                     $fld->type = $query_array[1];\r
+                     $fld->max_length = $query_array[2];\r
+                   }\r
+                 else\r
+                   {\r
+                     $fld->max_length = -1;\r
+                   }\r
+                 $fld->not_null = ($rs->fields[2] != 'YES');\r
+                 $fld->primary_key = ($rs->fields[3] == 'PRI');\r
+                 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
+                 $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                 if (!$fld->binary) \r
+                   {\r
+                     $d = $rs->fields[4];\r
+                     $d = $rs->fields['Default'];\r
+                     if ($d != "" && $d != "NULL")\r
+                       {\r
+                         $fld->has_default = true;\r
+                         $fld->default_value = $d;\r
+                       } \r
+                     else \r
+                       {\r
+                         $fld->has_default = false;\r
+                       }\r
+                   }\r
+                 $retarr[strtoupper($fld->name)] = $fld;       \r
+                 $rs->MoveNext();\r
+               }\r
+               break;\r
+             case ADODB_FETCH_ASSOC:\r
+             case ADODB_FETCH_DEFAULT:\r
+             case ADODB_FETCH_BOTH:\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,\r
+                                            $table));\r
+               $ADODB_FETCH_MODE = $save;\r
+               if ($rs === false) break;\r
+               $retarr = array();\r
+               while (!$rs->EOF){\r
+                 $fld = new ADOFieldObject();\r
+                 $fld->name = $rs->fields['Field'];\r
+                 $fld->type = $rs->fields['Type'];\r
+                               \r
+                 // split type into type(length):\r
+                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))\r
+                   {\r
+                     $fld->type = $query_array[1];\r
+                     $fld->max_length = $query_array[2];\r
+                   }\r
+                 else\r
+                   {\r
+                     $fld->max_length = -1;\r
+                   }\r
+                 $fld->not_null = ($rs->fields['Null'] != 'YES');\r
+                 $fld->primary_key = ($rs->fields['Key'] == 'PRI');\r
+                 $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false);\r
+                 $fld->binary = (strpos($fld->type,'blob') !== false);\r
+                 if (!$fld->binary) \r
+                   {\r
+                     $d = $rs->fields['Default'];\r
+                     if ($d != "" && $d != "NULL")\r
+                       {\r
+                         $fld->has_default = true;\r
+                         $fld->default_value = $d;\r
+                       } \r
+                     else \r
+                       {\r
+                         $fld->has_default = false;\r
+                       }\r
+                   }\r
+                 $retarr[strtoupper($fld->name)] = $fld;       \r
+                 $rs->MoveNext();\r
+               }\r
+               break;\r
+             default:\r
+             }\r
+           \r
+           if ($rs === false) return false;\r
+           $rs->Close();\r
+           return $retarr;     \r
+         }\r
+         return false;\r
+       }\r
+               \r
+       // returns true or false\r
+       function SelectDB($dbName) \r
+       {\r
+//         $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
+           $this->databaseName = $dbName;\r
+           if ($this->_connectionID) {\r
+               $result = @mysqli_select_db($this->_connectionID, $dbName);\r
+                       if (!$result) {\r
+                       ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());\r
+                       }\r
+                       return $result;         \r
+               }\r
+           return false;       \r
+       }\r
+       \r
+       // parameters use PostgreSQL convention, not MySQL\r
+       function &SelectLimit($sql,\r
+                             $nrows = -1,\r
+                             $offset = -1,\r
+                             $inputarr = false, \r
+                             $arg3 = false,\r
+                             $secs = 0)\r
+       {\r
+               $offsetStr = ($offset >= 0) ? "$offset," : '';\r
+               \r
+               if ($secs)\r
+                       $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);\r
+               else\r
+                       $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);\r
+                       \r
+               return $rs;\r
+       }\r
+       \r
+       \r
+       function Prepare($sql)\r
+       {\r
+               return $sql;\r
+               \r
+               $stmt = mysqli_prepare($this->_connectionID,$sql);\r
+               if (!$stmt) return false;\r
+               return array($sql,$stmt);\r
+       }\r
+       \r
+       \r
+       // returns queryID or false\r
+       function _query($sql, $inputarr)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               if (is_array($sql)) {\r
+                       $stmt = $sql[1];\r
+                       foreach($inputarr as $k => $v) {\r
+                               if (is_string($v)) $a[] = MYSQLI_BIND_STRING;\r
+                               else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; \r
+                               else $a[] = MYSQLI_BIND_DOUBLE;\r
+                               \r
+                               $fnarr =& array_merge( array($stmt,$a) , $inputarr);\r
+                               $ret = call_user_func_array('mysqli_bind_param',$fnarr);\r
+                       }\r
+                       $ret = mysqli_execute($stmt);\r
+                       return $ret;\r
+               }\r
+               if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {\r
+                   if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());\r
+                   return false;\r
+               }\r
+               \r
+               return $mysql_res;\r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+         {\r
+           if (empty($this->_connectionID)) \r
+             $this->_errorMsg = @mysqli_error();\r
+           else \r
+             $this->_errorMsg = @mysqli_error($this->_connectionID);\r
+           return $this->_errorMsg;\r
+         }\r
+       \r
+       /*      Returns: the last error number from previous database operation */      \r
+       function ErrorNo() \r
+         {\r
+           if (empty($this->_connectionID))  \r
+             return @mysqli_errno();\r
+           else \r
+             return @mysqli_errno($this->_connectionID);\r
+         }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+         {\r
+           @mysqli_close($this->_connectionID);\r
+           $this->_connectionID = false;\r
+         }\r
+\r
+       /*\r
+       * Maximum size of C field\r
+       */\r
+       function CharMax()\r
+       {\r
+               return 255; \r
+       }\r
+       \r
+       /*\r
+       * Maximum size of X field\r
+       */\r
+       function TextMax()\r
+       {\r
+         return 4294967295; \r
+       }\r
+\r
+\r
+}\r
\r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_mysqli extends ADORecordSet{        \r
+       \r
+       var $databaseType = "mysqli";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_mysqli($queryID, $mode = false) \r
+       {\r
+         if ($mode === false) \r
+          { \r
+             global $ADODB_FETCH_MODE;\r
+             $mode = $ADODB_FETCH_MODE;\r
+          }\r
+          \r
+         switch ($mode)\r
+           {\r
+           case ADODB_FETCH_NUM: \r
+             $this->fetchMode = MYSQLI_NUM; \r
+             break;\r
+           case ADODB_FETCH_ASSOC:\r
+             $this->fetchMode = MYSQLI_ASSOC; \r
+             break;\r
+           case ADODB_FETCH_DEFAULT:\r
+           case ADODB_FETCH_BOTH:\r
+           default:\r
+             $this->fetchMode = MYSQLI_BOTH; \r
+             break;\r
+           }\r
+         \r
+         $this->ADORecordSet($queryID);        \r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               $this->_numOfRows = $ADODB_COUNTRECS ? @mysqli_num_rows($this->_queryID) : -1;\r
+               $this->_numOfFields = @mysqli_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function &FetchField($fieldOffset = -1) \r
+       {       \r
+         $fieldnr = $fieldOffset;\r
+         if ($fieldOffset != -1) {\r
+           $fieldOffset = mysqli_field_seek($this->_queryID, $fieldnr);\r
+         }\r
+         $o = mysqli_fetch_field($this->_queryID);\r
+         return $o;\r
+       }\r
+\r
+       function &GetRowAssoc($upper = true)\r
+       {\r
+         if ($this->fetchMode == MYSQLI_ASSOC && !$upper) \r
+           return $this->fields;\r
+         $row =& ADORecordSet::GetRowAssoc($upper);\r
+         return $row;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {       \r
+         if ($this->fetchMode != MYSQLI_NUM) \r
+           return @$this->fields[$colname];\r
+               \r
+         if (!$this->bind) {\r
+           $this->bind = array();\r
+           for ($i = 0; $i < $this->_numOfFields; $i++) {\r
+             $o = $this->FetchField($i);\r
+             $this->bind[strtoupper($o->name)] = $i;\r
+           }\r
+         }\r
+         return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+       function _seek($row)\r
+       {\r
+         if ($this->_numOfRows == 0) \r
+           return false;\r
+\r
+         if ($row < 0)\r
+           return false;\r
+\r
+         mysqli_data_seek($this->_queryID, $row);\r
+         $this->EOF = false;\r
+         return true;\r
+       }\r
+               \r
+       // 10% speedup to move MoveNext to child class\r
+       // This is the only implementation that works now (23-10-2003).\r
+       // Other functions return no or the wrong results.\r
+       function MoveNext() \r
+       {\r
+               if ($this->EOF) return false;\r
+               $this->_currentRow++;\r
+               $this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);\r
+               \r
+               if (is_array($this->fields)) return true;\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+       \r
+       function _fetch()\r
+       {\r
+               $this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);  \r
+               return is_array($this->fields);\r
+       }\r
+       \r
+       function _close() \r
+       {\r
+               mysqli_free_result($this->_queryID); \r
+               $this->_queryID = false;        \r
+       }\r
+       \r
+       function MetaType($t, $len = -1, $fieldobj = false)\r
+       {\r
+         if (is_object($t)) \r
+           {\r
+             $fieldobj = $t;\r
+             $t = $fieldobj->type;\r
+             $len = $fieldobj->max_length;\r
+           }\r
+               \r
+         $len = -1; // mysql max_length is not accurate\r
+         switch (strtoupper($t)) {\r
+         case 'STRING': \r
+         case 'CHAR':\r
+         case 'VARCHAR': \r
+         case 'TINYBLOB': \r
+         case 'TINYTEXT': \r
+         case 'ENUM': \r
+         case 'SET': \r
+           if ($len <= $this->blobSize) return 'C';\r
+           \r
+         case 'TEXT':\r
+         case 'LONGTEXT': \r
+         case 'MEDIUMTEXT':\r
+           return 'X';\r
+                       \r
+           // php_mysql extension always returns 'blob' even if 'text'\r
+           // so we have to check whether binary...\r
+         case 'IMAGE':\r
+         case 'LONGBLOB': \r
+         case 'BLOB':\r
+         case 'MEDIUMBLOB':\r
+           return !empty($fieldobj->binary) ? 'B' : 'X';\r
+         case 'YEAR':\r
+         case 'DATE': \r
+           return 'D';\r
+               \r
+         case 'TIME':\r
+         case 'DATETIME':\r
+         case 'TIMESTAMP': return 'T';\r
+               \r
+         case 'INT': \r
+         case 'INTEGER':\r
+         case 'BIGINT':\r
+         case 'TINYINT':\r
+         case 'MEDIUMINT':\r
+         case 'SMALLINT': \r
+                       \r
+           if (!empty($fieldobj->primary_key)) return 'R';\r
+           else return 'I';\r
+           // Added floating-point types\r
+           // Maybe not necessery.\r
+         case 'FLOAT':\r
+         case 'DOUBLE':\r
+           //          case 'DOUBLE PRECISION':\r
+         case 'DECIMAL':\r
+         case 'DEC':\r
+         case 'FIXED':\r
+         default: \r
+           return 'N';\r
+         }\r
+       }\r
+       \r
+\r
+}\r
\r
+}\r
+\r
 ?>
\ No newline at end of file
index 5d8fcdaf46f1bed788ee6bd30416cb579d61d250..87b234fdb6d2c930529f26d24316e5632cf7440f 100644 (file)
@@ -1,76 +1,79 @@
-<?php
-
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
-  
-  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.
-*/
-
-
-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;
-       
-       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;
-       }
-       
-}
-
-class ADORecordSet_mysqlt extends ADORecordSet_mysql{  
-       var $databaseType = "mysqlt";
-       
-       function ADORecordSet_mysqlt($queryID,$mode=false) {
-               return $this->ADORecordSet_mysql($queryID,$mode);
-       }
-       
-       function MoveNext() 
-       {       
-               if ($this->EOF) return false;
-
-               $this->_currentRow++;
-               // using & below slows things down by 20%!
-               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
-               if ($this->fields) return true;
-               $this->EOF = true;
-               
-               return false;
-       }       
-}
+<?php\r
+\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  MySQL code that supports transactions. For MySQL 3.23 or later.\r
+  Code from James Poon <jpoon88@yahoo.com>\r
+  \r
+  Requires mysql client. Works on Windows and Unix.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");\r
+\r
+\r
+class ADODB_mysqlt extends ADODB_mysql {\r
+       var $databaseType = 'mysqlt';\r
+       var $ansiOuter = true; // for Version 3.23.17 or later\r
+       var $hasTransactions = true;\r
+       var $autoRollback = true; // apparently mysql does not autorollback properly \r
+       \r
+       function BeginTrans()\r
+       {         \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->Execute('SET AUTOCOMMIT=0');\r
+               $this->Execute('BEGIN');\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       {\r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('COMMIT');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->Execute('ROLLBACK');\r
+               $this->Execute('SET AUTOCOMMIT=1');\r
+               return true;\r
+       }\r
+       \r
+}\r
+\r
+class ADORecordSet_mysqlt extends ADORecordSet_mysql{  \r
+       var $databaseType = "mysqlt";\r
+       \r
+       function ADORecordSet_mysqlt($queryID,$mode=false) {\r
+               return $this->ADORecordSet_mysql($queryID,$mode);\r
+       }\r
+       \r
+       function MoveNext() \r
+       {       \r
+               if ($this->EOF) return false;\r
+\r
+               $this->_currentRow++;\r
+               // using & below slows things down by 20%!\r
+               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
+               if ($this->fields) return true;\r
+               $this->EOF = true;\r
+               \r
+               return false;\r
+       }       \r
+}\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/drivers/adodb-netezza.inc.php b/lib/adodb/drivers/adodb-netezza.inc.php
new file mode 100644 (file)
index 0000000..fe74b21
--- /dev/null
@@ -0,0 +1,169 @@
+<?php\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.\r
\r
+  First cut at the Netezza Driver by Josh Eldridge joshuae74#hotmail.com\r
+ Based on the previous postgres drivers.\r
+ http://www.netezza.com/\r
+ Major Additions/Changes:\r
+    MetaDatabasesSQL, MetaTablesSQL, MetaColumnsSQL\r
+    Note: You have to have admin privileges to access the system tables\r
+    Removed non-working keys code (Netezza has no concept of keys)\r
+    Fixed the way data types and lengths are returned in MetaColumns()\r
+    as well as added the default lengths for certain types\r
+    Updated public variables for Netezza\r
+    Still need to remove blob functions, as Netezza doesn't suppport blob\r
+*/\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR.'/drivers/adodb-postgres64.inc.php');\r
+\r
+class ADODB_netezza extends ADODB_postgres64 {\r
+    var $databaseType = 'netezza';     \r
+       var $dataProvider = 'netezza';\r
+       var $hasInsertID = false;\r
+       var $_resultid = false;\r
+       var $concat_operator='||';\r
+       var $random = 'random';\r
+       var $upperCase = 'upper';\r
+       var $metaDatabasesSQL = "select objname from _v_object_data where objtype='database' order by 1";\r
+    var $metaTablesSQL = "select objname from _v_object_data where objtype='table' order by 1";\r
+       var $isoDates = true; // accepts dates in ISO format\r
+       var $sysDate = "CURRENT_DATE";\r
+       var $sysTimeStamp = "CURRENT_TIMESTAMP";\r
+       var $blobEncodeType = 'C';\r
+       var $metaColumnsSQL = "SELECT attname, atttype FROM _v_relation_column_def WHERE name = '%s' AND attnum > 0 ORDER BY attnum";\r
+       var $metaColumnsSQL1 = "SELECT attname, atttype FROM _v_relation_column_def WHERE name = '%s' AND attnum > 0 ORDER BY attnum";\r
+       // netezza doesn't have keys. it does have distributions, so maybe this is \r
+       // something that can be pulled from the system tables\r
+       var $metaKeySQL = "";\r
+       var $hasAffectedRows = true;\r
+       var $hasLimit = true;   \r
+       var $true = 't';                // string that represents TRUE for a database\r
+       var $false = 'f';               // string that represents FALSE for a database\r
+       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.\r
+       var $ansiOuter = true;\r
+       var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4\r
+                                                       // http://bugs.php.net/bug.php?id=25404\r
+\r
+                                                       \r
+       function ADODB_netezza() \r
+       {\r
+       \r
+       }\r
+       \r
+       function &MetaColumns($table,$upper=true) \r
+       {\r
+       \r
+       // Changed this function to support Netezza which has no concept of keys\r
+       // could posisbly work on other things from the system table later.\r
+       \r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $table = strtolower($table);\r
+\r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+               \r
+               $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));\r
+               if (isset($savem)) $this->SetFetchMode($savem);\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               if ($rs === false) return false;\r
+\r
+               $retarr = array();\r
+               while (!$rs->EOF) {     \r
+                       $fld = new ADOFieldObject();\r
+                       $fld->name = $rs->fields[0];\r
+                       \r
+                       // since we're returning type and length as one string, \r
+                       // split them out here.\r
+                       \r
+                       if ($first = strstr($rs->fields[1], "(")) {\r
+                        $fld->max_length = trim($first, "()");\r
+                       } else {\r
+                        $fld->max_length = -1;\r
+                       }\r
+               \r
+                       if ($first = strpos($rs->fields[1], "(")) {\r
+                        $fld->type = substr($rs->fields[1], 0, $first);\r
+                       } else {\r
+                        $fld->type = $rs->fields[1];\r
+                       }\r
+                       \r
+                       switch ($fld->type) {\r
+                        case "byteint":\r
+                        case "boolean":\r
+                        $fld->max_length = 1;\r
+                        break;\r
+                        case "smallint":\r
+                        $fld->max_length = 2;\r
+                        break;\r
+                        case "integer":\r
+                        case "numeric":\r
+                        case "date":\r
+                        $fld->max_length = 4;\r
+                        break;\r
+                        case "bigint":\r
+                        case "time":\r
+                        case "timestamp":\r
+                        $fld->max_length = 8;\r
+                        break;\r
+                        case "timetz":\r
+                        case "time with time zone":\r
+                        $fld->max_length = 12;\r
+                        break;\r
+                       }\r
+                       \r
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                       else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;\r
+                       \r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close();\r
+               return $retarr; \r
+               \r
+       }\r
+\r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_netezza extends ADORecordSet_postgres64\r
+{\r
+       var $databaseType = "netezza";\r
+       var $canSeek = true;\r
+       \r
+       function ADORecordSet_netezza($queryID,$mode=false) \r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode)\r
+               {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;\r
+               }\r
+               $this->ADORecordSet($queryID);\r
+       }\r
+       \r
+       // _initrs modified to disable blob handling\r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;\r
+               $this->_numOfFields = @pg_numfields($this->_queryID);\r
+       }\r
+\r
+}\r
+?>\r
index efabaf4b38afd055867bb98bf092aeaca800434c..b6454a723c9bba6c9b2558d03647252bd669a944 100644 (file)
-<?php
-/*
-
-  version V4.20 22 Feb 2004 (c) 2000-2004 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.
-
-  Latest version is available at http://php.weblogs.com/
-  
-  Code contributed by George Fourlanos <fou@infomap.gr>
-  
-  13 Nov 2000 jlim - removed all ora_* references.
-*/
-
-/*
-NLS_Date_Format
-Allows you to use a date format other than the Oracle Lite default. When a literal
-character string appears where a date value is expected, the Oracle Lite database
-tests the string to see if it matches the formats of Oracle, SQL-92, or the value
-specified for this parameter in the POLITE.INI file. Setting this parameter also
-defines the default format used in the TO_CHAR or TO_DATE functions when no
-other format string is supplied.
-
-For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
-yy-mm-dd or yyyy-mm-dd.
-
-Using 'RR' in the format forces two-digit years less than or equal to 49 to be
-interpreted as years in the 21st century (2000\962049), and years over 50 as years in
-the 20th century (1950\961999). Setting the RR format as the default for all two-digit
-year entries allows you to become year-2000 compliant. For example:
-NLS_DATE_FORMAT='RR-MM-DD'
-
-You can also modify the date format using the ALTER SESSION command. 
-*/
-
-class ADODB_oci8 extends ADOConnection {
-       var $databaseType = 'oci8';
-       var $dataProvider = 'oci8';
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $concat_operator='||';
-       var $sysDate = "TRUNC(SYSDATE)";
-       var $sysTimeStamp = '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 $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
-       var $_bindInputArray = true;
-       var $hasGenID = true;
-       var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
-       var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";
-       var $_dropSeqSQL = "DROP SEQUENCE %s";
-       var $hasAffectedRows = true;
-       var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
-       var $noNullStrings = false;
-       var $connectSID = false;
-       var $_bind = false;
-       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 $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'
-       var $useDBDateFormatForTextInput=false;
-       var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
-       
-       // var $ansiOuter = true; // if oracle9
-    
-       function ADODB_oci8() 
-       {
-               $this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;
-       }
-       
-       /*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
-       function &MetaColumns($table) 
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-               
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
-               
-               if (isset($savem)) $this->SetFetchMode($savem);
-               $ADODB_FETCH_MODE = $save;
-               if (!$rs) return false;
-               $retarr = array();
-               while (!$rs->EOF) { //print_r($rs->fields);
-                       $fld = new ADOFieldObject();
-                       $fld->name = $rs->fields[0];
-                       $fld->type = $rs->fields[1];
-                       $fld->max_length = $rs->fields[2];
-                       $fld->scale = $rs->fields[3];
-                       if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
-                               $fld->type ='INT';
-                       $fld->max_length = $rs->fields[4];
-               }       
-                       $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
-                       $fld->binary = (strpos($fld->type,'BLOB') !== false);
-                       $fld->default_value = $rs->fields[6];
-                       
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
-                       else $retarr[strtoupper($fld->name)] = $fld;
-                       $rs->MoveNext();
-               }
-               $rs->Close();
-               return $retarr;
-       }
-/*
-
-  Multiple modes of connection are supported:
-  
-  a. Local Database
-    $conn->Connect(false,'scott','tiger');
-  
-  b. From tnsnames.ora
-    $conn->Connect(false,'scott','tiger',$tnsname); 
-    $conn->Connect($tnsname,'scott','tiger'); 
-  
-  c. Server + service name
-    $conn->Connect($serveraddress,'scott,'tiger',$service_name);
-  
-  d. Server + SID
-       $conn->connectSID = true;
-       $conn->Connect($serveraddress,'scott,'tiger',$SID);
-
-
-Example TNSName:
----------------
-NATSOFT.DOMAIN =
-  (DESCRIPTION =
-       (ADDRESS_LIST =
-         (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))
-       )
-       (CONNECT_DATA =
-         (SERVICE_NAME = natsoft.domain)
-       )
-  )
-  
-  There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection
-       
-*/
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
-       {
-               if (!function_exists('OCIPLogon')) return false;
-               
-               
-        $this->_errorMsg = false;
-               $this->_errorCode = false;
-               
-               if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
-                       if (empty($argDatabasename)) $argDatabasename = $argHostname;
-                       else {
-                               if(strpos($argHostname,":")) {
-                                       $argHostinfo=explode(":",$argHostname);
-                                       $argHostname=$argHostinfo[0];
-                                       $argHostport=$argHostinfo[1];
-                               } else {
-                                       $argHostport="1521";
-                               }
-                               
-                               if ($this->connectSID) {
-                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
-                                       .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
-                               } else
-                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
-                                       .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
-                       }
-               }
-                               
-               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
-               if ($mode==1) {
-                       $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename);
-                       if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);
-               } else if ($mode==2) {
-                       $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename);
-               } else {
-                       $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename);
-               }
-               if ($this->_connectionID === false) return false;
-               if ($this->_initdate) {
-                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
-               }
-               
-               // looks like: 
-               // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
-               // $vers = OCIServerVersion($this->_connectionID);
-               // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
-               return true;
-       }
-       
-       function ServerInfo()
-       {
-               $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
-               $arr['description'] = @OCIServerVersion($this->_connectionID);
-               $arr['version'] = ADOConnection::_findvers($arr['description']);
-               return $arr;
-       }
-               // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
-       }
-       
-       
-       
-       // returns true or false
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
-       }
-       
-       function _affectedrows()
-       {
-               if (is_resource($this->_stmt)) return @OCIRowCount($this->_stmt);
-               return 0;
-       }
-       
-       function IfNull( $field, $ifNull ) 
-       {
-               return " NVL($field, $ifNull) "; // if Oracle
-       }
-       
-       // format and return date string in database date format
-       function DBDate($d)
-       {
-               if (empty($d) && $d !== 0) return 'null';
-               
-               if (is_string($d)) $d = ADORecordSet::UnixDate($d);
-               return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";
-       }
-
-       
-       // 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).",'RRRR-MM-DD, HH:MI:SS AM')";
-       }
-       
-       function RowLock($tables,$where) 
-       {
-               if ($this->autoCommit) $this->BeginTrans();
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");
-       }
-       
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
-       {
-               if ($mask) {
-                       $save = $this->metaTablesSQL;
-                       $mask = $this->qstr(strtoupper($mask));
-                       $this->metaTablesSQL .= " AND table_name like $mask";
-               }
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
-               
-               if ($mask) {
-                       $this->metaTablesSQL = $save;
-               }
-               return $ret;
-       }
-       
-       function BeginTrans()
-       {       
-               if ($this->transOff) return true;
-               $this->transCnt += 1;
-               $this->autoCommit = false;
-               $this->_commit = OCI_DEFAULT;
-               return true;
-       }
-       
-       function CommitTrans($ok=true) 
-       { 
-               if ($this->transOff) return true;
-               if (!$ok) return $this->RollbackTrans();
-               
-               if ($this->transCnt) $this->transCnt -= 1;
-               $ret = OCIcommit($this->_connectionID);
-               $this->_commit = OCI_COMMIT_ON_SUCCESS;
-               $this->autoCommit = true;
-               return $ret;
-       }
-       
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true;
-               if ($this->transCnt) $this->transCnt -= 1;
-               $ret = OCIrollback($this->_connectionID);
-               $this->_commit = OCI_COMMIT_ON_SUCCESS;
-               $this->autoCommit = true;
-               return $ret;
-       }
-       
-       
-       function SelectDB($dbName) 
-       {
-               return false;
-       }
-
-       function ErrorMsg() 
-       {
-               if ($this->_errorMsg !== false) return $this->_errorMsg;
-
-               if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);
-               if (empty($arr)) {
-                       $arr = @OCIerror($this->_connectionID);
-                       if ($arr === false) $arr = @OCIError();
-                       if ($arr === false) return '';
-               }
-               $this->_errorMsg = $arr['message'];
-               $this->_errorCode = $arr['code'];
-               return $this->_errorMsg;
-       }
-
-       function ErrorNo() 
-       {
-               if ($this->_errorCode !== false) return $this->_errorCode;
-               
-               if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
-               if (empty($arr)) {
-                       $arr = @OCIError($this->_connectionID);
-                       if ($arr == false) $arr = @OCIError();
-                       if ($arr == false) return '';
-               }
-               
-               $this->_errorMsg = $arr['message'];
-               $this->_errorCode = $arr['code'];
-               
-               return $arr['code'];
-       }
-       
-       // 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 = 'TO_CHAR('.$col.",'";
-               
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= 'YYYY';
-                               break;
-                       case 'Q':
-                       case 'q':
-                               $s .= 'Q';
-                               break;
-                               
-                       case 'M':
-                               $s .= 'Mon';
-                               break;
-                               
-                       case 'm':
-                               $s .= 'MM';
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= 'DD';
-                               break;
-                       
-                       case 'H':
-                               $s.= 'HH24';
-                               break;
-                               
-                       case 'h':
-                               $s .= 'HH';
-                               break;
-                               
-                       case 'i':
-                               $s .= 'MI';
-                               break;
-                       
-                       case 's':
-                               $s .= 'SS';
-                               break;
-                       
-                       case 'a':
-                       case 'A':
-                               $s .= 'AM';
-                               break;
-                               
-                       default:
-                       // handle escape characters...
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
-                               else $s .= '"'.$ch.'"';
-                               
-                       }
-               }
-               return $s. "')";
-       }
-       
-       
-       /*
-       This algorithm makes use of
-       
-       a. FIRST_ROWS hint
-       The FIRST_ROWS hint explicitly chooses the approach to optimize response time, 
-       that is, minimum resource usage to return the first row. Results will be returned 
-       as soon as they are identified. 
-
-       b. Uses rownum tricks to obtain only the required rows from a given offset.
-        As this uses complicated sql statements, we only use this if the $offset >= 100. 
-        This idea by Tomas V V Cox.
-        
-        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)
-       {
-               // seems that oracle only supports 1 hint comment in 8i
-               if ($this->firstrows) {
-                       if (strpos($sql,'/*+') !== false)
-                               $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
-                       else
-                               $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
-               }
-               
-               if ($offset < $this->selectOffsetAlg1) {
-                       if ($nrows > 0) {       
-                               if ($offset > 0) $nrows += $offset;
-                               //$inputarr['adodb_rownum'] = $nrows;
-                               if ($this->databaseType == 'oci8po') {
-                                       $sql = "select * from ($sql) where rownum <= ?";
-                               } else {
-                                       $sql = "select * from ($sql) where rownum <= :adodb_offset";
-                               } 
-                               $inputarr['adodb_offset'] = $nrows;
-                               $nrows = -1;
-                       }
-                       // note that $nrows = 0 still has to work ==> no rows returned
-
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-                       return $rs;
-                       
-               } else {
-                        // Algorithm by Tomas V V Cox, from PEAR DB oci8.php
-                       
-                        // Let Oracle return the name of the columns
-                        $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL";
-                        if (!$stmt = OCIParse($this->_connectionID, $q_fields)) {
-                                return false;
-                        }
-                        
-                        if (is_array($inputarr)) {
-                               foreach($inputarr as $k => $v) {
-                                       if (is_array($v)) {
-                                               if (sizeof($v) == 2) // suggested by g.giunta@libero.
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
-                                               else
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
-                                       } else {
-                                               $len = -1;
-                                               if ($v === ' ') $len = 1;
-                                               if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again
-                                                       $bindarr[$k] = $v;
-                                               } else {                                // dynamic sql, so rebind every time
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k],$len);
-                                               }
-                                       }
-                               }
-                       }
-                       
-                        if (!OCIExecute($stmt, OCI_DEFAULT)) {
-                                OCIFreeStatement($stmt); 
-                                return false;
-                        }
-                        
-                        $ncols = OCINumCols($stmt);
-                        for ( $i = 1; $i <= $ncols; $i++ ) {
-                                $cols[] = '"'.OCIColumnName($stmt, $i).'"';
-                        }
-                        $result = false;
-                       
-                        OCIFreeStatement($stmt); 
-                        $fields = implode(',', $cols);
-                        $nrows += $offset;
-                        $offset += 1; // in Oracle rownum starts at 1
-                       
-                       if ($this->databaseType == 'oci8po') {
-                                        $sql = "SELECT $fields FROM".
-                                         "(SELECT rownum as adodb_rownum, $fields FROM".
-                                         " ($sql) WHERE rownum <= ?".
-                                         ") WHERE adodb_rownum >= ?";
-                               } else {
-                                        $sql = "SELECT $fields FROM".
-                                         "(SELECT rownum as adodb_rownum, $fields FROM".
-                                         " ($sql) WHERE rownum <= :adodb_nrows".
-                                         ") WHERE adodb_rownum >= :adodb_offset";
-                               } 
-                               $inputarr['adodb_nrows'] = $nrows;
-                               $inputarr['adodb_offset'] = $offset;
-                               
-                       if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);
-                       else $rs =& $this->Execute($sql,$inputarr);
-                       return $rs;
-               }
-       
-       }
-       
-       /**
-       * Usage:
-       * Store BLOBs and CLOBs
-       *
-       * Example: to store $var in a blob
-       *
-       *       $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
-       *       $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
-       *       
-       *       $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
-       *
-       *  to get length of LOB:
-       *       select DBMS_LOB.GETLENGTH(ablob) from TABLE
-       *
-       * If you are using CURSOR_SHARING = force, it appears this will case a segfault
-       * under oracle 8.1.7.0. Run:
-       *        $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
-       * before UpdateBlob() then...
-       */
-
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
-       {
-               
-               //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
-               
-               switch(strtoupper($blobtype)) {
-               default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
-               case 'BLOB': $type = OCI_B_BLOB; break;
-               case 'CLOB': $type = OCI_B_CLOB; break;
-               }
-               
-               if ($this->databaseType == 'oci8po') 
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
-               else 
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
-               
-               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
-               $arr['blob'] = array($desc,-1,$type);
-               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
-               $commit = $this->autoCommit;
-               if ($commit) $this->BeginTrans();
-               $rs = ADODB_oci8::Execute($sql,$arr);
-               if ($rez = !empty($rs)) $desc->save($val);
-               $desc->free();
-               if ($commit) $this->CommitTrans();
-               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
-               
-               if ($rez) $rs->Close();
-               return $rez;
-       }
-       
-       /**
-       * Usage:  store file pointed to by $var in a blob
-       */
-       function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
-       {
-               switch(strtoupper($blobtype)) {
-               default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
-               case 'BLOB': $type = OCI_B_BLOB; break;
-               case 'CLOB': $type = OCI_B_CLOB; break;
-               }
-               
-               if ($this->databaseType == 'oci8po') 
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
-               else 
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
-               
-               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
-               $arr['blob'] = array($desc,-1,$type);
-               
-               $this->BeginTrans();
-               $rs = ADODB_oci8::Execute($sql,$arr);
-               if ($rez = !empty($rs)) $desc->savefile($val);
-               $desc->free();
-               $this->CommitTrans();
-               
-               if ($rez) $rs->Close();
-               return $rez;
-       }
-       
-       /*
-               Example of usage:
-               
-               $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
-       */
-       function Prepare($sql,$cursor=false)
-       {
-       static $BINDNUM = 0;
-       
-               $stmt = OCIParse($this->_connectionID,$sql);
-
-               if (!$stmt) return false;
-
-               $BINDNUM += 1;
-               
-               if (@OCIStatementType($stmt) == 'BEGIN') {
-                       return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
-               } 
-               
-               return array($sql,$stmt,0,$BINDNUM);
-       }
-       
-       /*
-               Call an oracle stored procedure and return a cursor variable. 
-               Convert the cursor variable into a recordset. 
-               Concept by Robert Tuttle robert@ud.com
-               
-               Example:
-                       Note: we return a cursor variable in :RS2
-                       $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
-                       
-                       $rs = $db->ExecuteCursor(
-                               "BEGIN :RS2 = adodb.getdata(:VAR1); END;", 
-                               'RS2',
-                               array('VAR1' => 'Mr Bean'));
-                       
-       */
-       function &ExecuteCursor($sql,$cursorName='rs',$params=false)
-       {
-               $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
-                       
-               if (is_array($stmt) && sizeof($stmt) >= 5) {
-                       $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
-                       if ($params) {
-                               foreach($params as $k => $v) {
-                                       $this->Parameter($stmt,$params[$k], $k);
-                               }
-                       }
-               }
-               return $this->Execute($stmt);
-       }
-       
-       /*
-               Bind a variable -- very, very fast for executing repeated statements in oracle. 
-               Better than using
-                       for ($i = 0; $i < $max; $i++) { 
-                               $p1 = ?; $p2 = ?; $p3 = ?;
-                               $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", 
-                                       array($p1,$p2,$p3));
-                       }
-               
-               Usage:
-                       $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
-                       $DB->Bind($stmt, $p1);
-                       $DB->Bind($stmt, $p2);
-                       $DB->Bind($stmt, $p3);
-                       for ($i = 0; $i < $max; $i++) { 
-                               $p1 = ?; $p2 = ?; $p3 = ?;
-                               $DB->Execute($stmt);
-                       }
-                       
-               Some timings:           
-                       ** Test table has 3 cols, and 1 index. Test to insert 1000 records
-                       Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute
-                       Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
-                       Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
-                       
-               Now if PHP only had batch/bulk updating like Java or PL/SQL...
-       
-               Note that the order of parameters differs from OCIBindByName,
-               because we default the names to :0, :1, :2
-       */
-       function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false)
-       {
-               if (!is_array($stmt)) return false;
-        
-        if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { 
-            return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);
-        }
-        
-               if ($name == false) {
-                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
-                       else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
-                       $stmt[2] += 1;
-               } else {
-                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
-                       else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
-               }
-               
-               return $rez;
-       }
-       
-       function Param($name)
-       {
-               return ':'.$name;
-       }
-       
-       /* 
-       Usage:
-               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
-               $db->Parameter($stmt,$id,'myid');
-               $db->Parameter($stmt,$group,'group');
-               $db->Execute($stmt);
-               
-               @param $stmt Statement returned by Prepare() or PrepareSP().
-               @param $var PHP variable to bind to
-               @param $name Name of stored procedure variable name to bind to.
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
-               @param [$maxLen] Holds an maximum length of the variable.
-               @param [$type] The data type of $var. Legal values depend on driver.
-               
-               See OCIBindByName documentation at php.net.
-       */
-       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
-       {
-                       if  ($this->debug) {
-                               $prefix = ($isOutput) ? 'Out' : 'In';
-                               $ztype = (empty($type)) ? 'false' : $type;
-                               ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
-                       }
-                       return $this->Bind($stmt,$var,$maxLen,$type,$name);
-       }
-       
-       /*
-       returns query ID if successful, otherwise false
-       this version supports:
-       
-          1. $db->execute('select * from table');
-          
-          2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
-                 $db->execute($prepared_statement, array(1,2,3));
-                 
-          3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
-          
-          4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
-                 $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); 
-                 $db->execute($stmt);
-       */ 
-       function _query($sql,$inputarr)
-       {
-               
-               if (is_array($sql)) { // is prepared sql
-                       $stmt = $sql[1];
-                       
-                       // we try to bind to permanent array, so that OCIBindByName is persistent
-                       // and carried out once only - note that max array element size is 4000 chars
-                       if (is_array($inputarr)) {
-                               $bindpos = $sql[3];
-                               if (isset($this->_bind[$bindpos])) {
-                               // all tied up already
-                                       $bindarr = &$this->_bind[$bindpos];
-                               } else {
-                               // one statement to bind them all
-                                       $bindarr = array();
-                                       foreach($inputarr as $k => $v) {
-                                               $bindarr[$k] = $v;
-                                               OCIBindByName($stmt,":$k",$bindarr[$k],4000);
-                                       }
-                                       $this->_bind[$bindpos] = &$bindarr;
-                               }
-                       }
-               } else {
-                       $stmt=OCIParse($this->_connectionID,$sql);
-               }
-                       
-               $this->_stmt = $stmt;
-               if (!$stmt) return false;
-       
-               if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);
-                       
-               if (is_array($inputarr)) {
-                       foreach($inputarr as $k => $v) {
-                               if (is_array($v)) {
-                                       if (sizeof($v) == 2) // suggested by g.giunta@libero.
-                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
-                                       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>';
-                               } else {
-                                       $len = -1;
-                                       if ($v === ' ') $len = 1;
-                                       if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again
-                                               $bindarr[$k] = $v;
-                                       } else {                                // dynamic sql, so rebind every time
-                                               OCIBindByName($stmt,":$k",$inputarr[$k],$len);
-                                       }
-                               }
-                       }
-               }
-               
-        $this->_errorMsg = false;
-               $this->_errorCode = false;
-               if (OCIExecute($stmt,$this->_commit)) {
-               
-            switch (@OCIStatementType($stmt)) {
-                case "SELECT":
-                                       return $stmt;
-                                       
-                case "BEGIN":
-                    if (is_array($sql) && !empty($sql[4])) {
-                                               $cursor = $sql[4];
-                                               if (is_resource($cursor)) {
-                                                       $ok = OCIExecute($cursor);      
-                               return $cursor;
-                                               }
-                                               return $stmt;
-                    } else {
-                                               if (is_resource($stmt)) {
-                                                       OCIFreeStatement($stmt);
-                                                       return true;
-                                               }
-                        return $stmt;
-                    }
-                    break;
-                default :
-                                       // ociclose -- no because it could be used in a LOB?
-                    return true;
-            }
-               }
-               return false;
-       }
-       
-       // returns true or false
-       function _close()
-       {
-               if (!$this->autoCommit) OCIRollback($this->_connectionID);
-               OCILogoff($this->_connectionID);
-               $this->_stmt = false;
-               $this->_connectionID = false;
-       }
-       
-       function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
-       {
-               if ($internalKey) return array('ROWID');
-               
-       // tested with oracle 8.1.7
-               $table = strtoupper($table);
-               if ($owner) {
-                       $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
-                       $ptab = 'ALL_';
-               } else {
-                       $owner_clause = '';
-                       $ptab = 'USER_';
-               }
-               $sql = "
-SELECT /*+ RULE */ distinct b.column_name
-   FROM {$ptab}CONSTRAINTS a
-         , {$ptab}CONS_COLUMNS b
-  WHERE ( UPPER(b.table_name) = ('$table'))
-       AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
-       $owner_clause
-       AND (a.constraint_name = b.constraint_name)";
-
-               $rs = $this->Execute($sql);
-               if ($rs && !$rs->EOF) {
-                       $arr =& $rs->GetArray();
-                       $a = array();
-                       foreach($arr as $v) {
-                               $a[] = reset($v);
-                       }
-                       return $a;
-               }
-               else return false;
-       }
-       
-       // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
-       function MetaForeignKeys($table, $owner=false)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $table = $this->qstr(strtoupper($table));
-               if (!$owner) {
-                       $owner = $this->user;
-                       $tabp = 'user_';
-               } else
-                       $tabp = 'all_';
-                       
-               $owner = ' and owner='.$this->qstr(strtoupper($owner));
-               
-               $sql = 
-"select constraint_name,r_owner,r_constraint_name 
-       from {$tabp}constraints
-       where constraint_type = 'R' and table_name = $table $owner";
-               
-               $constraints =& $this->GetArray($sql);
-               $arr = false;
-               foreach($constraints as $constr) {
-                       $cons = $this->qstr($constr[0]);
-                       $rowner = $this->qstr($constr[1]);
-                       $rcons = $this->qstr($constr[2]);
-                       $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
-                       $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
-                       
-                       if ($cols && $tabcol) 
-                               for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
-                                       $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
-                               }
-               }
-               $ADODB_FETCH_MODE = $save;
-               
-               return $arr;
-       }
-
-       
-       function CharMax()
-       {
-               return 4000;
-       }
-       
-       function TextMax()
-       {
-               return 4000;
-       }
-       
-       /**
-        * Quotes a string.
-        * 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)
-       {       
-       $nofixquotes=false;
-       
-               if (is_array($s)) adodb_backtrace();
-               if ($this->noNullStrings && strlen($s)==0)$s = ' ';
-               if (!$magic_quotes) {   
-                       if ($this->replaceQuote[0] == '\\'){
-                               $s = str_replace('\\','\\\\',$s);
-                       }
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";
-               }
-               
-               // undo magic quotes for "
-               $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)."'";
-               }
-       }
-       
-}
-
-/*--------------------------------------------------------------------------------------
-                Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_oci8 extends ADORecordSet {
-
-       var $databaseType = 'oci8';
-       var $bind=false;
-       var $_fieldobjs;
-       //var $_arr = false;
-               
-       function ADORecordset_oci8($queryID,$mode=false)
-       {
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               switch ($mode)
-               {
-               default:
-               case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
-               case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
-               case ADODB_FETCH_DEFAULT:
-               case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
-               }
-
-               $this->_queryID = $queryID;
-       }
-
-
-       function Init()
-       {
-               if ($this->_inited) return;
-               
-               $this->_inited = true;
-               if ($this->_queryID) {
-                       
-                       $this->_currentRow = 0;
-                       @$this->_initrs();
-                       $this->EOF = !$this->_fetch();
-                       
-                       /*
-                       // based on idea by Gaetano Giunta to detect unusual oracle errors
-                       // see http://phplens.com/lens/lensforum/msgs.php?id=6771
-                       $err = OCIError($this->_queryID);
-                       if ($err && $this->connection->debug) ADOConnection::outp($err);
-                       */
-                       
-                       if (!is_array($this->fields)) {
-                               $this->_numOfRows = 0;
-                               $this->fields = array();
-                       }
-               } else {
-                       $this->fields = array();
-                       $this->_numOfRows = 0;
-                       $this->_numOfFields = 0;
-                       $this->EOF = true;
-               }
-       }
-       
-       function _initrs()
-       {
-               $this->_numOfRows = -1;
-               $this->_numOfFields = OCInumcols($this->_queryID);
-               if ($this->_numOfFields>0) {
-                       $this->_fieldobjs = array();
-                       $max = $this->_numOfFields;
-                       for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
-               }
-       }
-
-         /*            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)
-       {
-               $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') {
-                       $p = OCIColumnPrecision($this->_queryID, $fieldOffset);
-                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);
-                       if ($p != 0 && $sc == 0) $fld->type = 'INT';
-                       //echo " $this->name ($p.$sc) ";
-               }
-               return $fld;
-       }
-       
-       /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
-       function &FetchField($fieldOffset = -1)
-       {
-               return $this->_fieldobjs[$fieldOffset];
-       }
-       
-       
-       // 10% speedup to move MoveNext to child class
-       function MoveNext() 
-       {
-       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);
-               
-               if ($this->EOF) return false;
-               
-               $this->_currentRow++;
-               if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))
-                       return true;
-               $this->EOF = true;
-               
-               return false;
-       }       
-       
-       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
-       function &GetArrayLimit($nrows,$offset=-1) 
-       {
-               if ($offset <= 0) {
-                       $arr =& $this->GetArray($nrows);
-                       return $arr;
-               }
-               for ($i=1; $i < $offset; $i++) 
-                       if (!@OCIFetch($this->_queryID)) return array();
-                       
-               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
-               $results = array();
-               $cnt = 0;
-               while (!$this->EOF && $nrows != $cnt) {
-                       $results[$cnt++] = $this->fields;
-                       $this->MoveNext();
-               }
-               
-               return $results;
-       }
-
-       
-       /* Use associative array to get fields array */
-       function 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 _seek($row)
-       {
-               return false;
-       }
-
-       function _fetch() 
-       {
-               return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
-       }
-
-       /*              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() 
-       {
-               if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
-               OCIFreeStatement($this->_queryID);
-               $this->_queryID = false;
-               
-       }
-
-       function MetaType($t,$len=-1)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-               case 'VARCHAR':
-               case 'VARCHAR2':
-               case 'CHAR':
-               case 'VARBINARY':
-               case 'BINARY':
-               case 'NCHAR':
-               case 'NVARCHAR':
-               case 'NVARCHAR2':
-                                if (isset($this) && $len <= $this->blobSize) return 'C';
-               
-               case 'NCLOB':
-               case 'LONG':
-               case 'LONG VARCHAR':
-               case 'CLOB':
-               return 'X';
-               
-               case 'LONG RAW':
-               case 'LONG VARBINARY':
-               case 'BLOB':
-                       return 'B';
-               
-               case 'DATE': 
-                       return  ($this->connection->datetime) ? 'T' : 'D';
-               
-               
-               case 'TIMESTAMP': return 'T';
-               
-               case 'INT': 
-               case 'SMALLINT':
-               case 'INTEGER': 
-                       return 'I';
-                       
-               default: return 'N';
-               }
-       }
-}
+<?php\r
+/*\r
+\r
+  version V4.50 6 July 2004 (c) 2000-2004 John Lim. All rights reserved.\r
+\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Code contributed by George Fourlanos <fou@infomap.gr>\r
+  \r
+  13 Nov 2000 jlim - removed all ora_* references.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+/*\r
+NLS_Date_Format\r
+Allows you to use a date format other than the Oracle Lite default. When a literal\r
+character string appears where a date value is expected, the Oracle Lite database\r
+tests the string to see if it matches the formats of Oracle, SQL-92, or the value\r
+specified for this parameter in the POLITE.INI file. Setting this parameter also\r
+defines the default format used in the TO_CHAR or TO_DATE functions when no\r
+other format string is supplied.\r
+\r
+For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is\r
+yy-mm-dd or yyyy-mm-dd.\r
+\r
+Using 'RR' in the format forces two-digit years less than or equal to 49 to be\r
+interpreted as years in the 21st century (2000\962049), and years over 50 as years in\r
+the 20th century (1950\961999). Setting the RR format as the default for all two-digit\r
+year entries allows you to become year-2000 compliant. For example:\r
+NLS_DATE_FORMAT='RR-MM-DD'\r
+\r
+You can also modify the date format using the ALTER SESSION command. \r
+*/\r
+\r
+# define the LOB descriptor type for the given type\r
+# returns false if no LOB descriptor\r
+function oci_lob_desc($type) {\r
+       switch ($type) {\r
+               case OCI_B_BFILE: $result = OCI_D_FILE; break;\r
+               case OCI_B_CFILEE: $result = OCI_D_FILE; break;\r
+               case OCI_B_CLOB: $result = OCI_D_LOB; break;\r
+               case OCI_B_BLOB: $result = OCI_D_LOB; break;\r
+               case OCI_B_ROWID: $result = OCI_D_ROWID; break;\r
+               default: $result = false; break;\r
+       }\r
+       return $result;\r
+}\r
+\r
+class ADODB_oci8 extends ADOConnection {\r
+       var $databaseType = 'oci8';\r
+       var $dataProvider = 'oci8';\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $concat_operator='||';\r
+       var $sysDate = "TRUNC(SYSDATE)";\r
+       var $sysTimeStamp = 'SYSDATE';\r
+       var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";\r
+       var $_stmt;\r
+       var $_commit = OCI_COMMIT_ON_SUCCESS;\r
+       var $_initdate = true; // init date to YYYY-MM-DD\r
+       var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";\r
+       var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net\r
+       var $_bindInputArray = true;\r
+       var $hasGenID = true;\r
+       var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";\r
+       var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";\r
+       var $_dropSeqSQL = "DROP SEQUENCE %s";\r
+       var $hasAffectedRows = true;\r
+       var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";\r
+       var $noNullStrings = false;\r
+       var $connectSID = false;\r
+       var $_bind = false;\r
+       var $_hasOCIFetchStatement = false;\r
+       var $_getarray = false; // currently not working\r
+       var $leftOuter = '';  // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER\r
+       var $session_sharing_force_blob = false; // alter session on updateblob if set to true \r
+       var $firstrows = true; // enable first rows optimization on SelectLimit()\r
+       var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.\r
+       var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'\r
+       var $useDBDateFormatForTextInput=false;\r
+       var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)\r
+       var $_refLOBs = array();\r
+       \r
+       // var $ansiOuter = true; // if oracle9\r
+    \r
+       function ADODB_oci8() \r
+       {\r
+               $this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;\r
+       }\r
+       \r
+       /*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/\r
+       function &MetaColumns($table) \r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+               \r
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+               \r
+               if (isset($savem)) $this->SetFetchMode($savem);\r
+               $ADODB_FETCH_MODE = $save;\r
+               if (!$rs) return false;\r
+               $retarr = array();\r
+               while (!$rs->EOF) { //print_r($rs->fields);\r
+                       $fld = new ADOFieldObject();\r
+                       $fld->name = $rs->fields[0];\r
+                       $fld->type = $rs->fields[1];\r
+                       $fld->max_length = $rs->fields[2];\r
+                       $fld->scale = $rs->fields[3];\r
+                       if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {\r
+                               $fld->type ='INT';\r
+                       $fld->max_length = $rs->fields[4];\r
+               }       \r
+                       $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);\r
+                       $fld->binary = (strpos($fld->type,'BLOB') !== false);\r
+                       $fld->default_value = $rs->fields[6];\r
+                       \r
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                       else $retarr[strtoupper($fld->name)] = $fld;\r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close();\r
+               return $retarr;\r
+       }\r
+       \r
+       function Time()\r
+       {\r
+               $rs =& $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");\r
+               if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));\r
+               \r
+               return false;\r
+       }\r
\r
+/*\r
+\r
+  Multiple modes of connection are supported:\r
+  \r
+  a. Local Database\r
+    $conn->Connect(false,'scott','tiger');\r
+  \r
+  b. From tnsnames.ora\r
+    $conn->Connect(false,'scott','tiger',$tnsname); \r
+    $conn->Connect($tnsname,'scott','tiger'); \r
+  \r
+  c. Server + service name\r
+    $conn->Connect($serveraddress,'scott,'tiger',$service_name);\r
+  \r
+  d. Server + SID\r
+       $conn->connectSID = true;\r
+       $conn->Connect($serveraddress,'scott,'tiger',$SID);\r
+\r
+\r
+Example TNSName:\r
+---------------\r
+NATSOFT.DOMAIN =\r
+  (DESCRIPTION =\r
+       (ADDRESS_LIST =\r
+         (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))\r
+       )\r
+       (CONNECT_DATA =\r
+         (SERVICE_NAME = natsoft.domain)\r
+       )\r
+  )\r
+  \r
+  There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection\r
+       \r
+*/\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)\r
+       {\r
+               if (!function_exists('OCIPLogon')) return null;\r
+               \r
+               \r
+        $this->_errorMsg = false;\r
+               $this->_errorCode = false;\r
+               \r
+               if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
+                       if (empty($argDatabasename)) $argDatabasename = $argHostname;\r
+                       else {\r
+                               if(strpos($argHostname,":")) {\r
+                                       $argHostinfo=explode(":",$argHostname);\r
+                                       $argHostname=$argHostinfo[0];\r
+                                       $argHostport=$argHostinfo[1];\r
+                               } else {\r
+                                       $argHostport="1521";\r
+                               }\r
+                               \r
+                               if ($this->connectSID) {\r
+                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                                       .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";\r
+                               } else\r
+                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                                       .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";\r
+                       }\r
+               }\r
+                               \r
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
+               if ($mode==1) {\r
+                       $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename);\r
+                       if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);\r
+               } else if ($mode==2) {\r
+                       $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename);\r
+               } else {\r
+                       $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename);\r
+               }\r
+               if ($this->_connectionID === false) return false;\r
+               if ($this->_initdate) {\r
+                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");\r
+               }\r
+               \r
+               // looks like: \r
+               // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production\r
+               // $vers = OCIServerVersion($this->_connectionID);\r
+               // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;\r
+               return true;\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');\r
+               $arr['description'] = @OCIServerVersion($this->_connectionID);\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               return $arr;\r
+       }\r
+               // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);\r
+       }\r
+       \r
+       \r
+       \r
+       // returns true or false\r
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+               if (is_resource($this->_stmt)) return @OCIRowCount($this->_stmt);\r
+               return 0;\r
+       }\r
+       \r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " NVL($field, $ifNull) "; // if Oracle\r
+       }\r
+       \r
+       // format and return date string in database date format\r
+       function DBDate($d)\r
+       {\r
+               if (empty($d) && $d !== 0) return 'null';\r
+               \r
+               if (is_string($d)) $d = ADORecordSet::UnixDate($d);\r
+               return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";\r
+       }\r
+\r
+       \r
+       // format and return date string in database timestamp format\r
+       function DBTimeStamp($ts)\r
+       {\r
+               if (empty($ts) && $ts !== 0) return 'null';\r
+               if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);\r
+               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";\r
+       }\r
+       \r
+       function RowLock($tables,$where) \r
+       {\r
+               if ($this->autoCommit) $this->BeginTrans();\r
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
+       }\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {\r
+               if ($mask) {\r
+                       $save = $this->metaTablesSQL;\r
+                       $mask = $this->qstr(strtoupper($mask));\r
+                       $this->metaTablesSQL .= " AND table_name like $mask";\r
+               }\r
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
+               \r
+               if ($mask) {\r
+                       $this->metaTablesSQL = $save;\r
+               }\r
+               return $ret;\r
+       }\r
+       \r
+       function BeginTrans()\r
+       {       \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->autoCommit = false;\r
+               $this->_commit = OCI_DEFAULT;\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true;\r
+               if (!$ok) return $this->RollbackTrans();\r
+               \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $ret = OCIcommit($this->_connectionID);\r
+               $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
+               $this->autoCommit = true;\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $ret = OCIrollback($this->_connectionID);\r
+               $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
+               $this->autoCommit = true;\r
+               return $ret;\r
+       }\r
+       \r
+       \r
+       function SelectDB($dbName) \r
+       {\r
+               return false;\r
+       }\r
+\r
+       function ErrorMsg() \r
+       {\r
+               if ($this->_errorMsg !== false) return $this->_errorMsg;\r
+\r
+               if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);\r
+               if (empty($arr)) {\r
+                       $arr = @OCIerror($this->_connectionID);\r
+                       if ($arr === false) $arr = @OCIError();\r
+                       if ($arr === false) return '';\r
+               }\r
+               $this->_errorMsg = $arr['message'];\r
+               $this->_errorCode = $arr['code'];\r
+               return $this->_errorMsg;\r
+       }\r
+\r
+       function ErrorNo() \r
+       {\r
+               if ($this->_errorCode !== false) return $this->_errorCode;\r
+               \r
+               if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);\r
+               if (empty($arr)) {\r
+                       $arr = @OCIError($this->_connectionID);\r
+                       if ($arr == false) $arr = @OCIError();\r
+                       if ($arr == false) return '';\r
+               }\r
+               \r
+               $this->_errorMsg = $arr['message'];\r
+               $this->_errorCode = $arr['code'];\r
+               \r
+               return $arr['code'];\r
+       }\r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = 'TO_CHAR('.$col.",'";\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= 'YYYY';\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= 'Q';\r
+                               break;\r
+                               \r
+                       case 'M':\r
+                               $s .= 'Mon';\r
+                               break;\r
+                               \r
+                       case 'm':\r
+                               $s .= 'MM';\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= 'DD';\r
+                               break;\r
+                       \r
+                       case 'H':\r
+                               $s.= 'HH24';\r
+                               break;\r
+                               \r
+                       case 'h':\r
+                               $s .= 'HH';\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= 'MI';\r
+                               break;\r
+                       \r
+                       case 's':\r
+                               $s .= 'SS';\r
+                               break;\r
+                       \r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= 'AM';\r
+                               break;\r
+                               \r
+                       default:\r
+                       // handle escape characters...\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;\r
+                               else $s .= '"'.$ch.'"';\r
+                               \r
+                       }\r
+               }\r
+               return $s. "')";\r
+       }\r
+       \r
+       \r
+       /*\r
+       This algorithm makes use of\r
+       \r
+       a. FIRST_ROWS hint\r
+       The FIRST_ROWS hint explicitly chooses the approach to optimize response time, \r
+       that is, minimum resource usage to return the first row. Results will be returned \r
+       as soon as they are identified. \r
+\r
+       b. Uses rownum tricks to obtain only the required rows from a given offset.\r
+        As this uses complicated sql statements, we only use this if the $offset >= 100. \r
+        This idea by Tomas V V Cox.\r
+        \r
+        This implementation does not appear to work with oracle 8.0.5 or earlier. Comment\r
+        out this function then, and the slower SelectLimit() in the base class will be used.\r
+       */\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               // seems that oracle only supports 1 hint comment in 8i\r
+               if ($this->firstrows) {\r
+                       if (strpos($sql,'/*+') !== false)\r
+                               $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);\r
+                       else\r
+                               $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);\r
+               }\r
+               \r
+               if ($offset < $this->selectOffsetAlg1) {\r
+                       if ($nrows > 0) {       \r
+                               if ($offset > 0) $nrows += $offset;\r
+                               //$inputarr['adodb_rownum'] = $nrows;\r
+                               if ($this->databaseType == 'oci8po') {\r
+                                       $sql = "select * from ($sql) where rownum <= ?";\r
+                               } else {\r
+                                       $sql = "select * from ($sql) where rownum <= :adodb_offset";\r
+                               } \r
+                               $inputarr['adodb_offset'] = $nrows;\r
+                               $nrows = -1;\r
+                       }\r
+                       // note that $nrows = 0 still has to work ==> no rows returned\r
+\r
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+                       return $rs;\r
+                       \r
+               } else {\r
+                        // Algorithm by Tomas V V Cox, from PEAR DB oci8.php\r
+                       \r
+                        // Let Oracle return the name of the columns\r
+                        $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL";\r
+                        if (!$stmt = OCIParse($this->_connectionID, $q_fields)) {\r
+                                return false;\r
+                        }\r
+                        \r
+                        if (is_array($inputarr)) {\r
+                               foreach($inputarr as $k => $v) {\r
+                                       if (is_array($v)) {\r
+                                               if (sizeof($v) == 2) // suggested by g.giunta@libero.\r
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);\r
+                                               else\r
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);\r
+                                       } else {\r
+                                               $len = -1;\r
+                                               if ($v === ' ') $len = 1;\r
+                                               if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again\r
+                                                       $bindarr[$k] = $v;\r
+                                               } else {                                // dynamic sql, so rebind every time\r
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k],$len);\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+                       \r
+                        if (!OCIExecute($stmt, OCI_DEFAULT)) {\r
+                                OCIFreeStatement($stmt); \r
+                                return false;\r
+                        }\r
+                        \r
+                        $ncols = OCINumCols($stmt);\r
+                        for ( $i = 1; $i <= $ncols; $i++ ) {\r
+                                $cols[] = '"'.OCIColumnName($stmt, $i).'"';\r
+                        }\r
+                        $result = false;\r
+                       \r
+                        OCIFreeStatement($stmt); \r
+                        $fields = implode(',', $cols);\r
+                        $nrows += $offset;\r
+                        $offset += 1; // in Oracle rownum starts at 1\r
+                       \r
+                       if ($this->databaseType == 'oci8po') {\r
+                                        $sql = "SELECT $fields FROM".\r
+                                         "(SELECT rownum as adodb_rownum, $fields FROM".\r
+                                         " ($sql) WHERE rownum <= ?".\r
+                                         ") WHERE adodb_rownum >= ?";\r
+                               } else {\r
+                                        $sql = "SELECT $fields FROM".\r
+                                         "(SELECT rownum as adodb_rownum, $fields FROM".\r
+                                         " ($sql) WHERE rownum <= :adodb_nrows".\r
+                                         ") WHERE adodb_rownum >= :adodb_offset";\r
+                               } \r
+                               $inputarr['adodb_nrows'] = $nrows;\r
+                               $inputarr['adodb_offset'] = $offset;\r
+                               \r
+                       if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);\r
+                       else $rs =& $this->Execute($sql,$inputarr);\r
+                       return $rs;\r
+               }\r
+       \r
+       }\r
+       \r
+       /**\r
+       * Usage:\r
+       * Store BLOBs and CLOBs\r
+       *\r
+       * Example: to store $var in a blob\r
+       *\r
+       *       $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');\r
+       *       $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');\r
+       *       \r
+       *       $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.\r
+       *\r
+       *  to get length of LOB:\r
+       *       select DBMS_LOB.GETLENGTH(ablob) from TABLE\r
+       *\r
+       * If you are using CURSOR_SHARING = force, it appears this will case a segfault\r
+       * under oracle 8.1.7.0. Run:\r
+       *        $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');\r
+       * before UpdateBlob() then...\r
+       */\r
+\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               \r
+               //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;\r
+               \r
+               switch(strtoupper($blobtype)) {\r
+               default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;\r
+               case 'BLOB': $type = OCI_B_BLOB; break;\r
+               case 'CLOB': $type = OCI_B_CLOB; break;\r
+               }\r
+               \r
+               if ($this->databaseType == 'oci8po') \r
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";\r
+               else \r
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";\r
+               \r
+               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);\r
+               $arr['blob'] = array($desc,-1,$type);\r
+               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');\r
+               $commit = $this->autoCommit;\r
+               if ($commit) $this->BeginTrans();\r
+               $rs = ADODB_oci8::Execute($sql,$arr);\r
+               if ($rez = !empty($rs)) $desc->save($val);\r
+               $desc->free();\r
+               if ($commit) $this->CommitTrans();\r
+               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');\r
+               \r
+               if ($rez) $rs->Close();\r
+               return $rez;\r
+       }\r
+       \r
+       /**\r
+       * Usage:  store file pointed to by $var in a blob\r
+       */\r
+       function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               switch(strtoupper($blobtype)) {\r
+               default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;\r
+               case 'BLOB': $type = OCI_B_BLOB; break;\r
+               case 'CLOB': $type = OCI_B_CLOB; break;\r
+               }\r
+               \r
+               if ($this->databaseType == 'oci8po') \r
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";\r
+               else \r
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";\r
+               \r
+               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);\r
+               $arr['blob'] = array($desc,-1,$type);\r
+               \r
+               $this->BeginTrans();\r
+               $rs = ADODB_oci8::Execute($sql,$arr);\r
+               if ($rez = !empty($rs)) $desc->savefile($val);\r
+               $desc->free();\r
+               $this->CommitTrans();\r
+               \r
+               if ($rez) $rs->Close();\r
+               return $rez;\r
+       }\r
+\r
+       \r
+       /*\r
+               Example of usage:\r
+               \r
+               $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
+       */\r
+       function Prepare($sql,$cursor=false)\r
+       {\r
+       static $BINDNUM = 0;\r
+       \r
+               $stmt = OCIParse($this->_connectionID,$sql);\r
+\r
+               if (!$stmt) return false;\r
+\r
+               $BINDNUM += 1;\r
+               \r
+               if (@OCIStatementType($stmt) == 'BEGIN') {\r
+                       return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);\r
+               } \r
+               \r
+               return array($sql,$stmt,0,$BINDNUM);\r
+       }\r
+       \r
+       /*\r
+               Call an oracle stored procedure and return a cursor variable. \r
+               Convert the cursor variable into a recordset. \r
+               Concept by Robert Tuttle robert@ud.com\r
+               \r
+               Example:\r
+                       Note: we return a cursor variable in :RS2\r
+                       $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');\r
+                       \r
+                       $rs = $db->ExecuteCursor(\r
+                               "BEGIN :RS2 = adodb.getdata(:VAR1); END;", \r
+                               'RS2',\r
+                               array('VAR1' => 'Mr Bean'));\r
+                       \r
+       */\r
+       function &ExecuteCursor($sql,$cursorName='rs',$params=false)\r
+       {\r
+               $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor\r
+                       \r
+               if (is_array($stmt) && sizeof($stmt) >= 5) {\r
+                       $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);\r
+                       if ($params) {\r
+                               foreach($params as $k => $v) {\r
+                                       $this->Parameter($stmt,$params[$k], $k);\r
+                               }\r
+                       }\r
+               }\r
+               return $this->Execute($stmt);\r
+       }\r
+       \r
+       /*\r
+               Bind a variable -- very, very fast for executing repeated statements in oracle. \r
+               Better than using\r
+                       for ($i = 0; $i < $max; $i++) { \r
+                               $p1 = ?; $p2 = ?; $p3 = ?;\r
+                               $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", \r
+                                       array($p1,$p2,$p3));\r
+                       }\r
+               \r
+               Usage:\r
+                       $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");\r
+                       $DB->Bind($stmt, $p1);\r
+                       $DB->Bind($stmt, $p2);\r
+                       $DB->Bind($stmt, $p3);\r
+                       for ($i = 0; $i < $max; $i++) { \r
+                               $p1 = ?; $p2 = ?; $p3 = ?;\r
+                               $DB->Execute($stmt);\r
+                       }\r
+                       \r
+               Some timings:           \r
+                       ** Test table has 3 cols, and 1 index. Test to insert 1000 records\r
+                       Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute\r
+                       Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute\r
+                       Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute\r
+                       \r
+               Now if PHP only had batch/bulk updating like Java or PL/SQL...\r
+       \r
+               Note that the order of parameters differs from OCIBindByName,\r
+               because we default the names to :0, :1, :2\r
+       */\r
+       function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false)\r
+       {\r
+               \r
+               if (!is_array($stmt)) return false;\r
+        \r
+        if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { \r
+            return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);\r
+        }\r
+        \r
+               if ($name == false) {\r
+                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size,$type);\r
+                       else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator\r
+                       $stmt[2] += 1;\r
+               } else if (oci_lob_desc($type)) {\r
+                       if ($this->debug) {\r
+                               ADOConnection::outp("<b>Bind</b>: name = $name");\r
+                       }\r
+            //we have to create a new Descriptor here\r
+                       $numlob = count($this -> _refLOBs);\r
+               $this -> _refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type));\r
+                       $this -> _refLOBs[$numlob]['TYPE'] = $isOutput;\r
+                       \r
+                       $tmp = &$this -> _refLOBs[$numlob]['LOB'];\r
+               $rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type);\r
+                       if ($this->debug) {\r
+                               ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var binded");\r
+                       }\r
+                       \r
+                       // if type is input then write data to lob now\r
+                       if ($isOutput == false) {\r
+                               $var = $this -> BlobEncode($var);\r
+                               $tmp -> WriteTemporary($var);\r
+                               if ($this->debug) {\r
+                                       ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");\r
+                               }\r
+                       } else {\r
+                               $this -> _refLOBs[$numlob]['VAR'] = &$var;\r
+                       }\r
+                       $rez = $tmp;\r
+               } else {\r
+                       if ($this->debug) \r
+                               ADOConnection::outp("<b>Bind</b>: name = $name");\r
+                       \r
+                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);\r
+                       else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator\r
+               }\r
+               \r
+               return $rez;\r
+       }\r
+       \r
+       function Param($name)\r
+       {\r
+               return ':'.$name;\r
+       }\r
+       \r
+       /* \r
+       Usage:\r
+               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');\r
+               $db->Parameter($stmt,$id,'myid');\r
+               $db->Parameter($stmt,$group,'group');\r
+               $db->Execute($stmt);\r
+               \r
+               @param $stmt Statement returned by Prepare() or PrepareSP().\r
+               @param $var PHP variable to bind to\r
+               @param $name Name of stored procedure variable name to bind to.\r
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
+               @param [$maxLen] Holds an maximum length of the variable.\r
+               @param [$type] The data type of $var. Legal values depend on driver.\r
+               \r
+               See OCIBindByName documentation at php.net.\r
+       */\r
+       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)\r
+       {\r
+                       if  ($this->debug) {\r
+                               $prefix = ($isOutput) ? 'Out' : 'In';\r
+                               $ztype = (empty($type)) ? 'false' : $type;\r
+                               ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");\r
+                       }\r
+                       return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput);\r
+       }\r
+       \r
+       /*\r
+       returns query ID if successful, otherwise false\r
+       this version supports:\r
+       \r
+          1. $db->execute('select * from table');\r
+          \r
+          2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');\r
+                 $db->execute($prepared_statement, array(1,2,3));\r
+                 \r
+          3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));\r
+          \r
+          4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');\r
+                 $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); \r
+                 $db->execute($stmt);\r
+       */ \r
+       function _query($sql,$inputarr)\r
+       {\r
+               \r
+               if (is_array($sql)) { // is prepared sql\r
+                       $stmt = $sql[1];\r
+                       \r
+                       // we try to bind to permanent array, so that OCIBindByName is persistent\r
+                       // and carried out once only - note that max array element size is 4000 chars\r
+                       if (is_array($inputarr)) {\r
+                               $bindpos = $sql[3];\r
+                               if (isset($this->_bind[$bindpos])) {\r
+                               // all tied up already\r
+                                       $bindarr = &$this->_bind[$bindpos];\r
+                               } else {\r
+                               // one statement to bind them all\r
+                                       $bindarr = array();\r
+                                       foreach($inputarr as $k => $v) {\r
+                                               $bindarr[$k] = $v;\r
+                                               OCIBindByName($stmt,":$k",$bindarr[$k],4000);\r
+                                       }\r
+                                       $this->_bind[$bindpos] = &$bindarr;\r
+                               }\r
+                       }\r
+               } else {\r
+                       $stmt=OCIParse($this->_connectionID,$sql);\r
+               }\r
+                       \r
+               $this->_stmt = $stmt;\r
+               if (!$stmt) return false;\r
+       \r
+               if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);\r
+                       \r
+               if (is_array($inputarr)) {\r
+                       foreach($inputarr as $k => $v) {\r
+                               if (is_array($v)) {\r
+                                       if (sizeof($v) == 2) // suggested by g.giunta@libero.\r
+                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);\r
+                                       else\r
+                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);\r
+                                       \r
+                                       if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';\r
+                               } else {\r
+                                       $len = -1;\r
+                                       if ($v === ' ') $len = 1;\r
+                                       if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again\r
+                                               $bindarr[$k] = $v;\r
+                                       } else {                                // dynamic sql, so rebind every time\r
+                                               OCIBindByName($stmt,":$k",$inputarr[$k],$len);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+        $this->_errorMsg = false;\r
+               $this->_errorCode = false;\r
+               if (OCIExecute($stmt,$this->_commit)) {\r
+//OCIInternalDebug(1);                 \r
+                       if (count($this -> _refLOBs) > 0) {\r
+               \r
+                               foreach ($this -> _refLOBs as $key => $value) {\r
+                                       if ($this -> _refLOBs[$key]['TYPE'] == true) {\r
+                                               $tmp = $this -> _refLOBs[$key]['LOB'] -> load();\r
+                                               if ($this -> debug) {\r
+                                                       ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");\r
+                                               }\r
+                                               //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;\r
+                                               $this -> _refLOBs[$key]['VAR'] = $tmp;\r
+                                       }\r
+                                       $this -> _refLOBs[$key]['LOB'] -> free();\r
+                                       unset($this -> _refLOBs[$key]);\r
+                               }\r
+                       }\r
+               \r
+            switch (@OCIStatementType($stmt)) {\r
+                case "SELECT":\r
+                                       return $stmt;\r
+                                       \r
+                case "BEGIN":\r
+                    if (is_array($sql) && !empty($sql[4])) {\r
+                                               $cursor = $sql[4];\r
+                                               if (is_resource($cursor)) {\r
+                                                       $ok = OCIExecute($cursor);      \r
+                               return $cursor;\r
+                                               }\r
+                                               return $stmt;\r
+                    } else {\r
+                                               if (is_resource($stmt)) {\r
+                                                       OCIFreeStatement($stmt);\r
+                                                       return true;\r
+                                               }\r
+                        return $stmt;\r
+                    }\r
+                    break;\r
+                default :\r
+                                       // ociclose -- no because it could be used in a LOB?\r
+                    return true;\r
+            }\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if (!$this->autoCommit) OCIRollback($this->_connectionID);\r
+               if (count($this -> _refLOBs) > 0) {\r
+                       foreach ($this -> _refLOBs as $key => $value) {\r
+                               $this -> _refLOBs[$key] -> free();\r
+                               unset($this -> _refLOBs[$key]);\r
+                       }\r
+               }\r
+               OCILogoff($this->_connectionID);\r
+               $this->_stmt = false;\r
+               $this->_connectionID = false;\r
+       }\r
+       \r
+       function MetaPrimaryKeys($table, $owner=false,$internalKey=false)\r
+       {\r
+               if ($internalKey) return array('ROWID');\r
+               \r
+       // tested with oracle 8.1.7\r
+               $table = strtoupper($table);\r
+               if ($owner) {\r
+                       $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";\r
+                       $ptab = 'ALL_';\r
+               } else {\r
+                       $owner_clause = '';\r
+                       $ptab = 'USER_';\r
+               }\r
+               $sql = "\r
+SELECT /*+ RULE */ distinct b.column_name\r
+   FROM {$ptab}CONSTRAINTS a\r
+         , {$ptab}CONS_COLUMNS b\r
+  WHERE ( UPPER(b.table_name) = ('$table'))\r
+       AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')\r
+       $owner_clause\r
+       AND (a.constraint_name = b.constraint_name)";\r
+\r
+               $rs = $this->Execute($sql);\r
+               if ($rs && !$rs->EOF) {\r
+                       $arr =& $rs->GetArray();\r
+                       $a = array();\r
+                       foreach($arr as $v) {\r
+                               $a[] = reset($v);\r
+                       }\r
+                       return $a;\r
+               }\r
+               else return false;\r
+       }\r
+       \r
+       // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html\r
+       function MetaForeignKeys($table, $owner=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $table = $this->qstr(strtoupper($table));\r
+               if (!$owner) {\r
+                       $owner = $this->user;\r
+                       $tabp = 'user_';\r
+               } else\r
+                       $tabp = 'all_';\r
+                       \r
+               $owner = ' and owner='.$this->qstr(strtoupper($owner));\r
+               \r
+               $sql = \r
+"select constraint_name,r_owner,r_constraint_name \r
+       from {$tabp}constraints\r
+       where constraint_type = 'R' and table_name = $table $owner";\r
+               \r
+               $constraints =& $this->GetArray($sql);\r
+               $arr = false;\r
+               foreach($constraints as $constr) {\r
+                       $cons = $this->qstr($constr[0]);\r
+                       $rowner = $this->qstr($constr[1]);\r
+                       $rcons = $this->qstr($constr[2]);\r
+                       $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");\r
+                       $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");\r
+                       \r
+                       if ($cols && $tabcol) \r
+                               for ($i=0, $max=sizeof($cols); $i < $max; $i++) {\r
+                                       $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];\r
+                               }\r
+               }\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               return $arr;\r
+       }\r
+\r
+       \r
+       function CharMax()\r
+       {\r
+               return 4000;\r
+       }\r
+       \r
+       function TextMax()\r
+       {\r
+               return 4000;\r
+       }\r
+       \r
+       /**\r
+        * Quotes a string.\r
+        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());\r
+        * \r
+        * @param s                     the string to quote\r
+        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().\r
+        *                              This undoes the stupidity of magic quotes for GPC.\r
+        *\r
+        * @return  quoted string to be sent back to database\r
+        */\r
+       function qstr($s,$magic_quotes=false)\r
+       {       \r
+       $nofixquotes=false;\r
+       \r
+               if ($this->noNullStrings && strlen($s)==0)$s = ' ';\r
+               if (!$magic_quotes) {   \r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               $s = str_replace('\\','\\\\',$s);\r
+                       }\r
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";\r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               \r
+               $s = str_replace('\\\\','\\',$s);\r
+               return "'".str_replace("\\'",$this->replaceQuote,$s)."'";\r
+               \r
+       }\r
+       \r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+                Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_oci8 extends ADORecordSet {\r
+\r
+       var $databaseType = 'oci8';\r
+       var $bind=false;\r
+       var $_fieldobjs;\r
+       //var $_arr = false;\r
+               \r
+       function ADORecordset_oci8($queryID,$mode=false)\r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode)\r
+               {\r
+               default:\r
+               case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
+               }\r
+\r
+               $this->_queryID = $queryID;\r
+       }\r
+\r
+\r
+       function Init()\r
+       {\r
+               if ($this->_inited) return;\r
+               \r
+               $this->_inited = true;\r
+               if ($this->_queryID) {\r
+                       \r
+                       $this->_currentRow = 0;\r
+                       @$this->_initrs();\r
+                       $this->EOF = !$this->_fetch();\r
+                       \r
+                       /*\r
+                       // based on idea by Gaetano Giunta to detect unusual oracle errors\r
+                       // see http://phplens.com/lens/lensforum/msgs.php?id=6771\r
+                       $err = OCIError($this->_queryID);\r
+                       if ($err && $this->connection->debug) ADOConnection::outp($err);\r
+                       */\r
+                       \r
+                       if (!is_array($this->fields)) {\r
+                               $this->_numOfRows = 0;\r
+                               $this->fields = array();\r
+                       }\r
+               } else {\r
+                       $this->fields = array();\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+                       $this->EOF = true;\r
+               }\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+               $this->_numOfRows = -1;\r
+               $this->_numOfFields = OCInumcols($this->_queryID);\r
+               if ($this->_numOfFields>0) {\r
+                       $this->_fieldobjs = array();\r
+                       $max = $this->_numOfFields;\r
+                       for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);\r
+               }\r
+       }\r
+\r
+         /*            Returns: an object containing field information.\r
+                         Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                         fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                         fetchField() is retrieved.            */\r
+\r
+       function &_FetchField($fieldOffset = -1)\r
+       {\r
+               $fld = new ADOFieldObject;\r
+               $fieldOffset += 1;\r
+               $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);\r
+               $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);\r
+               $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);\r
+               if ($fld->type == 'NUMBER') {\r
+                       $p = OCIColumnPrecision($this->_queryID, $fieldOffset);\r
+                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);\r
+                       if ($p != 0 && $sc == 0) $fld->type = 'INT';\r
+                       //echo " $this->name ($p.$sc) ";\r
+               }\r
+               return $fld;\r
+       }\r
+       \r
+       /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */\r
+       function &FetchField($fieldOffset = -1)\r
+       {\r
+               return $this->_fieldobjs[$fieldOffset];\r
+       }\r
+       \r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);\r
+               \r
+               if ($this->EOF) return false;\r
+               \r
+               $this->_currentRow++;\r
+               if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))\r
+                       return true;\r
+               $this->EOF = true;\r
+               \r
+               return false;\r
+       }       \r
+       \r
+       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {\r
+               if ($offset <= 0) {\r
+                       $arr =& $this->GetArray($nrows);\r
+                       return $arr;\r
+               }\r
+               for ($i=1; $i < $offset; $i++) \r
+                       if (!@OCIFetch($this->_queryID)) return array();\r
+                       \r
+               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();\r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+\r
+\r
+       function _seek($row)\r
+       {\r
+               return false;\r
+       }\r
+\r
+       function _fetch() \r
+       {\r
+               return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);\r
+       }\r
+\r
+       /*              close() only needs to be called if you are worried about using too much memory while your script\r
+                       is running. All associated result memory for the specified result identifier will automatically be freed.               */\r
+\r
+       function _close() \r
+       {\r
+               if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;\r
+               OCIFreeStatement($this->_queryID);\r
+               $this->_queryID = false;\r
+               \r
+       }\r
+\r
+       function MetaType($t,$len=-1)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'VARCHAR2':\r
+               case 'CHAR':\r
+               case 'VARBINARY':\r
+               case 'BINARY':\r
+               case 'NCHAR':\r
+               case 'NVARCHAR':\r
+               case 'NVARCHAR2':\r
+                                if (isset($this) && $len <= $this->blobSize) return 'C';\r
+               \r
+               case 'NCLOB':\r
+               case 'LONG':\r
+               case 'LONG VARCHAR':\r
+               case 'CLOB':\r
+               return 'X';\r
+               \r
+               case 'LONG RAW':\r
+               case 'LONG VARBINARY':\r
+               case 'BLOB':\r
+                       return 'B';\r
+               \r
+               case 'DATE': \r
+                       return  ($this->connection->datetime) ? 'T' : 'D';\r
+               \r
+               \r
+               case 'TIMESTAMP': return 'T';\r
+               \r
+               case 'INT': \r
+               case 'SMALLINT':\r
+               case 'INTEGER': \r
+                       return 'I';\r
+                       \r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 51f61d44ccabbb924dbef3d08e9acc23302b3701..5790fbefa3083cac3dcb806eec7854fbfd138579 100644 (file)
@@ -1,56 +1,59 @@
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
- * Whenever there is any discrepancy between the two licenses, 
- * the BSD license will take precedence. 
- *
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com
- *
- * Oracle 8.0.5 driver
-*/
-
-include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
-
-class ADODB_oci805 extends ADODB_oci8 {
-       var $databaseType = "oci805";   
-       var $connectSID = true;
-       
-       function ADODB_oci805() 
-       {
-               $this->ADODB_oci8();
-       }
-       
-       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)
-                       $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
-               else
-                       $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
-               
-               /* 
-                       The following is only available from 8.1.5 because order by in inline views not 
-                       available before then...
-                       http://www.jlcomp.demon.co.uk/faq/top_sql.html
-               if ($nrows > 0) {       
-                       if ($offset > 0) $nrows += $offset;
-                       $sql = "select * from ($sql) where rownum <= $nrows";
-                       $nrows = -1;
-               }
-               */
-
-               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-       }
-}
-
-class ADORecordset_oci805 extends ADORecordset_oci8 {  
-       var $databaseType = "oci805";
-       function ADORecordset_oci805($id,$mode=false)
-       {
-               $this->ADORecordset_oci8($id,$mode);
-       }
-}
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+ * Oracle 8.0.5 driver\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');\r
+\r
+class ADODB_oci805 extends ADODB_oci8 {\r
+       var $databaseType = "oci805";   \r
+       var $connectSID = true;\r
+       \r
+       function ADODB_oci805() \r
+       {\r
+               $this->ADODB_oci8();\r
+       }\r
+       \r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               // seems that oracle only supports 1 hint comment in 8i\r
+               if (strpos($sql,'/*+') !== false)\r
+                       $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);\r
+               else\r
+                       $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);\r
+               \r
+               /* \r
+                       The following is only available from 8.1.5 because order by in inline views not \r
+                       available before then...\r
+                       http://www.jlcomp.demon.co.uk/faq/top_sql.html\r
+               if ($nrows > 0) {       \r
+                       if ($offset > 0) $nrows += $offset;\r
+                       $sql = "select * from ($sql) where rownum <= $nrows";\r
+                       $nrows = -1;\r
+               }\r
+               */\r
+\r
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+       }\r
+}\r
+\r
+class ADORecordset_oci805 extends ADORecordset_oci8 {  \r
+       var $databaseType = "oci805";\r
+       function ADORecordset_oci805($id,$mode=false)\r
+       {\r
+               $this->ADORecordset_oci8($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 1cccd8efe392627d28ef66d35cd820f690a7d4d7..63a1280166b3bfb5e57a6812b20e2200e586d4ab 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-  Latest version is available at http://php.weblogs.com/
-  
-  Portable version of oci8 driver, to make it more similar to other database drivers.
-  The main differences are
-
-   1. that the OCI_ASSOC names are in lowercase instead of uppercase.
-   2. bind variables are mapped using ? instead of :<bindvar>
-
-   Should some emulation of RecordCount() be implemented?
-  
-*/
-
-include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
-
-class ADODB_oci8po extends ADODB_oci8 {
-       var $databaseType = 'oci8po';
-       var $dataProvider = 'oci8';
-       var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
-       var $metaTablesSQL = "select lower(table_name),table_type from cat where table_type in ('TABLE','VIEW')";
-       
-       function ADODB_oci8po()
-       {
-               $this->ADODB_oci8();
-       }
-       
-       function Param($name)
-       {
-               return '?';
-       }
-       
-       function Prepare($sql,$cursor=false)
-       {
-               $sqlarr = explode('?',$sql);
-               $sql = $sqlarr[0];
-               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
-                       $sql .=  ':'.($i-1) . $sqlarr[$i];
-               } 
-               return ADODB_oci8::Prepare($sql,$cursor);
-       }
-       
-       // emulate handling of parameters ? ?, replacing with :bind0 :bind1
-       function _query($sql,$inputarr)
-       {
-               if (is_array($inputarr)) {
-                       $i = 0;
-                       if (is_array($sql)) {
-                               foreach($inputarr as $v) {
-                                       $arr['bind'.$i++] = $v;
-                               } 
-                       } else {
-                               $sqlarr = explode('?',$sql);
-                               $sql = $sqlarr[0];
-                               foreach($inputarr as $k => $v) {
-                                       $sql .=  ":$k" . $sqlarr[++$i];
-                               }
-                       }
-               }
-               return ADODB_oci8::_query($sql,$inputarr);
-       }
-}
-
-/*--------------------------------------------------------------------------------------
-                Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_oci8po extends ADORecordset_oci8 {
-
-       var $databaseType = 'oci8po';
-       
-               function ADORecordset_oci8po($queryID,$mode=false)
-               {
-                       $this->ADORecordset_oci8($queryID,$mode);
-               }
-
-               function Fields($colname)
-               {
-                       if ($this->fetchMode & OCI_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)]];
-               }
-               
-               // lowercase field names...
-               function &_FetchField($fieldOffset = -1)
-               {
-                                $fld = new ADOFieldObject;
-                                $fieldOffset += 1;
-                                $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
-                                $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
-                                $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
-                                if ($fld->type == 'NUMBER') {
-                                       //$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
-                                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);
-                                       if ($sc == 0) $fld->type = 'INT';
-                                }
-                                return $fld;
-               }
-
-       // 10% speedup to move MoveNext to child class
-       function MoveNext() 
-       {
-       
-               if (!$this->EOF) {              
-                       $this->_currentRow++;
-                       if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
-                       global $ADODB_ANSI_PADDING_OFF;
-       
-                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
-                               if (!empty($ADODB_ANSI_PADDING_OFF)) {
-                                       foreach($this->fields as $k => $v) {
-                                               if (is_string($v)) $this->fields[$k] = rtrim($v);
-                                       }
-                               }
-                               return true;
-                       }
-                       $this->EOF = true;
-               }
-               return false;
-       }       
-       
-       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
-       function &GetArrayLimit($nrows,$offset=-1) 
-       {
-               if ($offset <= 0) return $this->GetArray($nrows);
-               for ($i=1; $i < $offset; $i++) 
-                       if (!@OCIFetch($this->_queryID)) return array();
-                       
-               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
-               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
-               $results = array();
-               $cnt = 0;
-               while (!$this->EOF && $nrows != $cnt) {
-                       $results[$cnt++] = $this->fields;
-                       $this->MoveNext();
-               }
-               
-               return $results;
-       }
-
-       // Create associative array
-       function _updatefields()
-       {
-               if (ADODB_ASSOC_CASE == 2) return; // native
-       
-               $arr = array();
-               $lowercase = (ADODB_ASSOC_CASE == 0);
-               
-               foreach($this->fields as $k => $v) {
-                       if (is_integer($k)) $arr[$k] = $v;
-                       else {
-                               if ($lowercase)
-                                       $arr[strtolower($k)] = $v;
-                               else
-                                       $arr[strtoupper($k)] = $v;
-                       }
-               }
-               $this->fields = $arr;
-       }
-       
-       function _fetch() 
-       {
-               $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
-               if ($ret) {
-               global $ADODB_ANSI_PADDING_OFF;
-       
-                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
-                               if (!empty($ADODB_ANSI_PADDING_OFF)) {
-                                       foreach($this->fields as $k => $v) {
-                                               if (is_string($v)) $this->fields[$k] = rtrim($v);
-                                       }
-                               }
-               }
-               return $ret;
-       }
-       
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim. All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Portable version of oci8 driver, to make it more similar to other database drivers.\r
+  The main differences are\r
+\r
+   1. that the OCI_ASSOC names are in lowercase instead of uppercase.\r
+   2. bind variables are mapped using ? instead of :<bindvar>\r
+\r
+   Should some emulation of RecordCount() be implemented?\r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');\r
+\r
+class ADODB_oci8po extends ADODB_oci8 {\r
+       var $databaseType = 'oci8po';\r
+       var $dataProvider = 'oci8';\r
+       var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net\r
+       var $metaTablesSQL = "select lower(table_name),table_type from cat where table_type in ('TABLE','VIEW')";\r
+       \r
+       function ADODB_oci8po()\r
+       {\r
+               $this->ADODB_oci8();\r
+       }\r
+       \r
+       function Param($name)\r
+       {\r
+               return '?';\r
+       }\r
+       \r
+       function Prepare($sql,$cursor=false)\r
+       {\r
+               $sqlarr = explode('?',$sql);\r
+               $sql = $sqlarr[0];\r
+               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {\r
+                       $sql .=  ':'.($i-1) . $sqlarr[$i];\r
+               } \r
+               return ADODB_oci8::Prepare($sql,$cursor);\r
+       }\r
+       \r
+       // emulate handling of parameters ? ?, replacing with :bind0 :bind1\r
+       function _query($sql,$inputarr)\r
+       {\r
+               if (is_array($inputarr)) {\r
+                       $i = 0;\r
+                       if (is_array($sql)) {\r
+                               foreach($inputarr as $v) {\r
+                                       $arr['bind'.$i++] = $v;\r
+                               } \r
+                       } else {\r
+                               $sqlarr = explode('?',$sql);\r
+                               $sql = $sqlarr[0];\r
+                               foreach($inputarr as $k => $v) {\r
+                                       $sql .=  ":$k" . $sqlarr[++$i];\r
+                               }\r
+                       }\r
+               }\r
+               return ADODB_oci8::_query($sql,$inputarr);\r
+       }\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+                Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_oci8po extends ADORecordset_oci8 {\r
+\r
+       var $databaseType = 'oci8po';\r
+       \r
+               function ADORecordset_oci8po($queryID,$mode=false)\r
+               {\r
+                       $this->ADORecordset_oci8($queryID,$mode);\r
+               }\r
+\r
+               function Fields($colname)\r
+               {\r
+                       if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];\r
+                       \r
+                       if (!$this->bind) {\r
+                               $this->bind = array();\r
+                               for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                                       $o = $this->FetchField($i);\r
+                                       $this->bind[strtoupper($o->name)] = $i;\r
+                               }\r
+                       }\r
+                        return $this->fields[$this->bind[strtoupper($colname)]];\r
+               }\r
+               \r
+               // lowercase field names...\r
+               function &_FetchField($fieldOffset = -1)\r
+               {\r
+                                $fld = new ADOFieldObject;\r
+                                $fieldOffset += 1;\r
+                                $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));\r
+                                $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);\r
+                                $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);\r
+                                if ($fld->type == 'NUMBER') {\r
+                                       //$p = OCIColumnPrecision($this->_queryID, $fieldOffset);\r
+                                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);\r
+                                       if ($sc == 0) $fld->type = 'INT';\r
+                                }\r
+                                return $fld;\r
+               }\r
+\r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+       \r
+               if (!$this->EOF) {              \r
+                       $this->_currentRow++;\r
+                       if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {\r
+                       global $ADODB_ANSI_PADDING_OFF;\r
+       \r
+                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
+                               if (!empty($ADODB_ANSI_PADDING_OFF)) {\r
+                                       foreach($this->fields as $k => $v) {\r
+                                               if (is_string($v)) $this->fields[$k] = rtrim($v);\r
+                                       }\r
+                               }\r
+                               return true;\r
+                       }\r
+                       $this->EOF = true;\r
+               }\r
+               return false;\r
+       }       \r
+       \r
+       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {\r
+               if ($offset <= 0) return $this->GetArray($nrows);\r
+               for ($i=1; $i < $offset; $i++) \r
+                       if (!@OCIFetch($this->_queryID)) return array();\r
+                       \r
+               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();\r
+               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+\r
+       // Create associative array\r
+       function _updatefields()\r
+       {\r
+               if (ADODB_ASSOC_CASE == 2) return; // native\r
+       \r
+               $arr = array();\r
+               $lowercase = (ADODB_ASSOC_CASE == 0);\r
+               \r
+               foreach($this->fields as $k => $v) {\r
+                       if (is_integer($k)) $arr[$k] = $v;\r
+                       else {\r
+                               if ($lowercase)\r
+                                       $arr[strtolower($k)] = $v;\r
+                               else\r
+                                       $arr[strtoupper($k)] = $v;\r
+                       }\r
+               }\r
+               $this->fields = $arr;\r
+       }\r
+       \r
+       function _fetch() \r
+       {\r
+               $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);\r
+               if ($ret) {\r
+               global $ADODB_ANSI_PADDING_OFF;\r
+       \r
+                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
+                               if (!empty($ADODB_ANSI_PADDING_OFF)) {\r
+                                       foreach($this->fields as $k => $v) {\r
+                                               if (is_string($v)) $this->fields[$k] = rtrim($v);\r
+                                       }\r
+                               }\r
+               }\r
+               return $ret;\r
+       }\r
+       \r
+}\r
 ?>
\ No newline at end of file
index 79aadef54b44f6fcf2698a82d7c26c56d8baf886..930f0c201b1d31bcfc5ebae7d521a0ef56af2d7f 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Requires ODBC. Works on Windows and Unix.
-*/
-  define("_ADODB_ODBC_LAYER", 2 );
-        
-/*--------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------*/
-
-
-class ADODB_odbc extends ADOConnection {
-       var $databaseType = "odbc";     
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $dataProvider = "odbc";
-       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;
-       
-       function ADODB_odbc() 
-       {       
-               $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
-               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
-       }
-       
-       function ServerInfo()
-       {
-       
-               if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
-                       $dsn = strtoupper($this->host);
-                       $first = true;
-                       $found = false;
-                       
-                       if (!function_exists('odbc_data_source')) return false;
-                       
-                       while(true) {
-                               
-                               $rez = odbc_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;
-               } else {
-                       return ADOConnection::ServerInfo();
-               }
-       }
-
-       
-       function CreateSequence($seqname='adodbseq',$start=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
-               if (!$ok) return false;
-               $start -= 1;
-               return $this->Execute("insert into $seqname values($start)");
-       }
-       
-       var $_dropSeqSQL = 'drop table %s';
-       function DropSequence($seqname)
-       {
-               if (empty($this->_dropSeqSQL)) return false;
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
-       }
-       
-       /*
-               This algorithm is not very efficient, but works even if table locking
-               is not available.
-               
-               Will return false if unable to generate an ID after $MAXLOOPS attempts.
-       */
-       function GenID($seq='adodbseq',$start=1)
-       {       
-               // if you have to modify the parameter below, your database is overloaded,
-               // or you need to implement generation of id's yourself!
-               $MAXLOOPS = 100;
-               //$this->debug=1;
-               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;
-                               return $num;
-                       }
-               }
-               if ($fn = $this->raiseErrorFn) {
-                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
-               }
-               return false;
-       }
-
-
-       function ErrorMsg()
-       {
-               if ($this->_haserrorfunctions) {
-                       if ($this->_errorMsg !== false) return $this->_errorMsg;
-                       if (empty($this->_connectionID)) return @odbc_errormsg();
-                       return @odbc_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 = @odbc_error(); 
-                       else $e = @odbc_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();
-       }
-       
-       
-       // returns true or false
-       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
-       {
-       global $php_errormsg;
-               
-               if (!function_exists('odbc_connect')) return false;
-               
-               if ($this->debug && $argDatabasename) {
-                       ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
-               }
-               $php_errormsg = '';
-               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
-               else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
-               $this->_errorMsg = $php_errormsg;
-               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
-               
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
-               return $this->_connectionID != false;
-       }
-       
-       // returns true or false
-       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
-       {
-       global $php_errormsg;
-       
-               if (!function_exists('odbc_connect')) return false;
-               
-               $php_errormsg = '';
-               if ($this->debug && $argDatabasename) {
-                       ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
-               }
-       //      print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
-               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
-               else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
-               
-               $this->_errorMsg = $php_errormsg;
-               if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
-               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
-               
-               return $this->_connectionID != false;
-       }
-
-       function BeginTrans()
-       {       
-               if (!$this->hasTransactions) return false;
-               if ($this->transOff) return true; 
-               $this->transCnt += 1;
-               $this->_autocommit = false;
-               return odbc_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 = odbc_commit($this->_connectionID);
-               odbc_autocommit($this->_connectionID,true);
-               return $ret;
-       }
-       
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true; 
-               if ($this->transCnt) $this->transCnt -= 1;
-               $this->_autocommit = true;
-               $ret = odbc_rollback($this->_connectionID);
-               odbc_autocommit($this->_connectionID,true);
-               return $ret;
-       }
-       
-       function MetaPrimaryKeys($table)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $savem = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $qid = @odbc_primarykeys($this->_connectionID,'','',$table);
-               
-               if (!$qid) {
-                       $ADODB_FETCH_MODE = $savem;
-                       return false;
-               }
-               $rs = new ADORecordSet_odbc($qid);
-               $ADODB_FETCH_MODE = $savem;
-               
-               if (!$rs) return false;
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
-               
-               $arr =& $rs->GetArray();
-               $rs->Close();
-               //print_r($arr);
-               $arr2 = array();
-               for ($i=0; $i < sizeof($arr); $i++) {
-                       if ($arr[$i][3]) $arr2[] = $arr[$i][3];
-               }
-               return $arr2;
-       }
-       
-       
-       
-       function &MetaTables($ttype=false)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $savem = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $qid = odbc_tables($this->_connectionID);
-               
-               $rs = new ADORecordSet_odbc($qid);
-               
-               $ADODB_FETCH_MODE = $savem;
-               if (!$rs) return false;
-               
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
-               
-               $arr =& $rs->GetArray();
-               //print_r($arr);
-               
-               $rs->Close();
-               $arr2 = array();
-               
-               if ($ttype) {
-                       $isview = strncmp($ttype,'V',1) === 0;
-               }
-               for ($i=0; $i < sizeof($arr); $i++) {
-                       if (!$arr[$i][2]) continue;
-                       $type = $arr[$i][3];
-                       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];
-               }
-               return $arr2;
-       }
-       
-/*
-/ 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 91:
-               case 11:
-                       return 'D';
-                       
-               case 92:
-               case 93:
-               case 9: 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;
-       
-               $table = strtoupper($table);
-               $schema = false;
-               $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 = odbc_tables($this->_connectionID);
-                       $rs = new ADORecordSet_odbc($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 = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
-               } else switch ($this->databaseType) {
-               case 'access':
-               case 'vfp':
-               case 'db2':
-                       $qid = odbc_columns($this->_connectionID);
-                       break;
-                       
-               default:
-                       $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');
-                       if (empty($qid)) $qid = odbc_columns($this->_connectionID);
-                       break;
-               }
-               if (empty($qid)) return false;
-               
-               $rs = new ADORecordSet_odbc($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($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?
-               
-               return $retarr;
-       }
-       
-       function Prepare($sql)
-       {
-               if (! $this->_bindInputArray) return $sql; // no binding
-               $stmt = odbc_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;
-               $php_errormsg = '';
-               $this->_error = '';
-               
-               if ($inputarr) {
-                       if (is_array($sql)) {
-                               $stmtid = $sql[1];
-                       } else {
-                               $stmtid = odbc_prepare($this->_connectionID,$sql);
-       
-                               if ($stmtid == false) {
-                                       $this->_errorMsg = $php_errormsg;
-                                       return false;
-                               }
-                       }
-                       
-                       if (! odbc_execute($stmtid,$inputarr)) {
-                               //@odbc_free_result($stmtid);
-                               if ($this->_haserrorfunctions) {
-                                       $this->_errorMsg = odbc_errormsg();
-                                       $this->_errorCode = odbc_error();
-                               }
-                               return false;
-                       }
-               
-               } else if (is_array($sql)) {
-                       $stmtid = $sql[1];
-                       if (!odbc_execute($stmtid)) {
-                               //@odbc_free_result($stmtid);
-                               if ($this->_haserrorfunctions) {
-                                       $this->_errorMsg = odbc_errormsg();
-                                       $this->_errorCode = odbc_error();
-                               }
-                               return false;
-                       }
-               } else
-                       $stmtid = odbc_exec($this->_connectionID,$sql);
-               
-               $this->_lastAffectedRows = 0;
-               if ($stmtid) {
-                       if (@odbc_num_fields($stmtid) == 0) {
-                               $this->_lastAffectedRows = odbc_num_rows($stmtid);
-                               $stmtid = true;
-                       } else {
-                               $this->_lastAffectedRows = 0;
-                               odbc_binmode($stmtid,$this->binmode);
-                               odbc_longreadlen($stmtid,$this->maxblobsize);
-                       }
-                       
-                       if ($this->_haserrorfunctions) {
-                               $this->_errorMsg = '';
-                               $this->_errorCode = 0;
-                       } else
-                               $this->_errorMsg = $php_errormsg;
-               } else {
-                       if ($this->_haserrorfunctions) {
-                               $this->_errorMsg = odbc_errormsg();
-                               $this->_errorCode = odbc_error();
-                       } else
-                               $this->_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')
-       {
-               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
-       }
-       
-       // returns true or false
-       function _close()
-       {
-               $ret = @odbc_close($this->_connectionID);
-               $this->_connectionID = false;
-               return $ret;
-       }
-
-       function _affectedrows()
-       {
-               return $this->_lastAffectedRows;
-       }
-       
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_odbc extends ADORecordSet { 
-       
-       var $bind = false;
-       var $databaseType = "odbc";             
-       var $dataProvider = "odbc";
-       var $useFetchArray;
-       var $_has_stupid_odbc_fetch_api_change;
-       
-       function ADORecordSet_odbc($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 = @odbc_field_name($this->_queryID,$off);
-               $o->type = @odbc_field_type($this->_queryID,$off);
-               $o->max_length = @odbc_field_len($this->_queryID,$off);
-               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
-               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
-               return $o;
-       }
-       
-       /* 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) ? @odbc_num_rows($this->_queryID) : -1;
-               $this->_numOfFields = @odbc_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++;
-                       $row = 0;
-                       if ($this->_has_stupid_odbc_fetch_api_change)
-                               $rez = @odbc_fetch_into($this->_queryID,$this->fields);
-                       else 
-                               $rez = @odbc_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()
-       {
-               $row = 0;
-               if ($this->_has_stupid_odbc_fetch_api_change)
-                       $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row);
-               else 
-                       $rez = @odbc_fetch_into($this->_queryID,$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 @odbc_free_result($this->_queryID);              
-       }
-
-}
-
-?>
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Requires ODBC. Works on Windows and Unix.\r
+*/\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+  define("_ADODB_ODBC_LAYER", 2 );\r
+        \r
+/*--------------------------------------------------------------------------------------\r
+--------------------------------------------------------------------------------------*/\r
+\r
+\r
+class ADODB_odbc extends ADOConnection {\r
+       var $databaseType = "odbc";     \r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $dataProvider = "odbc";\r
+       var $hasAffectedRows = true;\r
+       var $binmode = ODBC_BINMODE_RETURN;\r
+       var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive\r
+                                                               // breaking backward-compat\r
+       //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field\r
+       var $_bindInputArray = false;   \r
+       var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L\r
+       var $_genSeqSQL = "create table %s (id integer)";\r
+       var $_autocommit = true;\r
+       var $_haserrorfunctions = true;\r
+       var $_has_stupid_odbc_fetch_api_change = true;\r
+       var $_lastAffectedRows = 0;\r
+       \r
+       function ADODB_odbc() \r
+       {       \r
+               $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;\r
+               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+       \r
+               if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {\r
+                       $dsn = strtoupper($this->host);\r
+                       $first = true;\r
+                       $found = false;\r
+                       \r
+                       if (!function_exists('odbc_data_source')) return false;\r
+                       \r
+                       while(true) {\r
+                               \r
+                               $rez = odbc_data_source($this->_connectionID,\r
+                                       $first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);\r
+                               $first = false;\r
+                               if (!is_array($rez)) break;\r
+                               if (strtoupper($rez['server']) == $dsn) {\r
+                                       $found = true;\r
+                                       break;\r
+                               }\r
+                       } \r
+                       if (!$found) return ADOConnection::ServerInfo();\r
+                       if (!isset($rez['version'])) $rez['version'] = '';\r
+                       return $rez;\r
+               } else {\r
+                       return ADOConnection::ServerInfo();\r
+               }\r
+       }\r
+\r
+       \r
+       function CreateSequence($seqname='adodbseq',$start=1)\r
+       {\r
+               if (empty($this->_genSeqSQL)) return false;\r
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+               if (!$ok) return false;\r
+               $start -= 1;\r
+               return $this->Execute("insert into $seqname values($start)");\r
+       }\r
+       \r
+       var $_dropSeqSQL = 'drop table %s';\r
+       function DropSequence($seqname)\r
+       {\r
+               if (empty($this->_dropSeqSQL)) return false;\r
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
+       }\r
+       \r
+       /*\r
+               This algorithm is not very efficient, but works even if table locking\r
+               is not available.\r
+               \r
+               Will return false if unable to generate an ID after $MAXLOOPS attempts.\r
+       */\r
+       function GenID($seq='adodbseq',$start=1)\r
+       {       \r
+               // if you have to modify the parameter below, your database is overloaded,\r
+               // or you need to implement generation of id's yourself!\r
+               $MAXLOOPS = 100;\r
+               //$this->debug=1;\r
+               while (--$MAXLOOPS>=0) {\r
+                       $num = $this->GetOne("select id from $seq");\r
+                       if ($num === false) {\r
+                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       \r
+                               $start -= 1;\r
+                               $num = '0';\r
+                               $ok = $this->Execute("insert into $seq values($start)");\r
+                               if (!$ok) return false;\r
+                       } \r
+                       $this->Execute("update $seq set id=id+1 where id=$num");\r
+                       \r
+                       if ($this->affected_rows() > 0) {\r
+                               $num += 1;\r
+                               $this->genID = $num;\r
+                               return $num;\r
+                       }\r
+               }\r
+               if ($fn = $this->raiseErrorFn) {\r
+                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);\r
+               }\r
+               return false;\r
+       }\r
+\r
+\r
+       function ErrorMsg()\r
+       {\r
+               if ($this->_haserrorfunctions) {\r
+                       if ($this->_errorMsg !== false) return $this->_errorMsg;\r
+                       if (empty($this->_connectionID)) return @odbc_errormsg();\r
+                       return @odbc_errormsg($this->_connectionID);\r
+               } else return ADOConnection::ErrorMsg();\r
+       }\r
+       \r
+       function ErrorNo()\r
+       {\r
+               \r
+               if ($this->_haserrorfunctions) {\r
+                       if ($this->_errorCode !== false) {\r
+                               // bug in 4.0.6, error number can be corrupted string (should be 6 digits)\r
+                               return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;\r
+                       }\r
+\r
+                       if (empty($this->_connectionID)) $e = @odbc_error(); \r
+                       else $e = @odbc_error($this->_connectionID);\r
+                       \r
+                        // bug in 4.0.6, error number can be corrupted string (should be 6 digits)\r
+                        // so we check and patch\r
+                       if (strlen($e)<=2) return 0;\r
+                       return $e;\r
+               } else return ADOConnection::ErrorNo();\r
+       }\r
+       \r
+       \r
+       // returns true or false\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+               \r
+               if (!function_exists('odbc_connect')) return null;\r
+               \r
+               if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') {\r
+                       ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");\r
+               }\r
+               if (isset($php_errormsg)) $php_errormsg = '';\r
+               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);\r
+               else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);\r
+               $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);\r
+               \r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+       \r
+               if (!function_exists('odbc_connect')) return null;\r
+               \r
+               if (isset($php_errormsg)) $php_errormsg = '';\r
+               $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+               if ($this->debug && $argDatabasename) {\r
+                       ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");\r
+               }\r
+       //      print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();\r
+               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);\r
+               else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);\r
+               \r
+               $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+               if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);\r
+               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);\r
+               \r
+               return $this->_connectionID != false;\r
+       }\r
+\r
+       function BeginTrans()\r
+       {       \r
+               if (!$this->hasTransactions) return false;\r
+               if ($this->transOff) return true; \r
+               $this->transCnt += 1;\r
+               $this->_autocommit = false;\r
+               return odbc_autocommit($this->_connectionID,false);\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               $ret = odbc_commit($this->_connectionID);\r
+               odbc_autocommit($this->_connectionID,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true; \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               $ret = odbc_rollback($this->_connectionID);\r
+               odbc_autocommit($this->_connectionID,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function MetaPrimaryKeys($table)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $qid = @odbc_primarykeys($this->_connectionID,'','',$table);\r
+               \r
+               if (!$qid) {\r
+                       $ADODB_FETCH_MODE = $savem;\r
+                       return false;\r
+               }\r
+               $rs = new ADORecordSet_odbc($qid);\r
+               $ADODB_FETCH_MODE = $savem;\r
+               \r
+               if (!$rs) return false;\r
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+               \r
+               $arr =& $rs->GetArray();\r
+               $rs->Close();\r
+               //print_r($arr);\r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][3]) $arr2[] = $arr[$i][3];\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+       \r
+       \r
+       function &MetaTables($ttype=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $qid = odbc_tables($this->_connectionID);\r
+               \r
+               $rs = new ADORecordSet_odbc($qid);\r
+               \r
+               $ADODB_FETCH_MODE = $savem;\r
+               if (!$rs) return false;\r
+               \r
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+               \r
+               $arr =& $rs->GetArray();\r
+               //print_r($arr);\r
+               \r
+               $rs->Close();\r
+               $arr2 = array();\r
+               \r
+               if ($ttype) {\r
+                       $isview = strncmp($ttype,'V',1) === 0;\r
+               }\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if (!$arr[$i][2]) continue;\r
+                       $type = $arr[$i][3];\r
+                       if ($ttype) { \r
+                               if ($isview) {\r
+                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];\r
+                               } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];\r
+                       } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+/*\r
+/ SQL data type codes /\r
+#define        SQL_UNKNOWN_TYPE        0\r
+#define SQL_CHAR                       1\r
+#define SQL_NUMERIC             2\r
+#define SQL_DECIMAL             3\r
+#define SQL_INTEGER             4\r
+#define SQL_SMALLINT           5\r
+#define SQL_FLOAT                 6\r
+#define SQL_REAL                       7\r
+#define SQL_DOUBLE               8\r
+#if (ODBCVER >= 0x0300)\r
+#define SQL_DATETIME           9\r
+#endif\r
+#define SQL_VARCHAR            12\r
+\r
+/ One-parameter shortcuts for date/time data types /\r
+#if (ODBCVER >= 0x0300)\r
+#define SQL_TYPE_DATE    91\r
+#define SQL_TYPE_TIME    92\r
+#define SQL_TYPE_TIMESTAMP 93\r
+\r
+#define SQL_UNICODE                             (-95)\r
+#define SQL_UNICODE_VARCHAR                     (-96)\r
+#define SQL_UNICODE_LONGVARCHAR                 (-97)\r
+*/\r
+       function ODBCTypes($t)\r
+       {\r
+               switch ((integer)$t) {\r
+               case 1: \r
+               case 12:\r
+               case 0:\r
+               case -95:\r
+               case -96:\r
+                       return 'C';\r
+               case -97:\r
+               case -1: //text\r
+                       return 'X';\r
+               case -4: //image\r
+                       return 'B';\r
+                               \r
+               case 91:\r
+               case 11:\r
+                       return 'D';\r
+                       \r
+               case 92:\r
+               case 93:\r
+               case 9: return 'T';\r
+               case 4:\r
+               case 5:\r
+               case -6:\r
+                       return 'I';\r
+                       \r
+               case -11: // uniqidentifier\r
+                       return 'R';\r
+               case -7: //bit\r
+                       return 'L';\r
+               \r
+               default:\r
+                       return 'N';\r
+               }\r
+       }\r
+       \r
+       function &MetaColumns($table)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $table = strtoupper($table);\r
+               $schema = false;\r
+               $this->_findschema($table,$schema);\r
+               \r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       \r
+               if (false) { // after testing, confirmed that the following does not work becoz of a bug\r
+                       $qid2 = odbc_tables($this->_connectionID);\r
+                       $rs = new ADORecordSet_odbc($qid2);             \r
+                       $ADODB_FETCH_MODE = $savem;\r
+                       if (!$rs) return false;\r
+                       $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+                       $rs->_fetch();\r
+                       \r
+                       while (!$rs->EOF) {\r
+                               if ($table == strtoupper($rs->fields[2])) {\r
+                                       $q = $rs->fields[0];\r
+                                       $o = $rs->fields[1];\r
+                                       break;\r
+                               }\r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       \r
+                       $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');\r
+               } else switch ($this->databaseType) {\r
+               case 'access':\r
+               case 'vfp':\r
+               case 'db2':\r
+                       $qid = odbc_columns($this->_connectionID);\r
+                       break;\r
+                       \r
+               default:\r
+                       $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');\r
+                       if (empty($qid)) $qid = odbc_columns($this->_connectionID);\r
+                       break;\r
+               }\r
+               if (empty($qid)) return false;\r
+               \r
+               $rs = new ADORecordSet_odbc($qid);\r
+               $ADODB_FETCH_MODE = $savem;\r
+               \r
+               if (!$rs) return false;\r
+               \r
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
+               $rs->_fetch();\r
+               $retarr = array();\r
+               \r
+               /*\r
+               $rs->fields indices\r
+               0 TABLE_QUALIFIER\r
+               1 TABLE_SCHEM\r
+               2 TABLE_NAME\r
+               3 COLUMN_NAME\r
+               4 DATA_TYPE\r
+               5 TYPE_NAME\r
+               6 PRECISION\r
+               7 LENGTH\r
+               8 SCALE\r
+               9 RADIX\r
+               10 NULLABLE\r
+               11 REMARKS\r
+               */\r
+               while (!$rs->EOF) {\r
+                       //adodb_pr($rs->fields);\r
+                       if (strtoupper($rs->fields[2]) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[3];\r
+                               $fld->type = $this->ODBCTypes($rs->fields[4]);\r
+                               \r
+                               // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp\r
+                               // access uses precision to store length for char/varchar\r
+                               if ($fld->type == 'C' or $fld->type == 'X') {\r
+                                       if ($this->databaseType == 'access') \r
+                                               $fld->max_length = $rs->fields[6];\r
+                                       else if ($rs->fields[4] <= -95) // UNICODE\r
+                                               $fld->max_length = $rs->fields[7]/2;\r
+                                       else\r
+                                               $fld->max_length = $rs->fields[7];\r
+                               } else \r
+                                       $fld->max_length = $rs->fields[7];\r
+                               $fld->not_null = !empty($rs->fields[10]);\r
+                               $fld->scale = $rs->fields[8];\r
+                               $retarr[strtoupper($fld->name)] = $fld; \r
+                       } else if (sizeof($retarr)>0)\r
+                               break;\r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close(); //-- crashes 4.03pl1 -- why?\r
+               \r
+               return $retarr;\r
+       }\r
+       \r
+       function Prepare($sql)\r
+       {\r
+               if (! $this->_bindInputArray) return $sql; // no binding\r
+               $stmt = odbc_prepare($this->_connectionID,$sql);\r
+               if (!$stmt) {\r
+                       // we don't know whether odbc driver is parsing prepared stmts, so just return sql\r
+                       return $sql;\r
+               }\r
+               return array($sql,$stmt,false);\r
+       }\r
+\r
+       /* returns queryID or false */\r
+       function _query($sql,$inputarr=false) \r
+       {\r
+       GLOBAL $php_errormsg;\r
+               if (isset($php_errormsg)) $php_errormsg = '';\r
+               $this->_error = '';\r
+               \r
+               if ($inputarr) {\r
+                       if (is_array($sql)) {\r
+                               $stmtid = $sql[1];\r
+                       } else {\r
+                               $stmtid = odbc_prepare($this->_connectionID,$sql);\r
+       \r
+                               if ($stmtid == false) {\r
+                                       $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+                                       return false;\r
+                               }\r
+                       }\r
+                       \r
+                       if (! odbc_execute($stmtid,$inputarr)) {\r
+                               //@odbc_free_result($stmtid);\r
+                               if ($this->_haserrorfunctions) {\r
+                                       $this->_errorMsg = odbc_errormsg();\r
+                                       $this->_errorCode = odbc_error();\r
+                               }\r
+                               return false;\r
+                       }\r
+               \r
+               } else if (is_array($sql)) {\r
+                       $stmtid = $sql[1];\r
+                       if (!odbc_execute($stmtid)) {\r
+                               //@odbc_free_result($stmtid);\r
+                               if ($this->_haserrorfunctions) {\r
+                                       $this->_errorMsg = odbc_errormsg();\r
+                                       $this->_errorCode = odbc_error();\r
+                               }\r
+                               return false;\r
+                       }\r
+               } else\r
+                       $stmtid = odbc_exec($this->_connectionID,$sql);\r
+               \r
+               $this->_lastAffectedRows = 0;\r
+               if ($stmtid) {\r
+                       if (@odbc_num_fields($stmtid) == 0) {\r
+                               $this->_lastAffectedRows = odbc_num_rows($stmtid);\r
+                               $stmtid = true;\r
+                       } else {\r
+                               $this->_lastAffectedRows = 0;\r
+                               odbc_binmode($stmtid,$this->binmode);\r
+                               odbc_longreadlen($stmtid,$this->maxblobsize);\r
+                       }\r
+                       \r
+                       if ($this->_haserrorfunctions) {\r
+                               $this->_errorMsg = '';\r
+                               $this->_errorCode = 0;\r
+                       } else\r
+                               $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+               } else {\r
+                       if ($this->_haserrorfunctions) {\r
+                               $this->_errorMsg = odbc_errormsg();\r
+                               $this->_errorCode = odbc_error();\r
+                       } else\r
+                               $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : '';\r
+               }\r
+               return $stmtid;\r
+       }\r
+\r
+       /*\r
+               Insert a null into the blob field of the table first.\r
+               Then use UpdateBlob to store the blob.\r
+               \r
+               Usage:\r
+                \r
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               $ret = @odbc_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+               return $ret;\r
+       }\r
+\r
+       function _affectedrows()\r
+       {\r
+               return $this->_lastAffectedRows;\r
+       }\r
+       \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_odbc extends ADORecordSet { \r
+       \r
+       var $bind = false;\r
+       var $databaseType = "odbc";             \r
+       var $dataProvider = "odbc";\r
+       var $useFetchArray;\r
+       var $_has_stupid_odbc_fetch_api_change;\r
+       \r
+       function ADORecordSet_odbc($id,$mode=false)\r
+       {\r
+               if ($mode === false) {  \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               \r
+               $this->_queryID = $id;\r
+               \r
+               // the following is required for mysql odbc driver in 4.3.1 -- why?\r
+               $this->EOF = false;\r
+               $this->_currentRow = -1;\r
+               //$this->ADORecordSet($id);\r
+       }\r
+\r
+\r
+       // returns the field object\r
+       function &FetchField($fieldOffset = -1) \r
+       {\r
+               \r
+               $off=$fieldOffset+1; // offsets begin at 1\r
+               \r
+               $o= new ADOFieldObject();\r
+               $o->name = @odbc_field_name($this->_queryID,$off);\r
+               $o->type = @odbc_field_type($this->_queryID,$off);\r
+               $o->max_length = @odbc_field_len($this->_queryID,$off);\r
+               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);\r
+               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);\r
+               return $o;\r
+       }\r
+       \r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+\r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+               \r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1;\r
+               $this->_numOfFields = @odbc_num_fields($this->_queryID);\r
+               // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0\r
+               if ($this->_numOfRows == 0) $this->_numOfRows = -1;\r
+               //$this->useFetchArray = $this->connection->useFetchArray;\r
+               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;\r
+       }       \r
+       \r
+       function _seek($row)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated\r
+       function &GetArrayLimit($nrows,$offset=-1) \r
+       {\r
+               if ($offset <= 0) {\r
+                       $rs =& $this->GetArray($nrows);\r
+                       return $rs;\r
+               }\r
+               $savem = $this->fetchMode;\r
+               $this->fetchMode = ADODB_FETCH_NUM;\r
+               $this->Move($offset);\r
+               $this->fetchMode = $savem;\r
+               \r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+               }\r
+               \r
+               $results = array();\r
+               $cnt = 0;\r
+               while (!$this->EOF && $nrows != $cnt) {\r
+                       $results[$cnt++] = $this->fields;\r
+                       $this->MoveNext();\r
+               }\r
+               \r
+               return $results;\r
+       }\r
+       \r
+       \r
+       function MoveNext() \r
+       {\r
+               if ($this->_numOfRows != 0 && !$this->EOF) {            \r
+                       $this->_currentRow++;\r
+                       $row = 0;\r
+                       if ($this->_has_stupid_odbc_fetch_api_change)\r
+                               $rez = @odbc_fetch_into($this->_queryID,$this->fields);\r
+                       else \r
+                               $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);\r
+                       if ($rez) {\r
+                               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+                               }\r
+                               return true;\r
+                       }\r
+               }\r
+               $this->fields = false;\r
+               $this->EOF = true;\r
+               return false;\r
+       }       \r
+       \r
+       function _fetch()\r
+       {\r
+               $row = 0;\r
+               if ($this->_has_stupid_odbc_fetch_api_change)\r
+                       $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row);\r
+               else \r
+                       $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);\r
+               \r
+               if ($rez) {\r
+                       if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
+                               $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+                       }\r
+                       return true;\r
+               }\r
+               $this->fields = false;\r
+               return false;\r
+       }\r
+       \r
+       function _close() \r
+       {\r
+               return @odbc_free_result($this->_queryID);              \r
+       }\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
index 4b3161245b9670eb3f6a4680fc46e5c983588973..9e01c453e89d99fef2fc2b841873b61a01173082 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. 
-  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-
-class  ADODB_odbc_mssql extends ADODB_odbc {   
-       var $databaseType = 'odbc_mssql';
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
-       var $_bindInputArray = true;
-       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
-       var $sysDate = 'GetDate()';
-       var $sysTimeStamp = 'GetDate()';
-       var $leftOuter = '*=';
-       var $rightOuter = '=*';
-       var $upperCase = 'upper';
-       var $substr = 'substring';
-       var $length = 'len';
-       var $ansiOuter = true; // for mssql7 or later
-       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
-       var $hasInsertID = true;
-       var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, 
-                                                                                                                 # concatenating a null value with a string yields a NULL result
-       
-       function ADODB_odbc_mssql()
-       {
-               $this->ADODB_odbc();
-               $this->curmode = SQL_CUR_USE_ODBC;      
-       }
-
-       // crashes php...
-       function ServerInfo()
-       {
-       global $ADODB_FETCH_MODE;
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $row = $this->GetRow("execute sp_server_info 2");
-               $ADODB_FETCH_MODE = $save;
-               if (!is_array($row)) return false;
-               $arr['description'] = $row[2];
-               $arr['version'] = 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 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;
-       }
-       
-       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);
-               
-               if ($mask) {
-                       $this->metaTablesSQL = $save;
-               }
-               return $ret;
-       }
-       
-       function &MetaColumns($table)
-       {
-               return ADOConnection::MetaColumns($table);
-       }
-       
-       function _query($sql,$inputarr)
-       {
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);
-               return ADODB_odbc::_query($sql,$inputarr);
-       }
-       
-       // "Stein-Aksel Basma" <basma@accelero.no>
-       // tested with MSSQL 2000
-       function &MetaPrimaryKeys($table)
-       {
-               $sql = "select k.column_name 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'";
-               
-               $a = $this->GetCol($sql);
-               if ($a && sizeof($a)>0) return $a;
-               return false;     
-       }
-       
-       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);
-               } else
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-                       
-               return $rs;
-       }
-       
-       // 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;
-       }
-
-} 
-class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {     
-       
-       var $databaseType = 'odbc_mssql';
-       
-       function ADORecordSet_odbc_mssql($id,$mode=false)
-       {
-               return $this->ADORecordSet_odbc($id,$mode);
-       }       
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. \r
+  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+\r
\r
+class  ADODB_odbc_mssql extends ADODB_odbc {   \r
+       var $databaseType = 'odbc_mssql';\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $_bindInputArray = true;\r
+       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'))";\r
+       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'";\r
+       var $hasTop = 'top';            // support mssql/interbase SELECT TOP 10 * FROM TABLE\r
+       var $sysDate = 'GetDate()';\r
+       var $sysTimeStamp = 'GetDate()';\r
+       var $leftOuter = '*=';\r
+       var $rightOuter = '=*';\r
+       var $upperCase = 'upper';\r
+       var $substr = 'substring';\r
+       var $length = 'len';\r
+       var $ansiOuter = true; // for mssql7 or later\r
+       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000\r
+       var $hasInsertID = true;\r
+       var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, \r
+                                                                                                                 # concatenating a null value with a string yields a NULL result\r
+       \r
+       function ADODB_odbc_mssql()\r
+       {\r
+               $this->ADODB_odbc();\r
+               $this->curmode = SQL_CUR_USE_ODBC;      \r
+       }\r
+\r
+       // crashes php...\r
+       function ServerInfo()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $row = $this->GetRow("execute sp_server_info 2");\r
+               $ADODB_FETCH_MODE = $save;\r
+               if (!is_array($row)) return false;\r
+               $arr['description'] = $row[2];\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               return $arr;\r
+       }\r
+\r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " ISNULL($field, $ifNull) "; // if MS SQL Server\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+       // SCOPE_IDENTITY()\r
+       // Returns the last IDENTITY value inserted into an IDENTITY column in \r
+       // the same scope. A scope is a module -- a stored procedure, trigger, \r
+       // function, or batch. Thus, two statements are in the same scope if \r
+       // they are in the same stored procedure, function, or batch.\r
+                       return $this->GetOne($this->identitySQL);\r
+       }\r
+       \r
+       \r
+       function MetaForeignKeys($table, $owner=false, $upper=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $table = $this->qstr(strtoupper($table));\r
+               \r
+               $sql = \r
+"select object_name(constid) as constraint_name,\r
+       col_name(fkeyid, fkey) as column_name,\r
+       object_name(rkeyid) as referenced_table_name,\r
+       col_name(rkeyid, rkey) as referenced_column_name\r
+from sysforeignkeys\r
+where upper(object_name(fkeyid)) = $table\r
+order by constraint_name, referenced_table_name, keyno";\r
+               \r
+               $constraints =& $this->GetArray($sql);\r
+               \r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               $arr = false;\r
+               foreach($constraints as $constr) {\r
+                       //print_r($constr);\r
+                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; \r
+               }\r
+               if (!$arr) return false;\r
+               \r
+               $arr2 = false;\r
+               \r
+               foreach($arr as $k => $v) {\r
+                       foreach($v as $a => $b) {\r
+                               if ($upper) $a = strtoupper($a);\r
+                               $arr2[$a] = $b;\r
+                       }\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {\r
+               if ($mask) {$this->debug=1;\r
+                       $save = $this->metaTablesSQL;\r
+                       $mask = $this->qstr($mask);\r
+                       $this->metaTablesSQL .= " AND name like $mask";\r
+               }\r
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
+               \r
+               if ($mask) {\r
+                       $this->metaTablesSQL = $save;\r
+               }\r
+               return $ret;\r
+       }\r
+       \r
+       function &MetaColumns($table)\r
+       {\r
+               return ADOConnection::MetaColumns($table);\r
+       }\r
+       \r
+       function _query($sql,$inputarr)\r
+       {\r
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
+               return ADODB_odbc::_query($sql,$inputarr);\r
+       }\r
+       \r
+       // "Stein-Aksel Basma" <basma@accelero.no>\r
+       // tested with MSSQL 2000\r
+       function &MetaPrimaryKeys($table)\r
+       {\r
+               $sql = "select k.column_name from information_schema.key_column_usage k,\r
+               information_schema.table_constraints tc \r
+               where tc.constraint_name = k.constraint_name and tc.constraint_type =\r
+               'PRIMARY KEY' and k.table_name = '$table'";\r
+               \r
+               $a = $this->GetCol($sql);\r
+               if ($a && sizeof($a)>0) return $a;\r
+               return false;     \r
+       }\r
+       \r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               if ($nrows > 0 && $offset <= 0) {\r
+                       $sql = preg_replace(\r
+                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);\r
+                       $rs =& $this->Execute($sql,$inputarr);\r
+               } else\r
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+                       \r
+               return $rs;\r
+       }\r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = '';\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       if ($s) $s .= '+';\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= "datename(yyyy,$col)";\r
+                               break;\r
+                       case 'M':\r
+                               $s .= "convert(char(3),$col,0)";\r
+                               break;\r
+                       case 'm':\r
+                               $s .= "replace(str(month($col),2),' ','0')";\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= "datename(quarter,$col)";\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= "replace(str(day($col),2),' ','0')";\r
+                               break;\r
+                       case 'h':\r
+                               $s .= "substring(convert(char(14),$col,0),13,2)";\r
+                               break;\r
+                       \r
+                       case 'H':\r
+                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
+                               break;\r
+                       case 's':\r
+                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
+                               break;\r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= "substring(convert(char(19),$col,0),18,2)";\r
+                               break;\r
+                               \r
+                       default:\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               $s .= $this->qstr($ch);\r
+                               break;\r
+                       }\r
+               }\r
+               return $s;\r
+       }\r
+\r
+} \r
\r
+class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {     \r
+       \r
+       var $databaseType = 'odbc_mssql';\r
+       \r
+       function ADORecordSet_odbc_mssql($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_odbc($id,$mode);\r
+       }       \r
+}\r
 ?>
\ No newline at end of file
index 80c6ae8cba6a66fe668a26b92bbb0cbbe5f2fd94..a3e43e6607252a140a1e6746c2e142a719e8dd95 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Oracle support via ODBC. Requires ODBC. Works on Windows. 
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-
-class  ADODB_odbc_oracle extends ADODB_odbc {  
-       var $databaseType = 'odbc_oracle';
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $concat_operator='||';
-       var $fmtDate = "'Y-m-d 00:00:00'"; 
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
-       var $metaTablesSQL = 'select table_name from cat';
-       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
-       var $sysDate = "TRUNC(SYSDATE)";
-       var $sysTimeStamp = 'SYSDATE';
-       
-       //var $_bindInputArray = false;
-       
-       function ADODB_odbc_oracle()
-       {
-               $this->ADODB_odbc();
-       }
-               
-       function &MetaTables() 
-       {
-               if ($this->metaTablesSQL) {
-                       $rs = $this->Execute($this->metaTablesSQL);
-                       if ($rs === false) return false;
-                       $arr = $rs->GetArray();
-                       $arr2 = array();
-                       for ($i=0; $i < sizeof($arr); $i++) {
-                               $arr2[] = $arr[$i][0];
-                       }
-                       $rs->Close();
-                       return $arr2;
-               }
-               return false;
-       }
-       
-       function &MetaColumns($table) 
-       {
-               if (!empty($this->metaColumnsSQL)) {
-               
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
-                       if ($rs === false) return false;
-
-                       $retarr = array();
-                       while (!$rs->EOF) { //print_r($rs->fields);
-                               $fld = new ADOFieldObject();
-                               $fld->name = $rs->fields[0];
-                               $fld->type = $rs->fields[1];
-                               $fld->max_length = $rs->fields[2];
-                               
-                               
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
-                               else $retarr[strtoupper($fld->name)] = $fld;
-                               
-                               $rs->MoveNext();
-                       }
-                       $rs->Close();
-                       return $retarr; 
-               }
-               return false;
-       }
-
-       // returns true or false
-       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
-       {
-       global $php_errormsg;
-       
-               $php_errormsg = '';
-               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
-               $this->_errorMsg = $php_errormsg;
-               
-               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
-               return $this->_connectionID != false;
-       }
-       // returns true or false
-       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
-       {
-       global $php_errormsg;
-               $php_errormsg = '';
-               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
-               $this->_errorMsg = $php_errormsg;
-               
-               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
-               return $this->_connectionID != false;
-       }
-} 
-class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {    
-       
-       var $databaseType = 'odbc_oracle';
-       
-       function ADORecordSet_odbc_oracle($id,$mode=false)
-       {
-               return $this->ADORecordSet_odbc($id,$mode);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Oracle support via ODBC. Requires ODBC. Works on Windows. \r
+*/\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+\r
\r
+class  ADODB_odbc_oracle extends ADODB_odbc {  \r
+       var $databaseType = 'odbc_oracle';\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $concat_operator='||';\r
+       var $fmtDate = "'Y-m-d 00:00:00'"; \r
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+       var $metaTablesSQL = 'select table_name from cat';\r
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
+       var $sysDate = "TRUNC(SYSDATE)";\r
+       var $sysTimeStamp = 'SYSDATE';\r
+       \r
+       //var $_bindInputArray = false;\r
+       \r
+       function ADODB_odbc_oracle()\r
+       {\r
+               $this->ADODB_odbc();\r
+       }\r
+               \r
+       function &MetaTables() \r
+       {\r
+               if ($this->metaTablesSQL) {\r
+                       $rs = $this->Execute($this->metaTablesSQL);\r
+                       if ($rs === false) return false;\r
+                       $arr = $rs->GetArray();\r
+                       $arr2 = array();\r
+                       for ($i=0; $i < sizeof($arr); $i++) {\r
+                               $arr2[] = $arr[$i][0];\r
+                       }\r
+                       $rs->Close();\r
+                       return $arr2;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       function &MetaColumns($table) \r
+       {\r
+               if (!empty($this->metaColumnsSQL)) {\r
+               \r
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
+                       if ($rs === false) return false;\r
+\r
+                       $retarr = array();\r
+                       while (!$rs->EOF) { //print_r($rs->fields);\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[0];\r
+                               $fld->type = $rs->fields[1];\r
+                               $fld->max_length = $rs->fields[2];\r
+                               \r
+                               \r
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                               else $retarr[strtoupper($fld->name)] = $fld;\r
+                               \r
+                               $rs->MoveNext();\r
+                       }\r
+                       $rs->Close();\r
+                       return $retarr; \r
+               }\r
+               return false;\r
+       }\r
+\r
+       // returns true or false\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+       \r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+       global $php_errormsg;\r
+               $php_errormsg = '';\r
+               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
+               $this->_errorMsg = $php_errormsg;\r
+               \r
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
+               return $this->_connectionID != false;\r
+       }\r
+} \r
\r
+class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = 'odbc_oracle';\r
+       \r
+       function ADORecordSet_odbc_oracle($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_odbc($id,$mode);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/drivers/adodb-odbtp.inc.php b/lib/adodb/drivers/adodb-odbtp.inc.php
new file mode 100644 (file)
index 0000000..975c8ed
--- /dev/null
@@ -0,0 +1,633 @@
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license.\r
+  Whenever there is any discrepancy between the two licenses,\r
+  the BSD license will take precedence. See License.txt.\r
+  Set tabs to 4 for best viewing.\r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+// Code contributed by "stefan bogdan" <sbogdan#rsb.ro>\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+define("_ADODB_ODBTP_LAYER", 2 );\r
+\r
+class ADODB_odbtp extends ADOConnection{\r
+       var $databaseType = "odbtp";\r
+       var $dataProvider = "odbtp";\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $odbc_driver = 0;\r
+       var $hasAffectedRows = true;\r
+       var $hasInsertID = false;\r
+       var $hasGenID = true;\r
+       var $hasMoveFirst = true;\r
+\r
+       var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)";\r
+       var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'";\r
+       var $_autocommit = true;\r
+       var $_bindInputArray = false;\r
+       var $_useUnicodeSQL = false;\r
+       var $_canPrepareSP = false;\r
+\r
+       function ADODB_odbtp()\r
+       {\r
+       }\r
+\r
+       function ServerInfo()\r
+       {\r
+               return array('description' => @odbtp_get_attr( ODB_ATTR_DBMSNAME, $this->_connectionID),\r
+                            'version' => @odbtp_get_attr( ODB_ATTR_DBMSVER, $this->_connectionID));\r
+       }\r
+\r
+       function ErrorMsg()\r
+       {\r
+               if (empty($this->_connectionID)) return @odbtp_last_error();\r
+               return @odbtp_last_error($this->_connectionID);\r
+       }\r
+\r
+       function ErrorNo()\r
+       {\r
+               if (empty($this->_connectionID)) return @odbtp_last_error_state();\r
+                       return @odbtp_last_error_state($this->_connectionID);\r
+       }\r
+\r
+       function _insertid()\r
+       {\r
+       // SCOPE_IDENTITY()\r
+       // Returns the last IDENTITY value inserted into an IDENTITY column in\r
+       // the same scope. A scope is a module -- a stored procedure, trigger,\r
+       // function, or batch. Thus, two statements are in the same scope if\r
+       // they are in the same stored procedure, function, or batch.\r
+                       return $this->GetOne($this->identitySQL);\r
+       }\r
+\r
+       function _affectedrows()\r
+       {\r
+               if ($this->_queryID) {\r
+                       return @odbtp_affected_rows ($this->_queryID);\r
+          } else\r
+               return 0;\r
+       }\r
+\r
+       function CreateSequence($seqname='adodbseq',$start=1)\r
+       {\r
+               //verify existence\r
+               $num = $this->GetOne("select seq_value from adodb_seq");\r
+               $seqtab='adodb_seq';\r
+               if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {\r
+                       $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );\r
+                       //if using vfp dbc file\r
+                       if( !strcasecmp(strrchr($path, '.'), '.dbc') )\r
+                $path = substr($path,0,strrpos($path,'\/'));\r
+               $seqtab = $path . '/' . $seqtab;\r
+        }\r
+               if($num == false) {\r
+                       if (empty($this->_genSeqSQL)) return false;\r
+                       $ok = $this->Execute(sprintf($this->_genSeqSQL ,$seqtab));\r
+               }\r
+               $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'");\r
+               if ($num) {\r
+                       return false;\r
+               }\r
+               $start -= 1;\r
+               return $this->Execute("insert into adodb_seq values('$seqname',$start)");\r
+       }\r
+\r
+       function DropSequence($seqname)\r
+       {\r
+               if (empty($this->_dropSeqSQL)) return false;\r
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
+       }\r
+\r
+       function GenID($seq='adodbseq',$start=1)\r
+       {\r
+               $seqtab='adodb_seq';\r
+               if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {\r
+                       $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );\r
+                       //if using vfp dbc file\r
+                       if( !strcasecmp(strrchr($path, '.'), '.dbc') )\r
+                $path = substr($path,0,strrpos($path,'\/'));\r
+               $seqtab = $path . '/' . $seqtab;\r
+        }\r
+               $MAXLOOPS = 100;\r
+               while (--$MAXLOOPS>=0) {\r
+                       $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'");\r
+                       if ($num === false) {\r
+                               //verify if abodb_seq table exist\r
+                               $ok = $this->GetOne("select seq_value from adodb_seq ");\r
+                               if(!$ok) {\r
+                                       //creating the sequence table adodb_seq\r
+                                       $this->Execute(sprintf($this->_genSeqSQL ,$seqtab));\r
+                               }\r
+                               $start -= 1;\r
+                               $num = '0';\r
+                               $ok = $this->Execute("insert into adodb_seq values('$seq',$start)");\r
+                               if (!$ok) return false;\r
+                       }\r
+                       $ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'");\r
+                       if($ok) {\r
+                               $num += 1;\r
+                               $this->genID = $num;\r
+                               return $num;\r
+                       }\r
+               }\r
+       if ($fn = $this->raiseErrorFn) {\r
+               $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);\r
+       }\r
+               return false;\r
+       }\r
+\r
+       //example for $UserOrDSN\r
+       //for visual fox : DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=c:\YourDbfFileDir;EXCLUSIVE=NO;\r
+       //for visual fox dbc: DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBC;SOURCEDB=c:\YourDbcFileDir\mydb.dbc;EXCLUSIVE=NO;\r
+       //for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=;\r
+       //for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest;\r
+       //if uid & pwd can be separate\r
+    function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')\r
+       {\r
+               $this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);\r
+               if ($this->_connectionID === false)\r
+               {\r
+                       $this->_errorMsg = $this->ErrorMsg() ;\r
+                       return false;\r
+               }\r
+               $this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID);\r
+\r
+               // Set driver specific attributes\r
+               switch( $this->odbc_driver ) {\r
+                       case ODB_DRIVER_MSSQL:\r
+                               $this->fmtDate = "'Y-m-d'";\r
+                               $this->fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+                               $this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';\r
+                               $this->sysTimeStamp = 'GetDate()';\r
+                               $this->ansiOuter = true;\r
+                               $this->leftOuter = '*=';\r
+                               $this->rightOuter = '=*';\r
+                $this->hasTop = 'top';\r
+                               $this->hasInsertID = true;\r
+                               $this->hasTransactions = true;\r
+                               $this->_bindInputArray = true;\r
+                               $this->_canSelectDb = true;\r
+                               $this->substr = "substring";\r
+                               $this->length = 'len';\r
+                               $this->upperCase = 'upper';\r
+                               $this->identitySQL = 'select @@IDENTITY';\r
+                               $this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'";\r
+                               break;\r
+                       case ODB_DRIVER_JET:\r
+                               $this->fmtDate = "#Y-m-d#";\r
+                               $this->fmtTimeStamp = "#Y-m-d h:i:sA#";\r
+                               $this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')";\r
+                               $this->sysTimeStamp = 'NOW';\r
+                $this->hasTop = 'top';\r
+                               $this->hasTransactions = false;\r
+                               $this->_canPrepareSP = true;  // For MS Access only.\r
+\r
+                               // Can't rebind ODB_CHAR to ODB_WCHAR if row cache enabled.\r
+                               if ($this->_useUnicodeSQL)\r
+                                       odbtp_use_row_cache($this->_connectionID, FALSE, 0);\r
+                               break;\r
+                       case ODB_DRIVER_FOXPRO:\r
+                               $this->fmtDate = "{^Y-m-d}";\r
+                               $this->fmtTimeStamp = "{^Y-m-d, h:i:sA}";\r
+                               $this->sysDate = 'date()';\r
+                               $this->sysTimeStamp = 'datetime()';\r
+                               $this->ansiOuter = true;\r
+                $this->hasTop = 'top';\r
+                       $this->hasTransactions = false;\r
+                               $this->replaceQuote = "'+chr(39)+'";\r
+                               $this->true = '.T.';\r
+                               $this->false = '.F.';\r
+                               $this->upperCase = 'upper';\r
+                               break;\r
+                       case ODB_DRIVER_ORACLE:\r
+                               $this->fmtDate = "'Y-m-d 00:00:00'";\r
+                               $this->fmtTimeStamp = "'Y-m-d h:i:sA'";\r
+                               $this->sysDate = 'TRUNC(SYSDATE)';\r
+                               $this->sysTimeStamp = 'SYSDATE';\r
+                               $this->hasTransactions = true;\r
+                               $this->_bindInputArray = true;\r
+                               $this->concat_operator = '||';\r
+                               break;\r
+                       case ODB_DRIVER_SYBASE:\r
+                               $this->fmtDate = "'Y-m-d'";\r
+                               $this->fmtTimeStamp = "'Y-m-d H:i:s'";\r
+                               $this->sysDate = 'GetDate()';\r
+                               $this->sysTimeStamp = 'GetDate()';\r
+                               $this->leftOuter = '*=';\r
+                               $this->rightOuter = '=*';\r
+                               $this->hasInsertID = true;\r
+                               $this->hasTransactions = true;\r
+                               $this->upperCase = 'upper';\r
+                               $this->identitySQL = 'select @@IDENTITY';\r
+                               break;\r
+                       default:\r
+                               if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) )\r
+                       $this->hasTransactions = true;\r
+                               else\r
+                                       $this->hasTransactions = false;\r
+               }\r
+        @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID );\r
+               if ($this->_useUnicodeSQL )\r
+                       @odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID);\r
+        return true;\r
+       }\r
+       \r
+       function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')\r
+       {\r
+               return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase);\r
+       }\r
+       \r
+       function SelectDB($dbName)\r
+       {\r
+               if (!@odbtp_select_db($dbName, $this->_connectionID)) {\r
+                       return false;\r
+               }\r
+               $this->databaseName = $dbName;\r
+               return true;\r
+       }\r
+       \r
+       function &MetaTables($ttype='',$showSchema=false,$mask=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+\r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $arr =& $this->GetArray("||SQLTables||||$ttype");\r
+               $ADODB_FETCH_MODE = $savem;\r
+\r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][3] == 'SYSTEM TABLE' )     continue;\r
+                       if ($arr[$i][2])\r
+                               $arr2[] = $showSchema ? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];\r
+               }\r
+               return $arr2;\r
+       }\r
+       \r
+       function &MetaColumns($table,$upper=true)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+\r
+               $schema = false;\r
+               $this->_findschema($table,$schema);\r
+               if ($upper) $table = strtoupper($table);\r
+\r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $rs = $this->Execute( "||SQLColumns||$schema|$table" );\r
+               $ADODB_FETCH_MODE = $savem;\r
+\r
+               if (!$rs) return false;\r
+               \r
+               while (!$rs->EOF) {\r
+                       //print_r($rs->fields);\r
+                       if (strtoupper($rs->fields[2]) == $table) {\r
+                               $fld = new ADOFieldObject();\r
+                               $fld->name = $rs->fields[3];\r
+                               $fld->type = $rs->fields[5];\r
+                               $fld->max_length = $rs->fields[6];\r
+                       $fld->not_null = !empty($rs->fields[9]);\r
+                               $fld->scale = $rs->fields[7];\r
+                               if (!is_null($rs->fields[12])) {\r
+                                       $fld->has_default = true;\r
+                                       $fld->default_value = $rs->fields[12];\r
+                               }\r
+                               $retarr[strtoupper($fld->name)] = $fld;\r
+                       } else if (sizeof($retarr)>0)\r
+                               break;\r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close(); \r
+\r
+               return $retarr;\r
+       }\r
+\r
+       function &MetaPrimaryKeys($table, $owner='')\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+\r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $arr =& $this->GetArray("||SQLPrimaryKeys||$owner|$table");\r
+               $ADODB_FETCH_MODE = $savem;\r
+\r
+               //print_r($arr);\r
+               $arr2 = array();\r
+               for ($i=0; $i < sizeof($arr); $i++) {\r
+                       if ($arr[$i][3]) $arr2[] = $arr[$i][3];\r
+               }\r
+               return $arr2;\r
+       }\r
+\r
+       function &MetaForeignKeys($table, $owner='', $upper=false)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+\r
+               $savem = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $constraints =& $this->GetArray("||SQLForeignKeys|||||$owner|$table");\r
+               $ADODB_FETCH_MODE = $savem;\r
+\r
+               $arr = false;\r
+               foreach($constraints as $constr) {\r
+                       //print_r($constr);\r
+                       $arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3];\r
+               }\r
+               if (!$arr) return false;\r
+\r
+               $arr2 = array();\r
+\r
+               foreach($arr as $k => $v) {\r
+                       foreach($v as $a => $b) {\r
+                               if ($upper) $a = strtoupper($a);\r
+                               $arr2[$a] = $b;\r
+                       }\r
+               }\r
+               return $arr2;\r
+       }\r
+\r
+       function BeginTrans()\r
+       {\r
+               if (!$this->hasTransactions) return false;\r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               $this->_autocommit = false;\r
+               $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,ODB_TXN_READUNCOMMITTED,$this->_connectionID);\r
+               if(!$rs) return false;\r
+               else return true;\r
+       }\r
+\r
+       function CommitTrans($ok=true)\r
+       {\r
+               if ($this->transOff) return true;\r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               if( ($ret = odbtp_commit($this->_connectionID)) )\r
+                       $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off\r
+               return $ret;\r
+       }\r
+\r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               if( ($ret = odbtp_rollback($this->_connectionID)) )\r
+                       $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off\r
+               return $ret;\r
+       }\r
+\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               // TOP requires ORDER BY for Visual FoxPro\r
+               if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {\r
+                       if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';\r
+               }\r
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+       }\r
+\r
+       function Prepare($sql)\r
+       {\r
+               if (! $this->_bindInputArray) return $sql; // no binding\r
+               $stmt = odbtp_prepare($sql,$this->_connectionID);\r
+               if (!$stmt) {\r
+               //      print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";\r
+                       return $sql;\r
+               }\r
+               return array($sql,$stmt,false);\r
+       }\r
+\r
+       function PrepareSP($sql)\r
+       {\r
+               if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures\r
+\r
+               $stmt = odbtp_prepare_proc($sql,$this->_connectionID);\r
+               if (!$stmt) return false;\r
+               return array($sql,$stmt);\r
+       }\r
+\r
+       /*\r
+       Usage:\r
+               $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group\r
+\r
+               # note that the parameter does not have @ in front!\r
+               $db->Parameter($stmt,$id,'myid');\r
+               $db->Parameter($stmt,$group,'group',false,64);\r
+               $db->Parameter($stmt,$group,'photo',false,100000,ODB_BINARY);\r
+               $db->Execute($stmt);\r
+\r
+               @param $stmt Statement returned by Prepare() or PrepareSP().\r
+               @param $var PHP variable to bind to. Can set to null (for isNull support).\r
+               @param $name Name of stored procedure variable name to bind to.\r
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in odbtp.\r
+               @param [$maxLen] Holds an maximum length of the variable.\r
+               @param [$type] The data type of $var. Legal values depend on driver.\r
+\r
+               See odbtp_attach_param documentation at http://odbtp.sourceforge.net.\r
+       */\r
+       function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0)\r
+       {\r
+               if ( $this->odbc_driver == ODB_DRIVER_JET ) {\r
+                       $name = '['.$name.']';\r
+                       if( !$type && $this->_useUnicodeSQL\r
+                               && @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR )\r
+                       {\r
+                               $type = ODB_WCHAR;\r
+                       }\r
+               }\r
+               else {\r
+                       $name = '@'.$name;\r
+               }\r
+               return odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen);\r
+       }\r
+\r
+       /*\r
+               Insert a null into the blob field of the table first.\r
+               Then use UpdateBlob to store the blob.\r
+\r
+               Usage:\r
+\r
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+       */\r
+\r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='image')\r
+       {\r
+               $sql = "UPDATE $table SET $column = ? WHERE $where";\r
+               if( !($stmt = odbtp_prepare($sql, $this->_connectionID)) )\r
+                       return false;\r
+               if( !odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )\r
+                       return false;\r
+               if( !odbtp_set( $stmt, 1, $val ) )\r
+                       return false;\r
+               return odbtp_execute( $stmt ) != false;\r
+       }\r
+\r
+       function IfNull( $field, $ifNull )\r
+       {\r
+               switch( $this->odbc_driver ) {\r
+                       case ODB_DRIVER_MSSQL:\r
+                               return " ISNULL($field, $ifNull) ";\r
+                       case ODB_DRIVER_JET:\r
+                               return " IIF(IsNull($field), $ifNull, $field) ";\r
+               }\r
+               return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";\r
+       }\r
+\r
+       function _query($sql,$inputarr=false)\r
+       {\r
+               if ($inputarr) {\r
+                       if (is_array($sql)) {\r
+                               $stmtid = $sql[1];\r
+                       } else {\r
+                               $stmtid = odbtp_prepare($sql,$this->_connectionID);\r
+                               if ($stmtid == false) {\r
+                                       $this->_errorMsg = $php_errormsg;\r
+                                       return false;\r
+                               }\r
+                       }\r
+                       $num_params = odbtp_num_params( $stmtid );\r
+                       for( $param = 1; $param <= $num_params; $param++ ) {\r
+                               @odbtp_input( $stmtid, $param );\r
+                               @odbtp_set( $stmtid, $param, $inputarr[$param-1] );\r
+                       }\r
+                       if (! odbtp_execute($stmtid) ) {\r
+                               return false;\r
+                       }\r
+               } else if (is_array($sql)) {\r
+                       $stmtid = $sql[1];\r
+                       if (!odbtp_execute($stmtid)) {\r
+                               return false;\r
+                       }\r
+               } else {\r
+                       $stmtid = @odbtp_query($sql,$this->_connectionID);\r
+               }\r
+               $this->_lastAffectedRows = 0;\r
+               if ($stmtid) {\r
+                               $this->_lastAffectedRows = @odbtp_affected_rows($stmtid);\r
+               }\r
+        return $stmtid;\r
+       }\r
+\r
+       function _close()\r
+       {\r
+               $ret = @odbtp_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+               return $ret;\r
+       }\r
+}\r
+\r
+class ADORecordSet_odbtp extends ADORecordSet {\r
+\r
+       var $databaseType = 'odbtp';\r
+       var $canSeek = true;\r
+\r
+       function ADORecordSet_odbtp($queryID,$mode=false)\r
+       {\r
+               if ($mode === false) {\r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               $this->ADORecordSet($queryID);\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+               $this->_numOfFields = @odbtp_num_fields($this->_queryID);\r
+               if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))\r
+                       $this->_numOfRows = -1;\r
+       }\r
+\r
+       function &FetchField($fieldOffset = 0)\r
+       {\r
+               $off=$fieldOffset; // offsets begin at 0\r
+               $o= new ADOFieldObject();\r
+               $o->name = @odbtp_field_name($this->_queryID,$off);\r
+               $o->type = @odbtp_field_type($this->_queryID,$off);\r
+        $o->max_length = @odbtp_field_length($this->_queryID,$off);\r
+               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);\r
+               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);\r
+               return $o;\r
+       }\r
+\r
+       function _seek($row)\r
+       {\r
+               return @odbtp_data_seek($this->_queryID, $row);\r
+       }\r
+\r
+       function fields($colname)\r
+       {\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
+\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $name = @odbtp_field_name( $this->_queryID, $i );\r
+                               $this->bind[strtoupper($name)] = $i;\r
+                       }\r
+               }\r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+\r
+       function _fetch_odbtp($type=0)\r
+       {\r
+               switch ($this->fetchMode) {\r
+                       case ADODB_FETCH_NUM:\r
+                               $this->fields = @odbtp_fetch_row($this->_queryID, $type);\r
+                               break;\r
+                       case ADODB_FETCH_ASSOC:\r
+                               $this->fields = @odbtp_fetch_assoc($this->_queryID, $type);\r
+                               break;\r
+            default:\r
+                               $this->fields = @odbtp_fetch_array($this->_queryID, $type);\r
+               }\r
+               return is_array($this->fields);\r
+       }\r
+\r
+       function _fetch()\r
+       {\r
+               return $this->_fetch_odbtp();\r
+       }\r
+\r
+       function MoveFirst()\r
+       {\r
+               if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false;\r
+               $this->EOF = false;\r
+         $this->_currentRow = 0;\r
+         return true;\r
+    }\r
+\r
+    function MoveLast()\r
+   {\r
+               if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false;\r
+               $this->EOF = false;\r
+               $this->_currentRow = $this->_numOfRows - 1;\r
+         return true;\r
+    }\r
+    \r
+       function NextRecordSet()\r
+       {\r
+               if (!@odbtp_next_result($this->_queryID)) return false;\r
+               $this->_inited = false;\r
+               $this->bind = false;\r
+               $this->_currentRow = -1;\r
+               $this->Init();\r
+               return true;\r
+       }\r
+\r
+       function _close()\r
+       {\r
+               return @odbtp_free_query($this->_queryID);\r
+       }\r
+}\r
+\r
+?>\r
+\r
+\r
diff --git a/lib/adodb/drivers/adodb-odbtp_unicode.inc.php b/lib/adodb/drivers/adodb-odbtp_unicode.inc.php
new file mode 100644 (file)
index 0000000..af942a3
--- /dev/null
@@ -0,0 +1,63 @@
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license.\r
+  Whenever there is any discrepancy between the two licenses,\r
+  the BSD license will take precedence. See License.txt.\r
+  Set tabs to 4 for best viewing.\r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+// Code contributed by "Robert Twitty" <rtwitty#neutron.ushmm.org>\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+/*\r
+    Because the ODBTP server sends and reads UNICODE text data using UTF-8\r
+    encoding, the following HTML meta tag must be included within the HTML\r
+    head section of every HTML form and script page:\r
+\r
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\r
+\r
+    Also, all SQL query strings must be submitted as UTF-8 encoded text.\r
+*/\r
+\r
+if (!defined('_ADODB_ODBTP_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbtp.inc.php");\r
+}\r
+\r
+class ADODB_odbtp_unicode extends ADODB_odbtp {\r
+       var $databaseType = "odbtp_unicode";\r
+       var $_useUnicodeSQL = true;\r
+\r
+       function ADODB_odbtp_unicode()\r
+       {\r
+               $this->ADODB_odbtp();\r
+       }\r
+}\r
+\r
+class ADORecordSet_odbtp_unicode extends ADORecordSet_odbtp {\r
+       var $databaseType = 'odbtp_unicode';\r
+\r
+       function ADORecordSet_odbtp_unicode($queryID,$mode=false)\r
+       {\r
+               $this->ADORecordSet_odbtp($queryID, $mode);\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+               $this->_numOfFields = @odbtp_num_fields($this->_queryID);\r
+               if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))\r
+                       $this->_numOfRows = -1;\r
+\r
+               if ($this->connection->odbc_driver == ODB_DRIVER_JET) {\r
+                       for ($f = 0; $f < $this->_numOfFields; $f++) {\r
+                               if (odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR)\r
+                                       odbtp_bind_field($this->_queryID, $f, ODB_WCHAR);\r
+                       }\r
+               }\r
+       }\r
+}\r
+?>\r
+\r
index bcc49118d7e3bc7114b53947c1e5a1b36dad592e..e36216c2b0202966fcd6fb303bfc8679e4f3c01b 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-  Latest version is available at http://php.weblogs.com/
-  
-  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.
-  
-  If you are using Oracle 8, use the oci8 driver which is much better and more reliable.
-  
-*/
-
-class ADODB_oracle extends ADOConnection {
-       var $databaseType = "oracle";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $concat_operator='||';
-       var $_curs;
-       var $_initdate = true; // init date to YYYY-MM-DD
-       var $metaTablesSQL = 'select table_name from cat';      
-       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
-       var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";
-       var $sysTimeStamp = 'SYSDATE';
-       var $connectSID = true;
-       
-       function ADODB_oracle() 
-       {
-       }
-
-       // format and return date string in database date format
-       function DBDate($d)
-       {
-               if (is_string($d)) $d = ADORecordSet::UnixDate($d);
-               return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'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')";
-       }
-
-       
-       function BeginTrans()
-       {         
-                $this->autoCommit = false;
-                ora_commitoff($this->_connectionID);
-                return true;
-       }
-
-       
-       function CommitTrans($ok=true) 
-       { 
-                  if (!$ok) return $this->RollbackTrans();
-                  $ret = ora_commit($this->_connectionID);
-                  ora_commiton($this->_connectionID);
-                  return $ret;
-       }
-
-       
-       function RollbackTrans()
-       {
-               $ret = ora_rollback($this->_connectionID);
-               ora_commiton($this->_connectionID);
-               return $ret;
-       }
-
-
-       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */
-       function ErrorMsg() 
-       {
-               $this->_errorMsg = @ora_error($this->_curs);
-               if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);
-               return $this->_errorMsg;
-       }
-
-       function ErrorNo() 
-       {
-               $err = @ora_errorcode($this->_curs);
-               if (!$err) return @ora_errorcode($this->_connectionID);
-       }
-
-       
-
-               // returns true or false
-               function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0)
-               {
-            // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set
-            // the oracle home to the host name of remote DB?
-//                     if ($argHostname) putenv("ORACLE_HOME=$argHostname");
-
-                       if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
-                               if (empty($argDatabasename)) $argDatabasename = $argHostname;
-                               else {
-                                       if(strpos($argHostname,":")) {
-                                               $argHostinfo=explode(":",$argHostname);
-                                               $argHostname=$argHostinfo[0];
-                                               $argHostport=$argHostinfo[1];
-                                       } else {
-                                               $argHostport="1521";
-                                       }
-
-
-                                       if ($this->connectSID) {
-                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
-                                               .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
-                                       } else
-                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
-                                               .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
-                               }
-
-                       }
-
-                       if ($argDatabasename) $argUsername .= "@$argDatabasename";
-
-               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
-                       if ($mode = 1)
-                               $this->_connectionID = ora_plogon($argUsername,$argPassword);
-                       else
-                               $this->_connectionID = ora_logon($argUsername,$argPassword);
-                       if ($this->_connectionID === false) return false;
-                       if ($this->autoCommit) ora_commiton($this->_connectionID);
-                       if ($this->_initdate) {
-                               $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
-                               if ($rs) ora_close($rs);
-                       }
-
-                       return true;
-               }
-
-
-               // returns true or false
-               function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-               {
-                       return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1);
-               }
-
-
-               // returns query ID if successful, otherwise false
-               function _query($sql,$inputarr=false)
-               {
-                       $curs = ora_open($this->_connectionID);
-                
-                       if ($curs === false) return false;
-                       $this->_curs = $curs;
-                       if (!ora_parse($curs,$sql)) return false;
-                       if (ora_exec($curs)) return $curs;
-               
-                       @ora_close($curs);
-                       return false;
-               }
-
-
-               // returns true or false
-               function _close()
-               {
-                       return @ora_logoff($this->_connectionID);
-               }
-
-
-
-}
-
-
-/*--------------------------------------------------------------------------------------
-                Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_oracle extends ADORecordSet {
-
-       var $databaseType = "oracle";
-       var $bind = false;
-
-       function ADORecordset_oracle($queryID,$mode=false)
-       {
-               
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               $this->fetchMode = $mode;
-               
-               $this->_queryID = $queryID;
-       
-               $this->_inited = true;
-               $this->fields = array();
-               if ($queryID) {
-                       $this->_currentRow = 0;
-                       $this->EOF = !$this->_fetch();
-                       @$this->_initrs();
-               } else {
-                       $this->_numOfRows = 0;
-                       $this->_numOfFields = 0;
-                       $this->EOF = true;
-               }
-               
-               return $this->_queryID;
-       }
-
-
-
-          /*           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)
-          {
-                       $fld = new ADOFieldObject;
-                       $fld->name = ora_columnname($this->_queryID, $fieldOffset);
-                       $fld->type = ora_columntype($this->_queryID, $fieldOffset);
-                       $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);
-                       return $fld;
-          }
-
-       /* Use associative array to get fields array */
-       function 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()
-   {
-                  $this->_numOfRows = -1;
-                  $this->_numOfFields = @ora_numcols($this->_queryID);
-   }
-
-
-   function _seek($row)
-   {
-                  return false;
-   }
-
-   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);
-               else 
-                       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
-                  is running. All associated result memory for the specified result identifier will automatically be freed.            */
-
-   function _close() 
-{
-                  return @ora_close($this->_queryID);
-   }
-
-       function MetaType($t,$len=-1)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               
-               switch (strtoupper($t)) {
-               case 'VARCHAR':
-               case 'VARCHAR2':
-               case 'CHAR':
-               case 'VARBINARY':
-               case 'BINARY':
-                               if ($len <= $this->blobSize) return 'C';
-               case 'LONG':
-               case 'LONG VARCHAR':
-               case 'CLOB':
-               return 'X';
-               case 'LONG RAW':
-               case 'LONG VARBINARY':
-               case 'BLOB':
-                               return 'B';
-               
-               case 'DATE': return 'D';
-               
-               //case 'T': return 'T';
-               
-               case 'BIT': return 'L';
-               case 'INT': 
-               case 'SMALLINT':
-               case 'INTEGER': return 'I';
-               default: return 'N';
-               }
-       }
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.\r
+  \r
+  If you are using Oracle 8, use the oci8 driver which is much better and more reliable.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB_oracle extends ADOConnection {\r
+       var $databaseType = "oracle";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $concat_operator='||';\r
+       var $_curs;\r
+       var $_initdate = true; // init date to YYYY-MM-DD\r
+       var $metaTablesSQL = 'select table_name from cat';      \r
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
+       var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";\r
+       var $sysTimeStamp = 'SYSDATE';\r
+       var $connectSID = true;\r
+       \r
+       function ADODB_oracle() \r
+       {\r
+       }\r
+\r
+       // format and return date string in database date format\r
+       function DBDate($d)\r
+       {\r
+               if (is_string($d)) $d = ADORecordSet::UnixDate($d);\r
+               return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";\r
+       }\r
+       \r
+       // format and return date string in database timestamp format\r
+       function DBTimeStamp($ts)\r
+       {\r
+\r
+               if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);\r
+               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";\r
+       }\r
+\r
+       \r
+       function BeginTrans()\r
+       {         \r
+                $this->autoCommit = false;\r
+                ora_commitoff($this->_connectionID);\r
+                return true;\r
+       }\r
+\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+                  if (!$ok) return $this->RollbackTrans();\r
+                  $ret = ora_commit($this->_connectionID);\r
+                  ora_commiton($this->_connectionID);\r
+                  return $ret;\r
+       }\r
+\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               $ret = ora_rollback($this->_connectionID);\r
+               ora_commiton($this->_connectionID);\r
+               return $ret;\r
+       }\r
+\r
+\r
+       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */\r
+       function ErrorMsg() \r
+       {   \r
+        if ($this->_errorMsg !== false) return $this->_errorMsg;\r
+\r
+        if (is_resource($this->_curs)) $this->_errorMsg = @ora_error($this->_curs);\r
+               if (empty($this->_errorMsg)) $this->_errorMsg = @ora_error($this->_connectionID);\r
+               return $this->_errorMsg;\r
+       }\r
+\r
\r
+       function ErrorNo() \r
+       {\r
+               if ($this->_errorCode !== false) return $this->_errorCode;\r
+\r
+               if (is_resource($this->_curs)) $this->_errorCode = @ora_errorcode($this->_curs);\r
+               if (empty($this->_errorCode)) $this->_errorCode = @ora_errorcode($this->_connectionID);\r
+        return $this->_errorCode;\r
+       }\r
+\r
+       \r
+\r
+               // returns true or false\r
+               function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0)\r
+               {\r
+                       if (!function_exists('ora_plogon')) return null;\r
+                               \r
+            // <G. Giunta 2003/03/03/> Reset error messages before connecting\r
+            $this->_errorMsg = false;\r
+                   $this->_errorCode = false;\r
+        \r
+            // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set\r
+            // the oracle home to the host name of remote DB?\r
+//                     if ($argHostname) putenv("ORACLE_HOME=$argHostname");\r
+\r
+                       if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
+                               if (empty($argDatabasename)) $argDatabasename = $argHostname;\r
+                               else {\r
+                                       if(strpos($argHostname,":")) {\r
+                                               $argHostinfo=explode(":",$argHostname);\r
+                                               $argHostname=$argHostinfo[0];\r
+                                               $argHostport=$argHostinfo[1];\r
+                                       } else {\r
+                                               $argHostport="1521";\r
+                                       }\r
+\r
+\r
+                                       if ($this->connectSID) {\r
+                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                                               .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";\r
+                                       } else\r
+                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
+                                               .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";\r
+                               }\r
+\r
+                       }\r
+\r
+                       if ($argDatabasename) $argUsername .= "@$argDatabasename";\r
+\r
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
+                       if ($mode = 1)\r
+                               $this->_connectionID = ora_plogon($argUsername,$argPassword);\r
+                       else\r
+                               $this->_connectionID = ora_logon($argUsername,$argPassword);\r
+                       if ($this->_connectionID === false) return false;\r
+                       if ($this->autoCommit) ora_commiton($this->_connectionID);\r
+                       if ($this->_initdate) {\r
+                               $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
+                               if ($rs) ora_close($rs);\r
+                       }\r
+\r
+                       return true;\r
+               }\r
+\r
+\r
+               // returns true or false\r
+               function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+               {\r
+                       return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1);\r
+               }\r
+\r
+\r
+               // returns query ID if successful, otherwise false\r
+               function _query($sql,$inputarr=false)\r
+               {\r
+            // <G. Giunta 2003/03/03/> Reset error messages before executing\r
+            $this->_errorMsg = false;\r
+                   $this->_errorCode = false;\r
+\r
+                       $curs = ora_open($this->_connectionID);\r
+                \r
+                       if ($curs === false) return false;\r
+                       $this->_curs = $curs;\r
+                       if (!ora_parse($curs,$sql)) return false;\r
+                       if (ora_exec($curs)) return $curs;\r
+            // <G. Giunta 2004/03/03> before we close the cursor, we have to store the error message\r
+            // that we can obtain ONLY from the cursor (and not from the connection)\r
+            $this->_errorCode = @ora_errorcode($curs);\r
+            $this->_errorMsg = @ora_error($curs);\r
+            // </G. Giunta 2004/03/03>            \r
+                       @ora_close($curs);\r
+                       return false;\r
+               }\r
+\r
+\r
+               // returns true or false\r
+               function _close()\r
+               {\r
+                       return @ora_logoff($this->_connectionID);\r
+               }\r
+\r
+\r
+\r
+}\r
+\r
+\r
+/*--------------------------------------------------------------------------------------\r
+                Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_oracle extends ADORecordSet {\r
+\r
+       var $databaseType = "oracle";\r
+       var $bind = false;\r
+\r
+       function ADORecordset_oracle($queryID,$mode=false)\r
+       {\r
+               \r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               \r
+               $this->_queryID = $queryID;\r
+       \r
+               $this->_inited = true;\r
+               $this->fields = array();\r
+               if ($queryID) {\r
+                       $this->_currentRow = 0;\r
+                       $this->EOF = !$this->_fetch();\r
+                       @$this->_initrs();\r
+               } else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+                       $this->EOF = true;\r
+               }\r
+               \r
+               return $this->_queryID;\r
+       }\r
+\r
+\r
+\r
+          /*           Returns: an object containing field information.\r
+                          Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+                          fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+                          fetchField() is retrieved.           */\r
+\r
+          function FetchField($fieldOffset = -1)\r
+          {\r
+                       $fld = new ADOFieldObject;\r
+                       $fld->name = ora_columnname($this->_queryID, $fieldOffset);\r
+                       $fld->type = ora_columntype($this->_queryID, $fieldOffset);\r
+                       $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);\r
+                       return $fld;\r
+          }\r
+\r
+       /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+   function _initrs()\r
+   {\r
+                  $this->_numOfRows = -1;\r
+                  $this->_numOfFields = @ora_numcols($this->_queryID);\r
+   }\r
+\r
+\r
+   function _seek($row)\r
+   {\r
+                  return false;\r
+   }\r
+\r
+   function _fetch($ignore_fields=false) {\r
+// should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1\r
+               if ($this->fetchMode & ADODB_FETCH_ASSOC)\r
+                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);\r
+               else \r
+                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);\r
+   }\r
+\r
+   /*          close() only needs to be called if you are worried about using too much memory while your script\r
+                  is running. All associated result memory for the specified result identifier will automatically be freed.            */\r
+\r
+   function _close() \r
+{\r
+                  return @ora_close($this->_queryID);\r
+   }\r
+\r
+       function MetaType($t,$len=-1)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               \r
+               switch (strtoupper($t)) {\r
+               case 'VARCHAR':\r
+               case 'VARCHAR2':\r
+               case 'CHAR':\r
+               case 'VARBINARY':\r
+               case 'BINARY':\r
+                               if ($len <= $this->blobSize) return 'C';\r
+               case 'LONG':\r
+               case 'LONG VARCHAR':\r
+               case 'CLOB':\r
+               return 'X';\r
+               case 'LONG RAW':\r
+               case 'LONG VARBINARY':\r
+               case 'BLOB':\r
+                               return 'B';\r
+               \r
+               case 'DATE': return 'D';\r
+               \r
+               //case 'T': return 'T';\r
+               \r
+               case 'BIT': return 'L';\r
+               case 'INT': \r
+               case 'SMALLINT':\r
+               case 'INTEGER': return 'I';\r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/drivers/adodb-pdo.inc.php b/lib/adodb/drivers/adodb-pdo.inc.php
new file mode 100644 (file)
index 0000000..b676468
--- /dev/null
@@ -0,0 +1,319 @@
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Requires ODBC. Works on Windows and Unix.\r
+*/\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+        \r
+/*--------------------------------------------------------------------------------------\r
+--------------------------------------------------------------------------------------*/\r
+\r
+\r
+class ADODB_pdo extends ADOConnection {\r
+       var $databaseType = "pdo";      \r
+       var $dataProvider = "pdo";\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $hasAffectedRows = true;\r
+       var $_bindInputArray = true;    \r
+       var $_genSeqSQL = "create table %s (id integer)";\r
+       var $_autocommit = true;\r
+       var $_haserrorfunctions = true;\r
+       var $_lastAffectedRows = 0;\r
+       \r
+       var $stmt = false;\r
+       \r
+       function ADODB_pdo() \r
+       {\r
+       }\r
+       \r
+\r
+       // returns true or false\r
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false)\r
+       {\r
+               $this->_connectionID = new PDO($argDSN, $argUsername, $argPassword);\r
+               if ($this->_connectionID) {\r
+                       switch(ADODB_ASSOC_CASE){\r
+                       case 0: $m = PDO_CASE_LOWER; break;\r
+                       case 1: $m = PDO_CASE_UPPER; break;\r
+                       default:\r
+                       case 2: $m = PDO_CASE_NATURAL; break;\r
+                       }\r
+                       \r
+                       //$this->_connectionID->setAttribute(PDO_ATTR_ERRMODE,PDO_ERRMODE_SILENT );\r
+                       $this->_connectionID->setAttribute(PDO_ATTR_CASE,$m);\r
+                       \r
+                       //$this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true);\r
+                       \r
+                       return true;\r
+               }\r
+               return false;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true);\r
+       }\r
+       \r
+       function ErrorMsg()\r
+       {\r
+               if ($this->_stmt) $arr = $this->_stmt->errorInfo();\r
+               else $arr = $this->_connectionID->errorInfo();\r
+               \r
+               if ($arr) {\r
+                       if ($arr[0]) return $arr[2];\r
+                       else return '';\r
+               } else return '-1';\r
+       }\r
+       \r
+       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)\r
+       {\r
+               $obj = $stmt[1];\r
+               if ($type) $obj->bindParam($name,$var,$type,$maxLen);\r
+               else $obj->bindParam($name, $var);\r
+       }\r
+       \r
+       function ErrorNo()\r
+       {\r
+               \r
+               if ($this->_stmt) return $this->_stmt->errorCode();\r
+               else return $this->_connectionID->errorInfo();\r
+       }\r
+\r
+       function BeginTrans()\r
+       {       \r
+               if (!$this->hasTransactions) return false;\r
+               if ($this->transOff) return true; \r
+               $this->transCnt += 1;\r
+               $this->_autocommit = false;\r
+               $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,false);\r
+               return $this->_connectionID->beginTransaction();\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               \r
+               $ret = $this->_connectionID->commit();\r
+               $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true; \r
+               if ($this->transCnt) $this->transCnt -= 1;\r
+               $this->_autocommit = true;\r
+               \r
+               $ret = $this->_connectionID->rollback();\r
+               $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true);\r
+               return $ret;\r
+       }\r
+       \r
+       function Prepare($sql)\r
+       {\r
+               $this->_stmt = $this->_connectionID->prepare($sql);\r
+               if ($this->_stmt) return array($sql,$this->_stmt);\r
+               \r
+               return false;\r
+       }\r
+       \r
+       function PrepareStmt($sql)\r
+       {\r
+               $stmt = $this->_connectionID->prepare($sql);\r
+               if (!$stmt) return false;\r
+               $obj = new ADOPDOStatement($stmt,$this);\r
+               return $obj;\r
+       }\r
+\r
+       /* returns queryID or false */\r
+       function _query($sql,$inputarr=false) \r
+       {\r
+               if (is_array($sql)) {\r
+                       $stmt = $sql[1];\r
+               } else {\r
+                       $stmt = $this->_connectionID->prepare($sql);            \r
+               }\r
+               if ($stmt) {\r
+                       if ($inputarr) $stmt->execute($inputarr);\r
+                       else $stmt->execute();\r
+               }\r
+               $this->_stmt = $stmt;\r
+               return $stmt;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               $this->_stmt = false;\r
+               return true;\r
+       }\r
+\r
+       function _affectedrows()\r
+       {\r
+               return ($this->_stmt) ? $this->_stmt->rowCount() : 0;\r
+       }\r
+       \r
+       function _insertid()\r
+       {\r
+               return ($this->_connectionID) ? $this->_connectionID->lastInsertId() : 0;\r
+       }\r
+}\r
+\r
+class ADOPDOStatement {\r
+\r
+       var $databaseType = "pdo";              \r
+       var $dataProvider = "pdo";\r
+       var $_stmt;\r
+       var $_connectionID;\r
+       \r
+       function ADOPDOStatement($stmt,$connection)\r
+       {\r
+               $this->_stmt = $stmt;\r
+               $this->_connectionID = $connection;\r
+       }\r
+       \r
+       function Execute($inputArr=false)\r
+       {\r
+               $savestmt = $this->_connectionID->_stmt;\r
+               $rs = $this->_connectionID->Execute(array(false,$this->_stmt),$inputArr);\r
+               $this->_connectionID->_stmt = $savestmt;\r
+               return $rs;\r
+       }\r
+       \r
+       function InParameter(&$var,$name,$maxLen=4000,$type=false)\r
+       {\r
+\r
+               if ($type) $this->_stmt->bindParam($name,$var,$type,$maxLen);\r
+               else $this->_stmt->bindParam($name, $var);\r
+       }\r
+       \r
+       function Affected_Rows()\r
+       {\r
+               return ($this->_stmt) ? $this->_stmt->rowCount() : 0;\r
+       }\r
+       \r
+       function ErrorMsg()\r
+       {\r
+               if ($this->_stmt) $arr = $this->_stmt->errorInfo();\r
+               else $arr = $this->_connectionID->errorInfo();\r
+               print_r($arr);\r
+               if ($arr) {\r
+                       if ($arr[0]) return $arr[2];\r
+                       else return '';\r
+               } else return '-1';\r
+       }\r
+       \r
+       function ErrorNo()\r
+       {\r
+               if ($this->_stmt) return $this->_stmt->errorCode();\r
+               else return $this->_connectionID->errorInfo();\r
+       }\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_pdo extends ADORecordSet {  \r
+       \r
+       var $bind = false;\r
+       var $databaseType = "pdo";              \r
+       var $dataProvider = "pdo";\r
+       \r
+       function ADORecordSet_pdo($id,$mode=false)\r
+       {\r
+               if ($mode === false) {  \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch($mode) {\r
+               default:\r
+               case ADODB_FETCH_BOTH: $mode = PDO_FETCH_BOTH; break;\r
+               case ADODB_FETCH_NUM: $mode = PDO_FETCH_NUM; break;\r
+               case ADODB_FETCH_ASSOC:  $mode = PDO_FETCH_ASSOC; break;\r
+               }\r
+               $this->fetchMode = $mode;\r
+               \r
+               $this->_queryID = $id;\r
+               $this->ADORecordSet($id);\r
+       }\r
+\r
+\r
+       // returns the field object\r
+       function &FetchField($fieldOffset = -1) \r
+       {\r
+               \r
+               $off=$fieldOffset+1; // offsets begin at 1\r
+               \r
+               $o= new ADOFieldObject();\r
+               $o->name = @odbc_field_name($this->_queryID,$off);\r
+               $o->type = @odbc_field_type($this->_queryID,$off);\r
+               $o->max_length = @odbc_field_len($this->_queryID,$off);\r
+               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);\r
+               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);\r
+               return $o;\r
+       }\r
+       \r
+       function Init()\r
+       {\r
+               if ($this->_inited) return;\r
+               $this->_inited = true;\r
+               if ($this->_queryID) @$this->_initrs();\r
+               else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+               }\r
+               if ($this->_numOfRows != 0 && $this->_currentRow == -1) {\r
+                       $this->_currentRow = 0;\r
+                       if ($this->EOF = ($this->_fetch() === false)) {\r
+                               $this->_numOfRows = 0; // _numOfRows could be -1\r
+                       }\r
+                       $this->_numOfFields = sizeof($this->fields);\r
+               } else {\r
+                       $this->EOF = true;\r
+               }\r
+       }\r
+       \r
+               \r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1;\r
+               if (!$this->_numOfRows) $this->_numOfRows = -1;\r
+               $this->_numOfFields =0;\r
+       }       \r
+       \r
+       function _seek($row)\r
+       {\r
+               return false;\r
+       }\r
+       \r
+       function _fetch()\r
+       {\r
+               $this->fields = $this->_queryID->fetch($this->fetchMode);\r
+               return !empty($this->fields);\r
+       }\r
+       \r
+       function _close() \r
+       {\r
+               $this->_queryID = false;\r
+       }\r
+\r
+}\r
+\r
+?>
\ No newline at end of file
index f269b9a9105beb7dd0e089263fe46ab422b0607d..13624470331e1ae7e99aaa36bb48d91c098210e4 100644 (file)
@@ -1,14 +1,14 @@
-<?php
-/*
- V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 4.
-  
-  NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
-  remapped to "postgres7". Maintaining multiple postgres drivers is no easy
-  job, so hopefully this will ensure greater consistency and fewer bugs.
-*/
-
+<?php\r
+/*\r
+ V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is\r
+  remapped to "postgres7". Maintaining multiple postgres drivers is no easy\r
+  job, so hopefully this will ensure greater consistency and fewer bugs.\r
+*/\r
+\r
 ?>
\ No newline at end of file
index 257947f98bb1380deadb8563f49a09a235be2dc6..14f151cdb0d80e8c435d86bd121679e4055675e5 100644 (file)
-<?php
-/*
- V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
-  
-  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. 
-  08 Nov 2000 jlim - Minor corrections, removing mysql stuff
-  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
-                                       jlim - changed concat operator to || and data types to MetaType to match documented pgsql types 
-                       see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  
-  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
-  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
-  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. 
-  31 Jan 2002 jlim - finally installed postgresql. testing
-  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
-  
-  See http://www.varlena.com/varlena/GeneralBits/47.php
-  
-       -- What indexes are on my table?
-       select * from pg_indexes where tablename = 'tablename';
-       
-       -- What triggers are on my table?
-       select c.relname as "Table", t.tgname as "Trigger Name", 
-          t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
-          t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
-          p.proname as "Function Name"
-       from pg_trigger t, pg_class c, pg_class cc, pg_proc p
-       where t.tgfoid = p.oid and t.tgrelid = c.oid
-          and t.tgconstrrelid = cc.oid
-          and c.relname = 'tablename';
-       
-       -- What constraints are on my table?
-       select r.relname as "Table", c.conname as "Constraint Name",
-          contype as "Constraint Type", conkey as "Key Columns",
-          confkey as "Foreign Columns", consrc as "Source"
-       from pg_class r, pg_constraint c
-       where r.oid = c.conrelid
-          and relname = 'tablename';
-
-*/
-
-function adodb_addslashes($s)
-{
-       $len = strlen($s);
-       if ($len == 0) return "''";
-       if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted
-       
-       return "'".addslashes($s)."'";
-}
-
-class ADODB_postgres64 extends ADOConnection{
-       var $databaseType = 'postgres64';
-       var $dataProvider = 'postgres';
-       var $hasInsertID = true;
-       var $_resultid = false;
-       var $concat_operator='||';
-       var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
-    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' union 
-        select viewname,'V' from pg_views where viewname not like 'pg\_%'";
-       //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
-       var $isoDates = true; // accepts dates in ISO format
-       var $sysDate = "CURRENT_DATE";
-       var $sysTimeStamp = "CURRENT_TIMESTAMP";
-       var $blobEncodeType = 'C';
-       var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum 
-               FROM pg_class c, pg_attribute a,pg_type t 
-               WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
-AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
-
-       var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum 
-FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n 
-WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
- and c.relnamespace=n.oid and n.nspname='%s' 
-       and a.attname not like '....%%' AND a.attnum > 0 
-       AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
-       
-       // get primary key etc -- from Freek Dijkstra
-       var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key 
-       FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
-       
-       var $hasAffectedRows = true;
-       var $hasLimit = false;  // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
-       // below suggested by Freek Dijkstra 
-       var $true = 't';                // string that represents TRUE for a database
-       var $false = 'f';               // string that represents FALSE for a database
-       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database
-       var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
-       var $hasMoveFirst = true;
-       var $hasGenID = true;
-       var $_genIDSQL = "SELECT NEXTVAL('%s')";
-       var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
-       var $_dropSeqSQL = "DROP SEQUENCE %s";
-       var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
-       var $random = 'random()';               /// random function
-       var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4
-                                                       // http://bugs.php.net/bug.php?id=25404
-                                                       
-       var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
-       
-       // The last (fmtTimeStamp is not entirely correct: 
-       // PostgreSQL also has support for time zones, 
-       // and writes these time in this format: "2001-03-01 18:59:26+02". 
-       // There is no code for the "+02" time zone information, so I just left that out. 
-       // I'm not familiar enough with both ADODB as well as Postgres 
-       // to know what the concequences are. The other values are correct (wheren't in 0.94)
-       // -- Freek Dijkstra 
-
-       function ADODB_postgres64() 
-       {
-       // changes the metaColumnsSQL, adds columns: attnum[6]
-       }
-       
-       function ServerInfo()
-       {
-               if (isset($this->version)) return $this->version;
-               
-               $arr['description'] = $this->GetOne("select version()");
-               $arr['version'] = ADOConnection::_findvers($arr['description']);
-               $this->version = $arr;
-               return $arr;
-       }
-/*
-       function IfNull( $field, $ifNull ) 
-       {
-               return " NULLIF($field, $ifNull) "; // if PGSQL
-       }
-*/
-       // get the last id - never tested
-       function pg_insert_id($tablename,$fieldname)
-       {
-               $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
-               if ($result) {
-                       $arr = @pg_fetch_row($result,0);
-                       pg_freeresult($result);
-                       if (isset($arr[0])) return $arr[0];
-               }
-               return false;
-       }
-       
-/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
-Using a OID as a unique identifier is not generally wise. 
-Unless you are very careful, you might end up with a tuple having 
-a different OID if a database must be reloaded. */
-       function _insertid()
-       {
-               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
-               return pg_getlastoid($this->_resultid);
-       }
-
-// I get this error with PHP before 4.0.6 - jlim
-// Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44
-   function _affectedrows()
-   {
-               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
-               return pg_cmdtuples($this->_resultid);
-   }
-   
-       
-               // returns true/false
-       function BeginTrans()
-       {
-               if ($this->transOff) return true;
-               $this->transCnt += 1;
-               return @pg_Exec($this->_connectionID, "begin");
-       }
-       
-       function RowLock($tables,$where) 
-       {
-               if (!$this->transCnt) $this->BeginTrans();
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");
-       }
-
-       // returns true/false. 
-       function CommitTrans($ok=true) 
-       { 
-               if ($this->transOff) return true;
-               if (!$ok) return $this->RollbackTrans();
-               
-               $this->transCnt -= 1;
-               return @pg_Exec($this->_connectionID, "commit");
-       }
-       
-       // returns true/false
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true;
-               $this->transCnt -= 1;
-               return @pg_Exec($this->_connectionID, "rollback");
-       }
-       
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
-       {       
-               if ($mask) {
-                       $save = $this->metaTablesSQL;
-                       $mask = $this->qstr(strtolower($mask));
-                       $this->metaTablesSQL = "
-select tablename,'T' from pg_tables where tablename like $mask union 
-select viewname,'V' from pg_views where viewname like $mask";
-               }
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
-               
-               if ($mask) {
-                       $this->metaTablesSQL = $save;
-               }
-               return $ret;
-       }
-       
-       /*
-       // if magic quotes disabled, use pg_escape_string()
-       function qstr($s,$magic_quotes=false)
-       {
-               if (!$magic_quotes) {
-                       if (ADODB_PHPVER >= 0x4200) {
-                               return  "'".pg_escape_string($s)."'";
-                       }
-                       if ($this->replaceQuote[0] == '\\'){
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-                       }
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
-               }
-               
-               // undo magic quotes for "
-               $s = str_replace('\\"','"',$s);
-               return "'$s'";
-       }
-       */
-       
-       
-       // 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 = 'TO_CHAR('.$col.",'";
-               
-               $len = strlen($fmt);
-               for ($i=0; $i < $len; $i++) {
-                       $ch = $fmt[$i];
-                       switch($ch) {
-                       case 'Y':
-                       case 'y':
-                               $s .= 'YYYY';
-                               break;
-                       case 'Q':
-                       case 'q':
-                               $s .= 'Q';
-                               break;
-                               
-                       case 'M':
-                               $s .= 'Mon';
-                               break;
-                               
-                       case 'm':
-                               $s .= 'MM';
-                               break;
-                       case 'D':
-                       case 'd':
-                               $s .= 'DD';
-                               break;
-                       
-                       case 'H':
-                               $s.= 'HH24';
-                               break;
-                               
-                       case 'h':
-                               $s .= 'HH';
-                               break;
-                               
-                       case 'i':
-                               $s .= 'MI';
-                               break;
-                       
-                       case 's':
-                               $s .= 'SS';
-                               break;
-                       
-                       case 'a':
-                       case 'A':
-                               $s .= 'AM';
-                               break;
-                               
-                       default:
-                       // handle escape characters...
-                               if ($ch == '\\') {
-                                       $i++;
-                                       $ch = substr($fmt,$i,1);
-                               }
-                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
-                               else $s .= '"'.$ch.'"';
-                               
-                       }
-               }
-               return $s. "')";
-       }
-       
-       
-       
-       /* 
-       * Load a Large Object from a file 
-       * - the procedure stores the object id in the table and imports the object using 
-       * postgres proprietary blob handling routines 
-       *
-       * contributed by Mattia Rossi mattia@technologist.com
-       * modified for safe mode by juraj chlebec
-       */ 
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
-       { 
-               pg_exec ($this->_connectionID, "begin"); 
-               
-               $fd = fopen($path,'r');
-               $contents = fread($fd,filesize($path));
-               fclose($fd);
-               
-               $oid = pg_lo_create($this->_connectionID);
-               $handle = pg_lo_open($this->_connectionID, $oid, 'w');
-               pg_lo_write($handle, $contents);
-               pg_lo_close($handle);
-               
-               // $oid = pg_lo_import ($path); 
-               pg_exec($this->_connectionID, "commit"); 
-               $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); 
-               $rez = !empty($rs); 
-               return $rez; 
-       } 
-       
-       /* 
-       * If an OID is detected, then we use pg_lo_* to open the oid file and read the
-       * real blob from the db using the oid supplied as a parameter. If you are storing
-       * blobs using bytea, we autodetect and process it so this function is not needed.
-       *
-       * contributed by Mattia Rossi mattia@technologist.com
-       *
-       * see http://www.postgresql.org/idocs/index.php?largeobjects.html
-       */ 
-       function BlobDecode( $blob) 
-       { 
-               if (strlen($blob) > 24) return $blob;
-               
-               @pg_exec($this->_connectionID,"begin"); 
-               $fd = @pg_lo_open($this->_connectionID,$blob,"r");
-               if ($fd === false) {
-                       @pg_exec($this->_connectionID,"commit");
-                       return $blob;
-               }
-               $realblob = @pg_loreadall($fd); 
-               @pg_loclose($fd); 
-               @pg_exec($this->_connectionID,"commit"); 
-               return $realblob;
-       } 
-       
-       /* 
-               See http://www.postgresql.org/idocs/index.php?datatype-binary.html
-               
-               NOTE: SQL string literals (input strings) must be preceded with two backslashes 
-               due to the fact that they must pass through two parsers in the PostgreSQL 
-               backend.
-       */
-       function BlobEncode($blob)
-       {
-               if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
-               
-               /*92=backslash, 0=null, 39=single-quote*/
-               $badch = array(chr(92),chr(0),chr(39)); # \  null  '
-               $fixch = array('\\\\134','\\\\000','\\\\047');
-               return adodb_str_replace($badch,$fixch,$blob);
-               
-               // note that there is a pg_escape_bytea function only for php 4.2.0 or later
-       }
-       
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
-       {
-               // do not use bind params which uses qstr(), as blobencode() already quotes data
-               return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
-       }
-       
-       function OffsetDate($dayFraction,$date=false)
-       {               
-               if (!$date) $date = $this->sysDate;
-               return "($date+interval'$dayFraction days')";
-       }
-       
-
-       // for schema support, pass in the $table param "$schema.$tabname".
-       // converts field names to lowercase, $upper is ignored
-       function &MetaColumns($table,$upper=true) 
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $schema = false;
-               $this->_findschema($table,$schema);
-               
-               $table = strtolower($table);
-
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
-               
-               if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
-               else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
-               if (isset($savem)) $this->SetFetchMode($savem);
-               $ADODB_FETCH_MODE = $save;
-               
-               if ($rs === false) return false;
-               
-               if (!empty($this->metaKeySQL)) {
-                       // If we want the primary keys, we have to issue a separate query
-                       // Of course, a modified version of the metaColumnsSQL query using a 
-                       // LEFT JOIN would have been much more elegant, but postgres does 
-                       // not support OUTER JOINS. So here is the clumsy way.
-                       
-                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-                       
-                       $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
-                       // fetch all result in once for performance.
-                       $keys =& $rskey->GetArray();
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save;
-                       
-                       $rskey->Close();
-                       unset($rskey);
-               }
-
-               $rsdefa = array();
-               if (!empty($this->metaDefaultsSQL)) {
-                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-                       $sql = sprintf($this->metaDefaultsSQL, ($table));
-                       $rsdef = $this->Execute($sql);
-                       if (isset($savem)) $this->SetFetchMode($savem);
-                       $ADODB_FETCH_MODE = $save;
-                       
-                       if ($rsdef) {
-                               while (!$rsdef->EOF) {
-                                       $num = $rsdef->fields['num'];
-                                       $s = $rsdef->fields['def'];
-                                       if (substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
-                                               $s = substr($s, 1);
-                                               $s = substr($s, 0, strlen($s) - 1);
-                                       }
-
-                                       $rsdefa[$num] = $s;
-                                       $rsdef->MoveNext();
-                               }
-                       } else {
-                               ADOConnection::outp( "==> SQL => " . $sql);
-                       }
-                       unset($rsdef);
-               }
-       
-               $retarr = array();
-               while (!$rs->EOF) {     
-                       $fld = new ADOFieldObject();
-                       $fld->name = $rs->fields[0];
-                       $fld->type = $rs->fields[1];
-                       $fld->max_length = $rs->fields[2];
-                       if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
-                       if ($fld->max_length <= 0) $fld->max_length = -1;
-                       
-                       // dannym
-                       // 5 hasdefault; 6 num-of-column
-                       $fld->has_default = ($rs->fields[5] == 't');
-                       if ($fld->has_default) {
-                               $fld->default_value = $rsdefa[$rs->fields[6]];
-                       }
-
-                       //Freek
-                       if ($rs->fields[4] == $this->true) {
-                               $fld->not_null = true;
-                       }
-                       
-                       // Freek
-                       if (is_array($keys)) {
-                               foreach($keys as $key) {
-                                       if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) 
-                                               $fld->primary_key = true;
-                                       if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) 
-                                               $fld->unique = true; // What name is more compatible?
-                               }
-                       }
-                       
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
-                       else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;
-                       
-                       $rs->MoveNext();
-               }
-               $rs->Close();
-               return $retarr; 
-               
-       }
-
-         function &MetaIndexes ($table, $primary = FALSE)
-      {
-         global $ADODB_FETCH_MODE;
-                
-                               $schema = false;
-                               $this->_findschema($table,$schema);
-                               
-                               if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
-                                       $sql = '
-SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" 
-FROM pg_catalog.pg_class c 
-JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid 
-JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
-       ,pg_namespace n 
-WHERE c2.relname=\'%s\' and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false';
-                               } else {
-                       $sql = '
-SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
-FROM pg_catalog.pg_class c
-JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
-JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
-WHERE c2.relname=\'%s\'';
-                       }
-                                           
-                if ($primary == FALSE) {
-                        $sql .= ' AND i.indisprimary=false;';
-                }
-                
-                $save = $ADODB_FETCH_MODE;
-                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-                if ($this->fetchMode !== FALSE) {
-                        $savem = $this->SetFetchMode(FALSE);
-                }
-                
-                $rs = $this->Execute(sprintf($sql,$table,$schema));
-                
-                if (isset($savem)) {
-                        $this->SetFetchMode($savem);
-                }
-                $ADODB_FETCH_MODE = $save;
-                
-                if (!is_object($rs)) {
-                        return FALSE;
-                }
-                
-                $col_names = $this->MetaColumnNames($table);
-                $indexes = array();
-                
-                while ($row = $rs->FetchRow()) {
-                        $columns = array();
-                        
-                        foreach (explode(' ', $row[2]) as $col) {
-                                $columns[] = $col_names[$col - 1];
-                        }
-                        
-                        $indexes[$row[0]] = array(
-                                'unique' => ($row[1] == 't'),
-                                'columns' => $columns
-                        );
-                }
-                
-                return $indexes;
-        }
-
-       // returns true or false
-       //
-       // examples:
-       //      $db->Connect("host=host1 user=user1 password=secret port=4341");
-       //      $db->Connect('host1','user1','secret');
-       function _connect($str,$user='',$pwd='',$db='',$ctype=0)
-       {
-               
-               if (!function_exists('pg_pconnect')) return false;
-               
-               $this->_errorMsg = false;
-               
-               if ($user || $pwd || $db) {
-                       $user = adodb_addslashes($user);
-                       $pwd = adodb_addslashes($pwd);
-                       if (strlen($db) == 0) $db = 'template1';
-                       $db = adodb_addslashes($db);
-                       if ($str)  {
-                               $host = split(":", $str);
-                               if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
-                               else $str = 'host=localhost';
-                               if (isset($host[1])) $str .= " port=$host[1]";
-                       }
-                               if ($user) $str .= " user=".$user;
-                               if ($pwd)  $str .= " password=".$pwd;
-                               if ($db)   $str .= " dbname=".$db;
-               }
-
-               //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
-               
-               if ($ctype === 1) { // persistent
-                       $this->_connectionID = pg_pconnect($str);
-               } else {
-                       if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
-                       static $ncnt;
-                       
-                               if (empty($ncnt)) $ncnt = 1;
-                               else $ncnt += 1;
-                               
-                               $str .= str_repeat(' ',$ncnt);
-                       }
-                       $this->_connectionID = pg_connect($str);
-               }
-               if ($this->_connectionID === false) return false;
-               $this->Execute("set datestyle='ISO'");
-               return true;
-       }
-       
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
-       {
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
-       }
-        
-       // returns true or false
-       //
-       // examples:
-       //      $db->PConnect("host=host1 user=user1 password=secret port=4341");
-       //      $db->PConnect('host1','user1','secret');
-       function _pconnect($str,$user='',$pwd='',$db='')
-       {
-               return $this->_connect($str,$user,$pwd,$db,1);
-       }
-       
-
-       // returns queryID or false
-       function _query($sql,$inputarr)
-       {
-               
-               if ($inputarr) {
-               /*
-                       It appears that PREPARE/EXECUTE is slower for many queries.
-                       
-                       For query executed 1000 times:
-                       "select id,firstname,lastname from adoxyz 
-                               where firstname not like ? and lastname not like ? and id = ?"
-                               
-                       with plan = 1.51861286163 secs
-                       no plan =   1.26903700829 secs
-
-                       
-
-               */
-                       $plan = 'P'.md5($sql);
-                               
-                       $execp = '';
-                       foreach($inputarr as $v) {
-                               if ($execp) $execp .= ',';
-                               if (is_string($v)) {
-                                       if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
-                               } else {
-                                       $execp .= $v;
-                               }
-                       }
-                       
-                       if ($execp) $exsql = "EXECUTE $plan ($execp)";
-                       else $exsql = "EXECUTE $plan";
-                       
-                       $rez = @pg_exec($this->_connectionID,$exsql);
-                       if (!$rez) {
-                       # Perhaps plan does not exist? Prepare/compile plan.
-                               $params = '';
-                               foreach($inputarr as $v) {
-                                       if ($params) $params .= ',';
-                                       if (is_string($v)) {
-                                               $params .= 'VARCHAR';
-                                       } else if (is_integer($v)) {
-                                               $params .= 'INTEGER';
-                                       } else {
-                                               $params .= "REAL";
-                                       }
-                               }
-                               $sqlarr = explode('?',$sql);
-                               //print_r($sqlarr);
-                               $sql = '';
-                               $i = 1;
-                               foreach($sqlarr as $v) {
-                                       $sql .= $v.' $'.$i;
-                                       $i++;
-                               }
-                               $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);               
-                               //adodb_pr($s);
-                               pg_exec($this->_connectionID,$s);
-                               echo $this->ErrorMsg();
-                       }
-                       
-                       $rez = pg_exec($this->_connectionID,$exsql);
-               } else {
-                       $this->_errorMsg = false;
-                       //adodb_backtrace();
-                       $rez = pg_exec($this->_connectionID,$sql);
-               }
-               // check if no data returned, then no need to create real recordset
-               if ($rez && pg_numfields($rez) <= 0) {
-                       if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
-                               pg_freeresult($this->_resultid);
-                       }
-                       $this->_resultid = $rez;
-                       return true;
-               }
-               
-               return $rez;
-       }
-       
-
-       /*      Returns: the last error message from previous database operation        */      
-       function ErrorMsg() 
-       {
-               if ($this->_errorMsg !== false) return $this->_errorMsg;
-               if (ADODB_PHPVER >= 0x4300) {
-                       if (!empty($this->_resultid)) {
-                               $this->_errorMsg = @pg_result_error($this->_resultid);
-                               if ($this->_errorMsg) return $this->_errorMsg;
-                       }
-                       
-                       if (!empty($this->_connectionID)) {
-                               $this->_errorMsg = @pg_last_error($this->_connectionID);
-                       } else $this->_errorMsg = @pg_last_error();
-               } else {
-                       if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();
-                       else $this->_errorMsg = @pg_errormessage($this->_connectionID);
-               }
-               return $this->_errorMsg;
-       }
-       
-       function ErrorNo()
-       {
-               $e = $this->ErrorMsg();
-               return strlen($e) ? $e : 0;
-       }
-
-       // returns true or false
-       function _close()
-       {
-               if ($this->transCnt) $this->RollbackTrans();
-               if ($this->_resultid) {
-                       @pg_freeresult($this->_resultid);
-                       $this->_resultid = false;
-               }
-               @pg_close($this->_connectionID);
-               $this->_connectionID = false;
-               return true;
-       }
-       
-       
-       /*
-       * Maximum size of C field
-       */
-       function CharMax()
-       {
-               return 1000000000;  // should be 1 Gb?
-       }
-       
-       /*
-       * Maximum size of X field
-       */
-       function TextMax()
-       {
-               return 1000000000; // should be 1 Gb?
-       }
-       
-               
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_postgres64 extends ADORecordSet{
-       var $_blobArr;
-       var $databaseType = "postgres64";
-       var $canSeek = true;
-       function ADORecordSet_postgres64($queryID,$mode=false) 
-       {
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               switch ($mode)
-               {
-               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
-               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
-               default:
-               case ADODB_FETCH_DEFAULT:
-               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;
-               }
-               $this->ADORecordSet($queryID);
-       }
-       
-       function &GetRowAssoc($upper=true)
-       {
-               if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
-               $row =& ADORecordSet::GetRowAssoc($upper);
-               return $row;
-       }
-
-       function _initrs()
-       {
-       global $ADODB_COUNTRECS;
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;
-               $this->_numOfFields = @pg_numfields($this->_queryID);
-               
-               // cache types for blob decode check
-               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
-                       $f1 = $this->FetchField($i);
-                       //print_r($f1);
-                       if ($f1->type == 'bytea') $this->_blobArr[$i] = $f1->name;
-               }               
-       }
-
-               /* Use associative array to get fields array */
-       function Fields($colname)
-       {
-               if ($this->fetchMode != PGSQL_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)]];
-       }
-
-       function &FetchField($fieldOffset = 0) 
-       {
-               $off=$fieldOffset; // offsets begin at 0
-               
-               $o= new ADOFieldObject();
-               $o->name = @pg_fieldname($this->_queryID,$off);
-               $o->type = @pg_fieldtype($this->_queryID,$off);
-               $o->max_length = @pg_fieldsize($this->_queryID,$off);
-               //print_r($o);          
-               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
-               return $o;      
-       }
-
-       function _seek($row)
-       {
-               return @pg_fetch_row($this->_queryID,$row);
-       }
-       
-       function _decode($blob)
-       {
-               eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
-               return $realblob;       
-       }
-       
-       function _fixblobs()
-       {
-               if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
-                       foreach($this->_blobArr as $k => $v) {
-                               $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
-                       }
-               }
-               if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
-                       foreach($this->_blobArr as $k => $v) {
-                               $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
-                       }
-               }
-       }
-       
-       // 10% speedup to move MoveNext to child class
-       function MoveNext() 
-       {
-               if (!$this->EOF) {
-                       $this->_currentRow++;
-                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
-                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
-                               if (is_array($this->fields) && $this->fields) {
-                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
-                                       return true;
-                               }
-                       }
-                       $this->fields = false;
-                       $this->EOF = true;
-               }
-               return false;
-       }               
-       
-       function _fetch()
-       {
-                               
-               if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
-               return false;
-
-               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
-               
-       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
-                       
-               return (is_array($this->fields));
-       }
-
-       function _close() 
-       { 
-               return @pg_freeresult($this->_queryID);
-       }
-
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-                               case 'MONEY': // stupid, postgres expects money to be a string
-                               case 'INTERVAL':
-                               case 'CHAR':
-                               case 'CHARACTER':
-                               case 'VARCHAR':
-                               case 'NAME':
-                               case 'BPCHAR':
-                               case '_VARCHAR':
-                                       if ($len <= $this->blobSize) return 'C';
-                               
-                               case 'TEXT':
-                                       return 'X';
-               
-                               case 'IMAGE': // user defined type
-                               case 'BLOB': // user defined type
-                               case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'
-                               case 'VARBIT':
-                               case 'BYTEA':
-                                       return 'B';
-                               
-                               case 'BOOL':
-                               case 'BOOLEAN':
-                                       return 'L';
-                               
-                               case 'DATE':
-                                       return 'D';
-                               
-                               case 'TIME':
-                               case 'DATETIME':
-                               case 'TIMESTAMP':
-                               case 'TIMESTAMPTZ':
-                                       return 'T';
-                               
-                               case 'SMALLINT': 
-                               case 'BIGINT': 
-                               case 'INTEGER': 
-                               case 'INT8': 
-                               case 'INT4':
-                               case 'INT2':
-                                       if (isset($fieldobj) &&
-                               empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
-                               
-                               case 'OID':
-                               case 'SERIAL':
-                                       return 'R';
-                               
-                                default:
-                                       return 'N';
-                       }
-       }
-
-}
-?>
+<?php\r
+/*\r
+ V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+  \r
+  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. \r
+  08 Nov 2000 jlim - Minor corrections, removing mysql stuff\r
+  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>\r
+                                       jlim - changed concat operator to || and data types to MetaType to match documented pgsql types \r
+                       see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  \r
+  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>\r
+  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>\r
+  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. \r
+  31 Jan 2002 jlim - finally installed postgresql. testing\r
+  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type\r
+  \r
+  See http://www.varlena.com/varlena/GeneralBits/47.php\r
+  \r
+       -- What indexes are on my table?\r
+       select * from pg_indexes where tablename = 'tablename';\r
+       \r
+       -- What triggers are on my table?\r
+       select c.relname as "Table", t.tgname as "Trigger Name", \r
+          t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",\r
+          t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",\r
+          p.proname as "Function Name"\r
+       from pg_trigger t, pg_class c, pg_class cc, pg_proc p\r
+       where t.tgfoid = p.oid and t.tgrelid = c.oid\r
+          and t.tgconstrrelid = cc.oid\r
+          and c.relname = 'tablename';\r
+       \r
+       -- What constraints are on my table?\r
+       select r.relname as "Table", c.conname as "Constraint Name",\r
+          contype as "Constraint Type", conkey as "Key Columns",\r
+          confkey as "Foreign Columns", consrc as "Source"\r
+       from pg_class r, pg_constraint c\r
+       where r.oid = c.conrelid\r
+          and relname = 'tablename';\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+function adodb_addslashes($s)\r
+{\r
+       $len = strlen($s);\r
+       if ($len == 0) return "''";\r
+       if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted\r
+       \r
+       return "'".addslashes($s)."'";\r
+}\r
+\r
+class ADODB_postgres64 extends ADOConnection{\r
+       var $databaseType = 'postgres64';\r
+       var $dataProvider = 'postgres';\r
+       var $hasInsertID = true;\r
+       var $_resultid = false;\r
+       var $concat_operator='||';\r
+       var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";\r
+    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'\r
+       and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',\r
+        'sql_packages', 'sql_sizing', 'sql_sizing_profiles') \r
+       union \r
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'";\r
+       //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";\r
+       var $isoDates = true; // accepts dates in ISO format\r
+       var $sysDate = "CURRENT_DATE";\r
+       var $sysTimeStamp = "CURRENT_TIMESTAMP";\r
+       var $blobEncodeType = 'C';\r
+       var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum \r
+               FROM pg_class c, pg_attribute a,pg_type t \r
+               WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'\r
+AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";\r
+\r
+       var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum \r
+FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n \r
+WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))\r
+ and c.relnamespace=n.oid and n.nspname='%s' \r
+       and a.attname not like '....%%' AND a.attnum > 0 \r
+       AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";\r
+       \r
+       // get primary key etc -- from Freek Dijkstra\r
+       var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key \r
+       FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";\r
+       \r
+       var $hasAffectedRows = true;\r
+       var $hasLimit = false;  // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+       // below suggested by Freek Dijkstra \r
+       var $true = 't';                // string that represents TRUE for a database\r
+       var $false = 'f';               // string that represents FALSE for a database\r
+       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.\r
+       var $hasMoveFirst = true;\r
+       var $hasGenID = true;\r
+       var $_genIDSQL = "SELECT NEXTVAL('%s')";\r
+       var $_genSeqSQL = "CREATE SEQUENCE %s START %s";\r
+       var $_dropSeqSQL = "DROP SEQUENCE %s";\r
+       var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";\r
+       var $random = 'random()';               /// random function\r
+       var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4\r
+                                                       // http://bugs.php.net/bug.php?id=25404\r
+                                                       \r
+       var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database\r
+       \r
+       // The last (fmtTimeStamp is not entirely correct: \r
+       // PostgreSQL also has support for time zones, \r
+       // and writes these time in this format: "2001-03-01 18:59:26+02". \r
+       // There is no code for the "+02" time zone information, so I just left that out. \r
+       // I'm not familiar enough with both ADODB as well as Postgres \r
+       // to know what the concequences are. The other values are correct (wheren't in 0.94)\r
+       // -- Freek Dijkstra \r
+\r
+       function ADODB_postgres64() \r
+       {\r
+       // changes the metaColumnsSQL, adds columns: attnum[6]\r
+       }\r
+       \r
+       function ServerInfo()\r
+       {\r
+               if (isset($this->version)) return $this->version;\r
+               \r
+               $arr['description'] = $this->GetOne("select version()");\r
+               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
+               $this->version = $arr;\r
+               return $arr;\r
+       }\r
+/*\r
+       function IfNull( $field, $ifNull ) \r
+       {\r
+               return " NULLIF($field, $ifNull) "; // if PGSQL\r
+       }\r
+*/\r
+       // get the last id - never tested\r
+       function pg_insert_id($tablename,$fieldname)\r
+       {\r
+               $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");\r
+               if ($result) {\r
+                       $arr = @pg_fetch_row($result,0);\r
+                       pg_freeresult($result);\r
+                       if (isset($arr[0])) return $arr[0];\r
+               }\r
+               return false;\r
+       }\r
+       \r
+/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:\r
+Using a OID as a unique identifier is not generally wise. \r
+Unless you are very careful, you might end up with a tuple having \r
+a different OID if a database must be reloaded. */\r
+       function _insertid()\r
+       {\r
+               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;\r
+               return pg_getlastoid($this->_resultid);\r
+       }\r
+\r
+// I get this error with PHP before 4.0.6 - jlim\r
+// Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44\r
+   function _affectedrows()\r
+   {\r
+               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;\r
+               return pg_cmdtuples($this->_resultid);\r
+   }\r
+   \r
+       \r
+               // returns true/false\r
+       function BeginTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+               return @pg_Exec($this->_connectionID, "begin");\r
+       }\r
+       \r
+       function RowLock($tables,$where) \r
+       {\r
+               if (!$this->transCnt) $this->BeginTrans();\r
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
+       }\r
+\r
+       // returns true/false. \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true;\r
+               if (!$ok) return $this->RollbackTrans();\r
+               \r
+               $this->transCnt -= 1;\r
+               return @pg_Exec($this->_connectionID, "commit");\r
+       }\r
+       \r
+       // returns true/false\r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               $this->transCnt -= 1;\r
+               return @pg_Exec($this->_connectionID, "rollback");\r
+       }\r
+       \r
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
+       {       \r
+               if ($mask) {\r
+                       $save = $this->metaTablesSQL;\r
+                       $mask = $this->qstr(strtolower($mask));\r
+                       $this->metaTablesSQL = "\r
+select tablename,'T' from pg_tables where tablename like $mask union \r
+select viewname,'V' from pg_views where viewname like $mask";\r
+               }\r
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
+               \r
+               if ($mask) {\r
+                       $this->metaTablesSQL = $save;\r
+               }\r
+               return $ret;\r
+       }\r
+       \r
+       /*\r
+       // if magic quotes disabled, use pg_escape_string()\r
+       function qstr($s,$magic_quotes=false)\r
+       {\r
+               if (!$magic_quotes) {\r
+                       if (ADODB_PHPVER >= 0x4200) {\r
+                               return  "'".pg_escape_string($s)."'";\r
+                       }\r
+                       if ($this->replaceQuote[0] == '\\'){\r
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
+                       }\r
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
+               }\r
+               \r
+               // undo magic quotes for "\r
+               $s = str_replace('\\"','"',$s);\r
+               return "'$s'";\r
+       }\r
+       */\r
+       \r
+       \r
+       // Format date column in sql string given an input format that understands Y M D\r
+       function SQLDate($fmt, $col=false)\r
+       {       \r
+               if (!$col) $col = $this->sysTimeStamp;\r
+               $s = 'TO_CHAR('.$col.",'";\r
+               \r
+               $len = strlen($fmt);\r
+               for ($i=0; $i < $len; $i++) {\r
+                       $ch = $fmt[$i];\r
+                       switch($ch) {\r
+                       case 'Y':\r
+                       case 'y':\r
+                               $s .= 'YYYY';\r
+                               break;\r
+                       case 'Q':\r
+                       case 'q':\r
+                               $s .= 'Q';\r
+                               break;\r
+                               \r
+                       case 'M':\r
+                               $s .= 'Mon';\r
+                               break;\r
+                               \r
+                       case 'm':\r
+                               $s .= 'MM';\r
+                               break;\r
+                       case 'D':\r
+                       case 'd':\r
+                               $s .= 'DD';\r
+                               break;\r
+                       \r
+                       case 'H':\r
+                               $s.= 'HH24';\r
+                               break;\r
+                               \r
+                       case 'h':\r
+                               $s .= 'HH';\r
+                               break;\r
+                               \r
+                       case 'i':\r
+                               $s .= 'MI';\r
+                               break;\r
+                       \r
+                       case 's':\r
+                               $s .= 'SS';\r
+                               break;\r
+                       \r
+                       case 'a':\r
+                       case 'A':\r
+                               $s .= 'AM';\r
+                               break;\r
+                               \r
+                       default:\r
+                       // handle escape characters...\r
+                               if ($ch == '\\') {\r
+                                       $i++;\r
+                                       $ch = substr($fmt,$i,1);\r
+                               }\r
+                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;\r
+                               else $s .= '"'.$ch.'"';\r
+                               \r
+                       }\r
+               }\r
+               return $s. "')";\r
+       }\r
+       \r
+       \r
+       \r
+       /* \r
+       * Load a Large Object from a file \r
+       * - the procedure stores the object id in the table and imports the object using \r
+       * postgres proprietary blob handling routines \r
+       *\r
+       * contributed by Mattia Rossi mattia@technologist.com\r
+       * modified for safe mode by juraj chlebec\r
+       */ \r
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') \r
+       { \r
+               pg_exec ($this->_connectionID, "begin"); \r
+               \r
+               $fd = fopen($path,'r');\r
+               $contents = fread($fd,filesize($path));\r
+               fclose($fd);\r
+               \r
+               $oid = pg_lo_create($this->_connectionID);\r
+               $handle = pg_lo_open($this->_connectionID, $oid, 'w');\r
+               pg_lo_write($handle, $contents);\r
+               pg_lo_close($handle);\r
+               \r
+               // $oid = pg_lo_import ($path); \r
+               pg_exec($this->_connectionID, "commit"); \r
+               $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); \r
+               $rez = !empty($rs); \r
+               return $rez; \r
+       } \r
+       \r
+       /* \r
+       * If an OID is detected, then we use pg_lo_* to open the oid file and read the\r
+       * real blob from the db using the oid supplied as a parameter. If you are storing\r
+       * blobs using bytea, we autodetect and process it so this function is not needed.\r
+       *\r
+       * contributed by Mattia Rossi mattia@technologist.com\r
+       *\r
+       * see http://www.postgresql.org/idocs/index.php?largeobjects.html\r
+       */ \r
+       function BlobDecode( $blob) \r
+       { \r
+               if (strlen($blob) > 24) return $blob;\r
+               \r
+               @pg_exec($this->_connectionID,"begin"); \r
+               $fd = @pg_lo_open($this->_connectionID,$blob,"r");\r
+               if ($fd === false) {\r
+                       @pg_exec($this->_connectionID,"commit");\r
+                       return $blob;\r
+               }\r
+               $realblob = @pg_loreadall($fd); \r
+               @pg_loclose($fd); \r
+               @pg_exec($this->_connectionID,"commit"); \r
+               return $realblob;\r
+       } \r
+       \r
+       /* \r
+               See http://www.postgresql.org/idocs/index.php?datatype-binary.html\r
+               \r
+               NOTE: SQL string literals (input strings) must be preceded with two backslashes \r
+               due to the fact that they must pass through two parsers in the PostgreSQL \r
+               backend.\r
+       */\r
+       function BlobEncode($blob)\r
+       {\r
+               if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);\r
+               \r
+               /*92=backslash, 0=null, 39=single-quote*/\r
+               $badch = array(chr(92),chr(0),chr(39)); # \  null  '\r
+               $fixch = array('\\\\134','\\\\000','\\\\047');\r
+               return adodb_str_replace($badch,$fixch,$blob);\r
+               \r
+               // note that there is a pg_escape_bytea function only for php 4.2.0 or later\r
+       }\r
+       \r
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
+       {\r
+               // do not use bind params which uses qstr(), as blobencode() already quotes data\r
+               return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");\r
+       }\r
+       \r
+       function OffsetDate($dayFraction,$date=false)\r
+       {               \r
+               if (!$date) $date = $this->sysDate;\r
+               return "($date+interval'$dayFraction days')";\r
+       }\r
+       \r
+\r
+       // for schema support, pass in the $table param "$schema.$tabname".\r
+       // converts field names to lowercase, $upper is ignored\r
+       function &MetaColumns($table,$upper=true) \r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $schema = false;\r
+               $this->_findschema($table,$schema);\r
+               \r
+               $table = strtolower($table);\r
+\r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
+               \r
+               if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));\r
+               else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));\r
+               if (isset($savem)) $this->SetFetchMode($savem);\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               if ($rs === false) return false;\r
+               \r
+               if (!empty($this->metaKeySQL)) {\r
+                       // If we want the primary keys, we have to issue a separate query\r
+                       // Of course, a modified version of the metaColumnsSQL query using a \r
+                       // LEFT JOIN would have been much more elegant, but postgres does \r
+                       // not support OUTER JOINS. So here is the clumsy way.\r
+                       \r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+                       \r
+                       $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));\r
+                       // fetch all result in once for performance.\r
+                       $keys =& $rskey->GetArray();\r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       \r
+                       $rskey->Close();\r
+                       unset($rskey);\r
+               }\r
+\r
+               $rsdefa = array();\r
+               if (!empty($this->metaDefaultsSQL)) {\r
+                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+                       $sql = sprintf($this->metaDefaultsSQL, ($table));\r
+                       $rsdef = $this->Execute($sql);\r
+                       if (isset($savem)) $this->SetFetchMode($savem);\r
+                       $ADODB_FETCH_MODE = $save;\r
+                       \r
+                       if ($rsdef) {\r
+                               while (!$rsdef->EOF) {\r
+                                       $num = $rsdef->fields['num'];\r
+                                       $s = $rsdef->fields['def'];\r
+                                       if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */\r
+                                               $s = substr($s, 1);\r
+                                               $s = substr($s, 0, strlen($s) - 1);\r
+                                       }\r
+\r
+                                       $rsdefa[$num] = $s;\r
+                                       $rsdef->MoveNext();\r
+                               }\r
+                       } else {\r
+                               ADOConnection::outp( "==> SQL => " . $sql);\r
+                       }\r
+                       unset($rsdef);\r
+               }\r
+       \r
+               $retarr = array();\r
+               while (!$rs->EOF) {     \r
+                       $fld = new ADOFieldObject();\r
+                       $fld->name = $rs->fields[0];\r
+                       $fld->type = $rs->fields[1];\r
+                       $fld->max_length = $rs->fields[2];\r
+                       if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;\r
+                       if ($fld->max_length <= 0) $fld->max_length = -1;\r
+                       \r
+                       // dannym\r
+                       // 5 hasdefault; 6 num-of-column\r
+                       $fld->has_default = ($rs->fields[5] == 't');\r
+                       if ($fld->has_default) {\r
+                               $fld->default_value = $rsdefa[$rs->fields[6]];\r
+                       }\r
+\r
+                       //Freek\r
+                       if ($rs->fields[4] == $this->true) {\r
+                               $fld->not_null = true;\r
+                       }\r
+                       \r
+                       // Freek\r
+                       if (is_array($keys)) {\r
+                               foreach($keys as $key) {\r
+                                       if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) \r
+                                               $fld->primary_key = true;\r
+                                       if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) \r
+                                               $fld->unique = true; // What name is more compatible?\r
+                               }\r
+                       }\r
+                       \r
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
+                       else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;\r
+                       \r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close();\r
+               return $retarr; \r
+               \r
+       }\r
+\r
+         function &MetaIndexes ($table, $primary = FALSE)\r
+      {\r
+         global $ADODB_FETCH_MODE;\r
+                \r
+                               $schema = false;\r
+                               $this->_findschema($table,$schema);\r
+\r
+                               if ($schema) { // requires pgsql 7.3+ - pg_namespace used.\r
+                                       $sql = '\r
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" \r
+FROM pg_catalog.pg_class c \r
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid \r
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid\r
+       ,pg_namespace n \r
+WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false';\r
+                               } else {\r
+                       $sql = '\r
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"\r
+FROM pg_catalog.pg_class c\r
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid\r
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid\r
+WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')';\r
+                       }\r
+                                           \r
+                if ($primary == FALSE) {\r
+                       $sql .= ' AND i.indisprimary=false;';\r
+                }\r
+                \r
+                $save = $ADODB_FETCH_MODE;\r
+                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+                if ($this->fetchMode !== FALSE) {\r
+                        $savem = $this->SetFetchMode(FALSE);\r
+                }\r
+                \r
+                $rs = $this->Execute(sprintf($sql,$table,$table,$schema));\r
+                if (isset($savem)) {\r
+                        $this->SetFetchMode($savem);\r
+                }\r
+                $ADODB_FETCH_MODE = $save;\r
+\r
+                if (!is_object($rs)) {\r
+                       return FALSE;\r
+                }\r
+                               \r
+                $col_names = $this->MetaColumnNames($table,true);\r
+                $indexes = array();\r
+                while ($row = $rs->FetchRow()) {\r
+                        $columns = array();\r
+                        foreach (explode(' ', $row[2]) as $col) {\r
+                                $columns[] = $col_names[$col - 1];\r
+                        }\r
+                        \r
+                        $indexes[$row[0]] = array(\r
+                                'unique' => ($row[1] == 't'),\r
+                                'columns' => $columns\r
+                        );\r
+                }\r
+                return $indexes;\r
+        }\r
+\r
+       // returns true or false\r
+       //\r
+       // examples:\r
+       //      $db->Connect("host=host1 user=user1 password=secret port=4341");\r
+       //      $db->Connect('host1','user1','secret');\r
+       function _connect($str,$user='',$pwd='',$db='',$ctype=0)\r
+       {\r
+               \r
+               if (!function_exists('pg_pconnect')) return null;\r
+               \r
+               $this->_errorMsg = false;\r
+               \r
+               if ($user || $pwd || $db) {\r
+                       $user = adodb_addslashes($user);\r
+                       $pwd = adodb_addslashes($pwd);\r
+                       if (strlen($db) == 0) $db = 'template1';\r
+                       $db = adodb_addslashes($db);\r
+                       if ($str)  {\r
+                               $host = split(":", $str);\r
+                               if ($host[0]) $str = "host=".adodb_addslashes($host[0]);\r
+                               else $str = 'host=localhost';\r
+                               if (isset($host[1])) $str .= " port=$host[1]";\r
+                       }\r
+                               if ($user) $str .= " user=".$user;\r
+                               if ($pwd)  $str .= " password=".$pwd;\r
+                               if ($db)   $str .= " dbname=".$db;\r
+               }\r
+\r
+               //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";\r
+               \r
+               if ($ctype === 1) { // persistent\r
+                       $this->_connectionID = pg_pconnect($str);\r
+               } else {\r
+                       if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str\r
+                       static $ncnt;\r
+                       \r
+                               if (empty($ncnt)) $ncnt = 1;\r
+                               else $ncnt += 1;\r
+                               \r
+                               $str .= str_repeat(' ',$ncnt);\r
+                       }\r
+                       $this->_connectionID = pg_connect($str);\r
+               }\r
+               if ($this->_connectionID === false) return false;\r
+               $this->Execute("set datestyle='ISO'");\r
+               return true;\r
+       }\r
+       \r
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)\r
+       {\r
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);\r
+       }\r
+        \r
+       // returns true or false\r
+       //\r
+       // examples:\r
+       //      $db->PConnect("host=host1 user=user1 password=secret port=4341");\r
+       //      $db->PConnect('host1','user1','secret');\r
+       function _pconnect($str,$user='',$pwd='',$db='')\r
+       {\r
+               return $this->_connect($str,$user,$pwd,$db,1);\r
+       }\r
+       \r
+\r
+       // returns queryID or false\r
+       function _query($sql,$inputarr)\r
+       {\r
+               \r
+               if ($inputarr) {\r
+               /*\r
+                       It appears that PREPARE/EXECUTE is slower for many queries.\r
+                       \r
+                       For query executed 1000 times:\r
+                       "select id,firstname,lastname from adoxyz \r
+                               where firstname not like ? and lastname not like ? and id = ?"\r
+                               \r
+                       with plan = 1.51861286163 secs\r
+                       no plan =   1.26903700829 secs\r
+\r
+                       \r
+\r
+               */\r
+                       $plan = 'P'.md5($sql);\r
+                               \r
+                       $execp = '';\r
+                       foreach($inputarr as $v) {\r
+                               if ($execp) $execp .= ',';\r
+                               if (is_string($v)) {\r
+                                       if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);\r
+                               } else {\r
+                                       $execp .= $v;\r
+                               }\r
+                       }\r
+                       \r
+                       if ($execp) $exsql = "EXECUTE $plan ($execp)";\r
+                       else $exsql = "EXECUTE $plan";\r
+                       \r
+                       $rez = @pg_exec($this->_connectionID,$exsql);\r
+                       if (!$rez) {\r
+                       # Perhaps plan does not exist? Prepare/compile plan.\r
+                               $params = '';\r
+                               foreach($inputarr as $v) {\r
+                                       if ($params) $params .= ',';\r
+                                       if (is_string($v)) {\r
+                                               $params .= 'VARCHAR';\r
+                                       } else if (is_integer($v)) {\r
+                                               $params .= 'INTEGER';\r
+                                       } else {\r
+                                               $params .= "REAL";\r
+                                       }\r
+                               }\r
+                               $sqlarr = explode('?',$sql);\r
+                               //print_r($sqlarr);\r
+                               $sql = '';\r
+                               $i = 1;\r
+                               foreach($sqlarr as $v) {\r
+                                       $sql .= $v.' $'.$i;\r
+                                       $i++;\r
+                               }\r
+                               $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);               \r
+                               //adodb_pr($s);\r
+                               pg_exec($this->_connectionID,$s);\r
+                               echo $this->ErrorMsg();\r
+                       }\r
+                       \r
+                       $rez = pg_exec($this->_connectionID,$exsql);\r
+               } else {\r
+                       $this->_errorMsg = false;\r
+                       //adodb_backtrace();\r
+                       $rez = pg_exec($this->_connectionID,$sql);\r
+               }\r
+               // check if no data returned, then no need to create real recordset\r
+               if ($rez && pg_numfields($rez) <= 0) {\r
+                       if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {\r
+                               pg_freeresult($this->_resultid);\r
+                       }\r
+                       $this->_resultid = $rez;\r
+                       return true;\r
+               }\r
+               \r
+               return $rez;\r
+       }\r
+       \r
+\r
+       /*      Returns: the last error message from previous database operation        */      \r
+       function ErrorMsg() \r
+       {\r
+               if ($this->_errorMsg !== false) return $this->_errorMsg;\r
+               if (ADODB_PHPVER >= 0x4300) {\r
+                       if (!empty($this->_resultid)) {\r
+                               $this->_errorMsg = @pg_result_error($this->_resultid);\r
+                               if ($this->_errorMsg) return $this->_errorMsg;\r
+                       }\r
+                       \r
+                       if (!empty($this->_connectionID)) {\r
+                               $this->_errorMsg = @pg_last_error($this->_connectionID);\r
+                       } else $this->_errorMsg = @pg_last_error();\r
+               } else {\r
+                       if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();\r
+                       else $this->_errorMsg = @pg_errormessage($this->_connectionID);\r
+               }\r
+               return $this->_errorMsg;\r
+       }\r
+       \r
+       function ErrorNo()\r
+       {\r
+               $e = $this->ErrorMsg();\r
+               if (strlen($e)) {\r
+                       return ADOConnection::MetaError($e);\r
+                }\r
+                return 0;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               if ($this->transCnt) $this->RollbackTrans();\r
+               if ($this->_resultid) {\r
+                       @pg_freeresult($this->_resultid);\r
+                       $this->_resultid = false;\r
+               }\r
+               @pg_close($this->_connectionID);\r
+               $this->_connectionID = false;\r
+               return true;\r
+       }\r
+       \r
+       \r
+       /*\r
+       * Maximum size of C field\r
+       */\r
+       function CharMax()\r
+       {\r
+               return 1000000000;  // should be 1 Gb?\r
+       }\r
+       \r
+       /*\r
+       * Maximum size of X field\r
+       */\r
+       function TextMax()\r
+       {\r
+               return 1000000000; // should be 1 Gb?\r
+       }\r
+       \r
+               \r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_postgres64 extends ADORecordSet{\r
+       var $_blobArr;\r
+       var $databaseType = "postgres64";\r
+       var $canSeek = true;\r
+       function ADORecordSet_postgres64($queryID,$mode=false) \r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch ($mode)\r
+               {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;\r
+               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;\r
+               default:\r
+               case ADODB_FETCH_DEFAULT:\r
+               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;\r
+               }\r
+               $this->ADORecordSet($queryID);\r
+       }\r
+       \r
+       function &GetRowAssoc($upper=true)\r
+       {\r
+               if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;\r
+               $row =& ADORecordSet::GetRowAssoc($upper);\r
+               return $row;\r
+       }\r
+\r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $qid = $this->_queryID;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;\r
+               $this->_numOfFields = @pg_numfields($qid);\r
+               \r
+               // cache types for blob decode check\r
+               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {  \r
+                       if (pg_fieldtype($qid,$i) == 'bytea') {\r
+                               $this->_blobArr[$i] = pg_fieldname($qid,$off);\r
+                       }\r
+               }               \r
+       }\r
+\r
+               /* Use associative array to get fields array */\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];\r
+               \r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+\r
+       function &FetchField($off = 0) \r
+       {\r
+               // offsets begin at 0\r
+               \r
+               $o= new ADOFieldObject();\r
+               $o->name = @pg_fieldname($this->_queryID,$off);\r
+               $o->type = @pg_fieldtype($this->_queryID,$off);\r
+               $o->max_length = @pg_fieldsize($this->_queryID,$off);\r
+               return $o;      \r
+       }\r
+\r
+       function _seek($row)\r
+       {\r
+               return @pg_fetch_row($this->_queryID,$row);\r
+       }\r
+       \r
+       function _decode($blob)\r
+       {\r
+               eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');\r
+               return $realblob;       \r
+       }\r
+       \r
+       function _fixblobs()\r
+       {\r
+               if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {\r
+                       foreach($this->_blobArr as $k => $v) {\r
+                               $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);\r
+                       }\r
+               }\r
+               if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {\r
+                       foreach($this->_blobArr as $k => $v) {\r
+                               $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);\r
+                       }\r
+               }\r
+       }\r
+       \r
+       // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {\r
+                       $this->_currentRow++;\r
+                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {\r
+                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+                               if (is_array($this->fields) && $this->fields) {\r
+                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
+                                       return true;\r
+                               }\r
+                       }\r
+                       $this->fields = false;\r
+                       $this->EOF = true;\r
+               }\r
+               return false;\r
+       }               \r
+       \r
+       function _fetch()\r
+       {\r
+                               \r
+               if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)\r
+               return false;\r
+\r
+               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+               \r
+       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
+                       \r
+               return (is_array($this->fields));\r
+       }\r
+\r
+       function _close() \r
+       { \r
+               return @pg_freeresult($this->_queryID);\r
+       }\r
+\r
+       function MetaType($t,$len=-1,$fieldobj=false)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+                               case 'MONEY': // stupid, postgres expects money to be a string\r
+                               case 'INTERVAL':\r
+                               case 'CHAR':\r
+                               case 'CHARACTER':\r
+                               case 'VARCHAR':\r
+                               case 'NAME':\r
+                               case 'BPCHAR':\r
+                               case '_VARCHAR':\r
+                                       if ($len <= $this->blobSize) return 'C';\r
+                               \r
+                               case 'TEXT':\r
+                                       return 'X';\r
+               \r
+                               case 'IMAGE': // user defined type\r
+                               case 'BLOB': // user defined type\r
+                               case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'\r
+                               case 'VARBIT':\r
+                               case 'BYTEA':\r
+                                       return 'B';\r
+                               \r
+                               case 'BOOL':\r
+                               case 'BOOLEAN':\r
+                                       return 'L';\r
+                               \r
+                               case 'DATE':\r
+                                       return 'D';\r
+                               \r
+                               case 'TIME':\r
+                               case 'DATETIME':\r
+                               case 'TIMESTAMP':\r
+                               case 'TIMESTAMPTZ':\r
+                                       return 'T';\r
+                               \r
+                               case 'SMALLINT': \r
+                               case 'BIGINT': \r
+                               case 'INTEGER': \r
+                               case 'INT8': \r
+                               case 'INT4':\r
+                               case 'INT2':\r
+                                       if (isset($fieldobj) &&\r
+                               empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';\r
+                               \r
+                               case 'OID':\r
+                               case 'SERIAL':\r
+                                       return 'R';\r
+                               \r
+                                default:\r
+                                       return 'N';\r
+                       }\r
+       }\r
+\r
+}\r
+?>\r
index 82ea97acf621a1ffbd1efa2d894aeccace921e3b..0b9b32c26dfdf0415ed7a23d581c3764f04abbc4 100644 (file)
-<?php
-/*
- V4.20 22 Feb 2004  (c) 2000-2004 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.
-  
-  Postgres7 support.
-  28 Feb 2001: Currently indicate that we support LIMIT
-  01 Dec 2001: dannym added support for default values
-*/
-
-include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
-
-class ADODB_postgres7 extends ADODB_postgres64 {
-       var $databaseType = 'postgres7';        
-       var $hasLimit = true;   // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
-       var $ansiOuter = true;
-       var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings
-       
-       function ADODB_postgres7() 
-       {
-               $this->ADODB_postgres64();
-       }
-
-       
-       // the following should be compat with postgresql 7.2, 
-       // which makes obsolete the LIMIT limit,offset syntax
-        function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
-        {
-                $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
-                $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';
-                if ($secs2cache)
-                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
-                else
-                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
-               
-               return $rs;
-        }
-       /*
-       function Prepare($sql)
-       {
-               $info = $this->ServerInfo();
-               if ($info['version']>=7.3) {
-                       return array($sql,false);
-               }
-               return $sql;
-       }
-       */
-
-       // from  Edward Jaramilla, improved version - works on pg 7.4
-function MetaForeignKeys($table, $owner=false, $upper=false)
-{
-       $sql = 'SELECT t.tgargs as args
-       FROM
-       pg_trigger t,pg_class c,pg_proc p
-       WHERE
-       t.tgenabled AND
-       t.tgrelid = c.oid AND
-       t.tgfoid = p.oid AND
-       p.proname = \'RI_FKey_check_ins\' AND
-       c.relname = \''.strtolower($table).'\'
-       ORDER BY
-               t.tgrelid';
-       
-       $rs = $this->Execute($sql);
-       
-       if ($rs && !$rs->EOF) {
-               $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];
-                       }
-               }
-               return $a;
-       }
-       return false;
-}
-
-
-
-    function xMetaForeignKeys($table, $owner=false, $upper=false)
-       {
-
-        $sql = '
-SELECT t.tgargs as args
-   FROM pg_trigger t,
-        pg_class c,
-        pg_class c2,
-        pg_proc f
-   WHERE t.tgenabled
-   AND t.tgrelid=c.oid
-   AND t.tgconstrrelid=c2.oid
-   AND t.tgfoid=f.oid
-   AND f.proname ~ \'^RI_FKey_check_ins\'
-   AND t.tgargs like \'$1\\\000'.strtolower($table).'%\'
-   ORDER BY t.tgrelid';
-
-        $rs = $this->Execute($sql);
-               if ($rs && !$rs->EOF) {
-                       $arr =& $rs->GetArray();
-                       $a = array();
-                       foreach($arr as $v) {
-                $data = explode(chr(0), $v['args']);
-                if ($upper) {
-                    $a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5]));
-                } else {
-                    $a[] = array($data[2] => $data[4].'='.$data[5]);
-                }
-                
-                       }
-                       return $a;
-               }
-               else return false;
-    }
-       
-        // this is a set of functions for managing client encoding - very important if the encodings
-       // of your database and your output target (i.e. HTML) don't match
-       //for instance, you may have UNICODE database and server it on-site as WIN1251 etc.
-       // GetCharSet - get the name of the character set the client is using now
-       // the functions should work with Postgres 7.0 and above, the set of charsets supported
-       // depends on compile flags of postgres distribution - if no charsets were compiled into the server
-       // it will return 'SQL_ANSI' always
-       function GetCharSet()
-       {
-               //we will use ADO's builtin property charSet
-               $this->charSet = @pg_client_encoding($this->_connectionID);
-               if (!$this->charSet) {
-                       return false;
-               } else {
-                       return $this->charSet;
-               }
-       }
-       
-       // SetCharSet - switch the client encoding
-       function SetCharSet($charset_name)
-       {
-               $this->GetCharSet();
-               if ($this->charSet !== $charset_name) {
-                       $if = pg_set_client_encoding($this->_connectionID, $charset_name);
-                       if ($if == "0" & $this->GetCharSet() == $charset_name) {
-                               return true;
-                       } else return false;
-               } else return true;
-       }
-
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
-
-       var $databaseType = "postgres7";
-       
-       
-       function ADORecordSet_postgres7($queryID,$mode=false) 
-       {
-               $this->ADORecordSet_postgres64($queryID,$mode);
-       }
-       
-               // 10% speedup to move MoveNext to child class
-       function MoveNext() 
-       {
-               if (!$this->EOF) {
-                       $this->_currentRow++;
-                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
-                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
-                       
-                               if (is_array($this->fields)) {
-                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
-                                       return true;
-                               }
-                       }
-                       $this->fields = false;
-                       $this->EOF = true;
-               }
-               return false;
-       }               
-
-}
+<?php\r
+/*\r
+ V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Postgres7 support.\r
+  28 Feb 2001: Currently indicate that we support LIMIT\r
+  01 Dec 2001: dannym added support for default values\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");\r
+\r
+class ADODB_postgres7 extends ADODB_postgres64 {\r
+       var $databaseType = 'postgres7';        \r
+       var $hasLimit = true;   // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
+       var $ansiOuter = true;\r
+       var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings\r
+       \r
+       function ADODB_postgres7() \r
+       {\r
+               $this->ADODB_postgres64();\r
+       }\r
+\r
+       \r
+       // the following should be compat with postgresql 7.2, \r
+       // which makes obsolete the LIMIT limit,offset syntax\r
+        function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
+        {\r
+                $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';\r
+                $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';\r
+                if ($secs2cache)\r
+                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);\r
+                else\r
+                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);\r
+               \r
+               return $rs;\r
+        }\r
+       /*\r
+       function Prepare($sql)\r
+       {\r
+               $info = $this->ServerInfo();\r
+               if ($info['version']>=7.3) {\r
+                       return array($sql,false);\r
+               }\r
+               return $sql;\r
+       }\r
+       */\r
+\r
+       // from  Edward Jaramilla, improved version - works on pg 7.4\r
+function MetaForeignKeys($table, $owner=false, $upper=false)\r
+{\r
+       $sql = 'SELECT t.tgargs as args\r
+       FROM\r
+       pg_trigger t,pg_class c,pg_proc p\r
+       WHERE\r
+       t.tgenabled AND\r
+       t.tgrelid = c.oid AND\r
+       t.tgfoid = p.oid AND\r
+       p.proname = \'RI_FKey_check_ins\' AND\r
+       c.relname = \''.strtolower($table).'\'\r
+       ORDER BY\r
+               t.tgrelid';\r
+       \r
+       $rs = $this->Execute($sql);\r
+       \r
+       if ($rs && !$rs->EOF) {\r
+               $arr =& $rs->GetArray();\r
+               $a = array();\r
+               foreach($arr as $v)\r
+               {\r
+                       $data = explode(chr(0), $v['args']);\r
+                       if ($upper) {\r
+                               $a[strtoupper($data[2])][] = strtoupper($data[4].'='.$data[5]);\r
+                       } else {\r
+                       $a[$data[2]][] = $data[4].'='.$data[5];\r
+                       }\r
+               }\r
+               return $a;\r
+       }\r
+       return false;\r
+}\r
+\r
+\r
+\r
+    function xMetaForeignKeys($table, $owner=false, $upper=false)\r
+       {\r
+\r
+        $sql = '\r
+SELECT t.tgargs as args\r
+   FROM pg_trigger t,\r
+        pg_class c,\r
+        pg_class c2,\r
+        pg_proc f\r
+   WHERE t.tgenabled\r
+   AND t.tgrelid=c.oid\r
+   AND t.tgconstrrelid=c2.oid\r
+   AND t.tgfoid=f.oid\r
+   AND f.proname ~ \'^RI_FKey_check_ins\'\r
+   AND t.tgargs like \'$1\\\000'.strtolower($table).'%\'\r
+   ORDER BY t.tgrelid';\r
+\r
+        $rs = $this->Execute($sql);\r
+               if ($rs && !$rs->EOF) {\r
+                       $arr =& $rs->GetArray();\r
+                       $a = array();\r
+                       foreach($arr as $v) {\r
+                $data = explode(chr(0), $v['args']);\r
+                if ($upper) {\r
+                    $a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5]));\r
+                } else {\r
+                    $a[] = array($data[2] => $data[4].'='.$data[5]);\r
+                }\r
+                \r
+                       }\r
+                       return $a;\r
+               }\r
+               else return false;\r
+    }\r
+       \r
+        // this is a set of functions for managing client encoding - very important if the encodings\r
+       // of your database and your output target (i.e. HTML) don't match\r
+       //for instance, you may have UNICODE database and server it on-site as WIN1251 etc.\r
+       // GetCharSet - get the name of the character set the client is using now\r
+       // the functions should work with Postgres 7.0 and above, the set of charsets supported\r
+       // depends on compile flags of postgres distribution - if no charsets were compiled into the server\r
+       // it will return 'SQL_ANSI' always\r
+       function GetCharSet()\r
+       {\r
+               //we will use ADO's builtin property charSet\r
+               $this->charSet = @pg_client_encoding($this->_connectionID);\r
+               if (!$this->charSet) {\r
+                       return false;\r
+               } else {\r
+                       return $this->charSet;\r
+               }\r
+       }\r
+       \r
+       // SetCharSet - switch the client encoding\r
+       function SetCharSet($charset_name)\r
+       {\r
+               $this->GetCharSet();\r
+               if ($this->charSet !== $charset_name) {\r
+                       $if = pg_set_client_encoding($this->_connectionID, $charset_name);\r
+                       if ($if == "0" & $this->GetCharSet() == $charset_name) {\r
+                               return true;\r
+                       } else return false;\r
+               } else return true;\r
+       }\r
+\r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordSet_postgres7 extends ADORecordSet_postgres64{\r
+\r
+       var $databaseType = "postgres7";\r
+       \r
+       \r
+       function ADORecordSet_postgres7($queryID,$mode=false) \r
+       {\r
+               $this->ADORecordSet_postgres64($queryID,$mode);\r
+       }\r
+       \r
+               // 10% speedup to move MoveNext to child class\r
+       function MoveNext() \r
+       {\r
+               if (!$this->EOF) {\r
+                       $this->_currentRow++;\r
+                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {\r
+                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
+                       \r
+                               if (is_array($this->fields)) {\r
+                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
+                                       return true;\r
+                               }\r
+                       }\r
+                       $this->fields = false;\r
+                       $this->EOF = true;\r
+               }\r
+               return false;\r
+       }               \r
+\r
+}\r
 ?>
\ No newline at end of file
index 44f448e8c5ceebc6c51d4236389625ad4f38df82..9c5527698adddda8f5efd1269ed67c14ec3691b5 100644 (file)
@@ -1,30 +1,33 @@
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-  
-  Synonym for csv driver.
-*/ 
-
-if (! defined("_ADODB_PROXY_LAYER")) {
-        define("_ADODB_PROXY_LAYER", 1 );
-        include(ADODB_DIR."/drivers/adodb-csv.inc.php");
-        
-       class ADODB_proxy extends ADODB_csv {
-               var $databaseType = 'proxy';
-               var $databaseProvider = 'csv';
-       }
-       class ADORecordset_proxy extends ADORecordset_csv {
-       var $databaseType = "proxy";            
-       
-               function ADORecordset_proxy($id,$mode=false) 
-               {
-                       $this->ADORecordset($id,$mode);
-               }
-       };
-} // define
-       
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 4.\r
+  \r
+  Synonym for csv driver.\r
+*/ \r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (! defined("_ADODB_PROXY_LAYER")) {\r
+        define("_ADODB_PROXY_LAYER", 1 );\r
+        include(ADODB_DIR."/drivers/adodb-csv.inc.php");\r
+        \r
+       class ADODB_proxy extends ADODB_csv {\r
+               var $databaseType = 'proxy';\r
+               var $databaseProvider = 'csv';\r
+       }\r
+       class ADORecordset_proxy extends ADORecordset_csv {\r
+       var $databaseType = "proxy";            \r
+       \r
+               function ADORecordset_proxy($id,$mode=false) \r
+               {\r
+                       $this->ADORecordset($id,$mode);\r
+               }\r
+       };\r
+} // define\r
+       \r
 ?>
\ No newline at end of file
index 320671e836e24ea707fa5bf34021b166367fa839..6fac46030f42b81dc406f39a9d3f891845e55b6f 100644 (file)
@@ -1,63 +1,66 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  SAPDB data driver. Requires ODBC.
-
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-if (!defined('ADODB_SAPDB')){
-define('ADODB_SAPDB',1);
-
-class ADODB_SAPDB extends ADODB_odbc {
-       var $databaseType = "sapdb";    
-       var $concat_operator = '||';
-       var $sysDate = 'DATE';
-       var $sysTimeStamp = 'TIMESTAMP';
-       var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database
-       var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt.
-       
-       function ADODB_SAPDB()
-       {
-               //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
-               $this->ADODB_odbc();
-       }
-       
-       /*
-               SelectLimit implementation problems:
-       
-               The following will return random 10 rows as order by performed after "WHERE rowno<10"
-               which is not ideal...
-               
-                       select * from table where rowno < 10 order by 1
-         
-               This means that we have to use the adoconnection base class SelectLimit when
-               there is an "order by".
-               
-               See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html
-        */
-       
-};
-
-class  ADORecordSet_sapdb extends ADORecordSet_odbc {  
-       
-       var $databaseType = "sapdb";            
-       
-       function ADORecordSet_sapdb($id,$mode=false)
-       {
-               $this->ADORecordSet_odbc($id,$mode);
-       }
-}
-
-} //define
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  SAPDB data driver. Requires ODBC.\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+if (!defined('ADODB_SAPDB')){\r
+define('ADODB_SAPDB',1);\r
+\r
+class ADODB_SAPDB extends ADODB_odbc {\r
+       var $databaseType = "sapdb";    \r
+       var $concat_operator = '||';\r
+       var $sysDate = 'DATE';\r
+       var $sysTimeStamp = 'TIMESTAMP';\r
+       var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database\r
+       var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt.\r
+       \r
+       function ADODB_SAPDB()\r
+       {\r
+               //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;\r
+               $this->ADODB_odbc();\r
+       }\r
+       \r
+       /*\r
+               SelectLimit implementation problems:\r
+       \r
+               The following will return random 10 rows as order by performed after "WHERE rowno<10"\r
+               which is not ideal...\r
+               \r
+                       select * from table where rowno < 10 order by 1\r
+         \r
+               This means that we have to use the adoconnection base class SelectLimit when\r
+               there is an "order by".\r
+               \r
+               See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html\r
+        */\r
+       \r
+};\r
\r
+\r
+class  ADORecordSet_sapdb extends ADORecordSet_odbc {  \r
+       \r
+       var $databaseType = "sapdb";            \r
+       \r
+       function ADORecordSet_sapdb($id,$mode=false)\r
+       {\r
+               $this->ADORecordSet_odbc($id,$mode);\r
+       }\r
+}\r
+\r
+} //define\r
 ?>
\ No newline at end of file
index 0008f187361b3072d010f52add88f69801d99911..e6a24e0829ab7bd573cf816d3c37f2f49a2ece25 100644 (file)
-<?php
-/* 
-version V4.20 22 Feb 2004 (c) 2000-2004  John Lim (jlim@natsoft.com.my). All rights
-reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-
-  Latest version is available at http://php.weblogs.com/
-
-  21.02.2002 - Wade Johnson wade@wadejohnson.de
-                          Extended ODBC class for Sybase SQLAnywhere.
-   1) Added support to retrieve the last row insert ID on tables with
-         primary key column using autoincrement function.
-
-   2) Added blob support.  Usage:
-                a) create blob variable on db server:
-
-               $dbconn->create_blobvar($blobVarName);
-
-         b) load blob var from file.  $filename must be complete path
-
-         $dbcon->load_blobvar_from_file($blobVarName, $filename);
-
-         c) Use the $blobVarName in SQL insert or update statement in the values
-         clause:
-
-               $recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '
-               .
-          'VALUES (\'test\', ' . $blobVarName . ')');
-
-        instead of loading blob from a file, you can also load from 
-         an unformatted (raw) blob variable:
-         $dbcon->load_blobvar_from_var($blobVarName, $varName);
-
-         d) drop blob variable on db server to free up resources:
-         $dbconn->drop_blobvar($blobVarName);
-
-  Sybase_SQLAnywhere data driver. Requires ODBC.
-
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
- include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-
-if (!defined('ADODB_SYBASE_SQLANYWHERE')){
-
- define('ADODB_SYBASE_SQLANYWHERE',1);
-
- class ADODB_sqlanywhere extends ADODB_odbc {
-       var $databaseType = "sqlanywhere";      
-       var $hasInsertID = true;
-       
-       function ADODB_sqlanywhere()
-       {
-               $this->ADODB_odbc();
-       }
-
-        function _insertid() {
-          return $this->GetOne('select @@identity');
-        }
-
-  function create_blobvar($blobVarName) {
-   $this->Execute("create variable $blobVarName long binary");
-   return;
-  }
-
-  function drop_blobvar($blobVarName) {
-   $this->Execute("drop variable $blobVarName");
-   return;
-  }
-
-  function load_blobvar_from_file($blobVarName, $filename) {
-   $chunk_size = 1000;
-
-   $fd = fopen ($filename, "rb");
-
-   $integer_chunks = (integer)filesize($filename) / $chunk_size;
-   $modulus = filesize($filename) % $chunk_size;
-   if ($modulus != 0){
-       $integer_chunks += 1;
-   }
-
-   for($loop=1;$loop<=$integer_chunks;$loop++){
-       $contents = fread ($fd, $chunk_size);
-       $contents = bin2hex($contents);
-
-       $hexstring = '';
-
-       for($loop2=0;$loop2<strlen($contents);$loop2+=2){
-        $hexstring .= '\x' . substr($contents,$loop2,2);
-        }
-
-       $hexstring = $this->qstr($hexstring);
-
-       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
-   }
-
-   fclose ($fd);
-   return;
-  }
-
-  function load_blobvar_from_var($blobVarName, &$varName) {
-   $chunk_size = 1000;
-
-   $integer_chunks = (integer)strlen($varName) / $chunk_size;
-   $modulus = strlen($varName) % $chunk_size;
-   if ($modulus != 0){
-       $integer_chunks += 1;
-   }
-
-   for($loop=1;$loop<=$integer_chunks;$loop++){
-       $contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);
-       $contents = bin2hex($contents);
-
-       $hexstring = '';
-
-       for($loop2=0;$loop2<strlen($contents);$loop2+=2){
-        $hexstring .= '\x' . substr($contents,$loop2,2);
-        }
-
-       $hexstring = $this->qstr($hexstring);
-
-       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
-   }
-
-   return;
-  }
-
- /*
-  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')
-  {
-   $blobVarName = 'hold_blob';
-   $this->create_blobvar($blobVarName);
-   $this->load_blobvar_from_var($blobVarName, $val);
-   $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");
-   $this->drop_blobvar($blobVarName);
-   return true;
-  }
- }; //class
-
- class  ADORecordSet_sqlanywhere extends ADORecordSet_odbc {   
-
-  var $databaseType = "sqlanywhere";           
-
- function ADORecordSet_sqlanywhere($id,$mode=false)
- {
-  $this->ADORecordSet_odbc($id,$mode);
- }
-
-
- }; //class
-
-
-} //define
-?>
+<?php\r
+/* \r
+version V4.50 6 July 2004 (c) 2000-2004  John Lim (jlim@natsoft.com.my). All rights\r
+reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+\r
+  21.02.2002 - Wade Johnson wade@wadejohnson.de\r
+                          Extended ODBC class for Sybase SQLAnywhere.\r
+   1) Added support to retrieve the last row insert ID on tables with\r
+         primary key column using autoincrement function.\r
+\r
+   2) Added blob support.  Usage:\r
+                a) create blob variable on db server:\r
+\r
+               $dbconn->create_blobvar($blobVarName);\r
+\r
+         b) load blob var from file.  $filename must be complete path\r
+\r
+         $dbcon->load_blobvar_from_file($blobVarName, $filename);\r
+\r
+         c) Use the $blobVarName in SQL insert or update statement in the values\r
+         clause:\r
+\r
+               $recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '\r
+               .\r
+          'VALUES (\'test\', ' . $blobVarName . ')');\r
+\r
+        instead of loading blob from a file, you can also load from \r
+         an unformatted (raw) blob variable:\r
+         $dbcon->load_blobvar_from_var($blobVarName, $varName);\r
+\r
+         d) drop blob variable on db server to free up resources:\r
+         $dbconn->drop_blobvar($blobVarName);\r
+\r
+  Sybase_SQLAnywhere data driver. Requires ODBC.\r
+\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+ include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+\r
+if (!defined('ADODB_SYBASE_SQLANYWHERE')){\r
+\r
+ define('ADODB_SYBASE_SQLANYWHERE',1);\r
+\r
+ class ADODB_sqlanywhere extends ADODB_odbc {\r
+       var $databaseType = "sqlanywhere";      \r
+       var $hasInsertID = true;\r
+       \r
+       function ADODB_sqlanywhere()\r
+       {\r
+               $this->ADODB_odbc();\r
+       }\r
+\r
+        function _insertid() {\r
+          return $this->GetOne('select @@identity');\r
+        }\r
+\r
+  function create_blobvar($blobVarName) {\r
+   $this->Execute("create variable $blobVarName long binary");\r
+   return;\r
+  }\r
+\r
+  function drop_blobvar($blobVarName) {\r
+   $this->Execute("drop variable $blobVarName");\r
+   return;\r
+  }\r
+\r
+  function load_blobvar_from_file($blobVarName, $filename) {\r
+   $chunk_size = 1000;\r
+\r
+   $fd = fopen ($filename, "rb");\r
+\r
+   $integer_chunks = (integer)filesize($filename) / $chunk_size;\r
+   $modulus = filesize($filename) % $chunk_size;\r
+   if ($modulus != 0){\r
+       $integer_chunks += 1;\r
+   }\r
+\r
+   for($loop=1;$loop<=$integer_chunks;$loop++){\r
+       $contents = fread ($fd, $chunk_size);\r
+       $contents = bin2hex($contents);\r
+\r
+       $hexstring = '';\r
+\r
+       for($loop2=0;$loop2<strlen($contents);$loop2+=2){\r
+        $hexstring .= '\x' . substr($contents,$loop2,2);\r
+        }\r
+\r
+       $hexstring = $this->qstr($hexstring);\r
+\r
+       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);\r
+   }\r
+\r
+   fclose ($fd);\r
+   return;\r
+  }\r
+\r
+  function load_blobvar_from_var($blobVarName, &$varName) {\r
+   $chunk_size = 1000;\r
+\r
+   $integer_chunks = (integer)strlen($varName) / $chunk_size;\r
+   $modulus = strlen($varName) % $chunk_size;\r
+   if ($modulus != 0){\r
+       $integer_chunks += 1;\r
+   }\r
+\r
+   for($loop=1;$loop<=$integer_chunks;$loop++){\r
+       $contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);\r
+       $contents = bin2hex($contents);\r
+\r
+       $hexstring = '';\r
+\r
+       for($loop2=0;$loop2<strlen($contents);$loop2+=2){\r
+        $hexstring .= '\x' . substr($contents,$loop2,2);\r
+        }\r
+\r
+       $hexstring = $this->qstr($hexstring);\r
+\r
+       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);\r
+   }\r
+\r
+   return;\r
+  }\r
+\r
+ /*\r
+  Insert a null into the blob field of the table first.\r
+  Then use UpdateBlob to store the blob.\r
+\r
+  Usage:\r
+\r
+  $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
+  $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
+ */\r
+  function UpdateBlob($table,$column,&$val,$where,$blobtype='BLOB')\r
+  {\r
+   $blobVarName = 'hold_blob';\r
+   $this->create_blobvar($blobVarName);\r
+   $this->load_blobvar_from_var($blobVarName, $val);\r
+   $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");\r
+   $this->drop_blobvar($blobVarName);\r
+   return true;\r
+  }\r
+ }; //class\r
+\r
+ class  ADORecordSet_sqlanywhere extends ADORecordSet_odbc {   \r
+\r
+  var $databaseType = "sqlanywhere";           \r
+\r
+ function ADORecordSet_sqlanywhere($id,$mode=false)\r
+ {\r
+  $this->ADORecordSet_odbc($id,$mode);\r
+ }\r
+\r
+\r
+ }; //class\r
+\r
+\r
+} //define\r
+?>\r
index 447f664da4d8f061e3b8c1db756f03363d28690a..83f7b20ff0178d1d1ac10043c544031a3676fee3 100644 (file)
-<?php
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-  Latest version is available at http://php.weblogs.com/
-  
-  SQLite info: http://www.hwaci.com/sw/sqlite/
-    
-  Install Instructions:
-  ====================
-  1. Place this in adodb/drivers
-  2. Rename the file, remove the .txt prefix.
-*/
-
-class ADODB_sqlite extends ADOConnection {
-       var $databaseType = "sqlite";
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $concat_operator='||';
-       var $_errorNo = 0;
-       var $hasLimit = true;   
-       var $hasInsertID = true;                /// supports autoincrement ID?
-       var $hasAffectedRows = true;    /// supports affected rows for update/delete?
-       var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
-       var $sysDate = "adodb_date('Y-m-d')";
-       var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       
-       function ADODB_sqlite() 
-       {
-       }
-       
-/*
-  function __get($name) 
-  {
-       switch($name) {
-       case 'sysDate': return "'".date($this->fmtDate)."'";
-       case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'";
-       }
-  }*/
-       
-       function ServerInfo()
-       {
-               $arr['version'] = sqlite_libversion();
-               $arr['description'] = 'SQLite ';
-               $arr['encoding'] = sqlite_libencoding();
-               return $arr;
-       }
-       
-       function BeginTrans()
-       {         
-                if ($this->transOff) return true; 
-                $ret = $this->Execute("BEGIN TRANSACTION");
-                $this->transCnt += 1;
-                return true;
-       }
-       
-       function CommitTrans($ok=true) 
-       { 
-               if ($this->transOff) return true; 
-               if (!$ok) return $this->RollbackTrans();
-               $ret = $this->Execute("COMMIT");
-               if ($this->transCnt>0)$this->transCnt -= 1;
-               return !empty($ret);
-       }
-       
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true; 
-               $ret = $this->Execute("ROLLBACK");
-               if ($this->transCnt>0)$this->transCnt -= 1;
-               return !empty($ret);
-       }
-
-       function _insertid()
-       {
-               return sqlite_last_insert_rowid($this->_connectionID);
-       }
-       
-       function _affectedrows()
-       {
-        return sqlite_changes($this->_connectionID);
-    }
-       
-       function ErrorMsg() 
-       {
-               if ($this->_logsql) return $this->_errorMsg;
-               return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';
-       }
-       function ErrorNo() 
-       {
-               return $this->_errorNo;
-       }
-       
-       function SQLDate($fmt, $col=false)
-       {
-               $fmt = $this->qstr($fmt);
-               return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";
-       }
-       
-       function &MetaColumns($tab)
-       {
-       global $ADODB_FETCH_MODE;
-       
-               $rs = $this->Execute("select * from $tab limit 1");
-               if (!$rs) return false;
-               $arr = array();
-               for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) {
-                       $fld =& $rs->FetchField($i);
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] =& $fld;    
-                       else $arr[strtoupper($fld->name)] =& $fld;
-               }
-               $rs->Close();
-               return $arr;
-       }
-       
-       function _createFunctions()
-       {
-               @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);
-               @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);
-       }
-       
-
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('sqlite_open')) return false;
-               
-               $this->_connectionID = sqlite_open($argHostname);
-               if ($this->_connectionID === false) return false;
-               $this->_createFunctions();
-               return true;
-       }
-       
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('sqlite_open')) return false;
-               
-               $this->_connectionID = sqlite_popen($argHostname);
-               if ($this->_connectionID === false) return false;
-               $this->_createFunctions();
-               return true;
-       }
-
-       // returns query ID if successful, otherwise false
-       function _query($sql,$inputarr=false)
-       {
-               $rez = sqlite_query($sql,$this->_connectionID);
-               if (!$rez) {
-                       $this->_errorNo = sqlite_last_error($this->_connectionID);
-               }
-               
-               return $rez;
-       }
-       
-       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);
-               else
-                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
-                       
-               return $rs;
-       }
-       
-       /*
-               This algorithm is not very efficient, but works even if table locking
-               is not available.
-               
-               Will return false if unable to generate an ID after $MAXLOOPS attempts.
-       */
-       var $_genSeqSQL = "create table %s (id integer)";
-       
-       function GenID($seq='adodbseq',$start=1)
-       {       
-               // if you have to modify the parameter below, your database is overloaded,
-               // or you need to implement generation of id's yourself!
-               $MAXLOOPS = 100;
-               //$this->debug=1;
-               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;
-                               return $num;
-                       }
-               }
-               if ($fn = $this->raiseErrorFn) {
-                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
-               }
-               return false;
-       }
-
-       function CreateSequence($seqname='adodbseq',$start=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
-               if (!$ok) return false;
-               $start -= 1;
-               return $this->Execute("insert into $seqname values($start)");
-       }
-       
-       var $_dropSeqSQL = 'drop table %s';
-       function DropSequence($seqname)
-       {
-               if (empty($this->_dropSeqSQL)) return false;
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
-       }
-       
-       // returns true or false
-       function _close()
-       {
-               return @sqlite_close($this->_connectionID);
-       }
-
-
-}
-
-/*--------------------------------------------------------------------------------------
-                Class Name: Recordset
---------------------------------------------------------------------------------------*/
-
-class ADORecordset_sqlite extends ADORecordSet {
-
-       var $databaseType = "sqlite";
-       var $bind = false;
-
-       function ADORecordset_sqlite($queryID,$mode=false)
-       {
-               
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               switch($mode) {
-               case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break;
-               case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;
-               default: $this->fetchMode = SQLITE_BOTH; break;
-               }
-               
-               $this->_queryID = $queryID;
-       
-               $this->_inited = true;
-               $this->fields = array();
-               if ($queryID) {
-                       $this->_currentRow = 0;
-                       $this->EOF = !$this->_fetch();
-                       @$this->_initrs();
-               } else {
-                       $this->_numOfRows = 0;
-                       $this->_numOfFields = 0;
-                       $this->EOF = true;
-               }
-               
-               return $this->_queryID;
-       }
-
-
-       function &FetchField($fieldOffset = -1)
-       {
-               $fld = new ADOFieldObject;
-               $fld->name = sqlite_field_name($this->_queryID, $fieldOffset);
-               $fld->type = 'VARCHAR';
-               $fld->max_length = -1;
-               return $fld;
-       }
-       
-   function _initrs()
-   {
-               $this->_numOfRows = @sqlite_num_rows($this->_queryID);
-               $this->_numOfFields = @sqlite_num_fields($this->_queryID);
-   }
-
-       function Fields($colname)
-       {
-               if ($this->fetchMode != SQLITE_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)]];
-       }
-       
-   function _seek($row)
-   {
-               return sqlite_seek($this->_queryID, $row);
-   }
-
-       function _fetch($ignore_fields=false) 
-       {
-               $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
-               return !empty($this->fields);
-       }
-       
-       function _close() 
-       {
-       }
-
-}
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+\r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  SQLite info: http://www.hwaci.com/sw/sqlite/\r
+    \r
+  Install Instructions:\r
+  ====================\r
+  1. Place this in adodb/drivers\r
+  2. Rename the file, remove the .txt prefix.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB_sqlite extends ADOConnection {\r
+       var $databaseType = "sqlite";\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $concat_operator='||';\r
+       var $_errorNo = 0;\r
+       var $hasLimit = true;   \r
+       var $hasInsertID = true;                /// supports autoincrement ID?\r
+       var $hasAffectedRows = true;    /// supports affected rows for update/delete?\r
+       var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";\r
+       var $sysDate = "adodb_date('Y-m-d')";\r
+       var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       \r
+       function ADODB_sqlite() \r
+       {\r
+       }\r
+       \r
+/*\r
+  function __get($name) \r
+  {\r
+       switch($name) {\r
+       case 'sysDate': return "'".date($this->fmtDate)."'";\r
+       case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'";\r
+       }\r
+  }*/\r
+       \r
+       function ServerInfo()\r
+       {\r
+               $arr['version'] = sqlite_libversion();\r
+               $arr['description'] = 'SQLite ';\r
+               $arr['encoding'] = sqlite_libencoding();\r
+               return $arr;\r
+       }\r
+       \r
+       function BeginTrans()\r
+       {         \r
+                if ($this->transOff) return true; \r
+                $ret = $this->Execute("BEGIN TRANSACTION");\r
+                $this->transCnt += 1;\r
+                return true;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true; \r
+               if (!$ok) return $this->RollbackTrans();\r
+               $ret = $this->Execute("COMMIT");\r
+               if ($this->transCnt>0)$this->transCnt -= 1;\r
+               return !empty($ret);\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true; \r
+               $ret = $this->Execute("ROLLBACK");\r
+               if ($this->transCnt>0)$this->transCnt -= 1;\r
+               return !empty($ret);\r
+       }\r
+\r
+       function _insertid()\r
+       {\r
+               return sqlite_last_insert_rowid($this->_connectionID);\r
+       }\r
+       \r
+       function _affectedrows()\r
+       {\r
+        return sqlite_changes($this->_connectionID);\r
+    }\r
+       \r
+       function ErrorMsg() \r
+       {\r
+               if ($this->_logsql) return $this->_errorMsg;\r
+               return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';\r
+       }\r
\r
+       function ErrorNo() \r
+       {\r
+               return $this->_errorNo;\r
+       }\r
+       \r
+       function SQLDate($fmt, $col=false)\r
+       {\r
+               $fmt = $this->qstr($fmt);\r
+               return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";\r
+       }\r
+       \r
+       function &MetaColumns($tab)\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $rs = $this->Execute("select * from $tab limit 1");\r
+               if (!$rs) return false;\r
+               $arr = array();\r
+               for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) {\r
+                       $fld =& $rs->FetchField($i);\r
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] =& $fld;    \r
+                       else $arr[strtoupper($fld->name)] =& $fld;\r
+               }\r
+               $rs->Close();\r
+               return $arr;\r
+       }\r
+       \r
+       function _createFunctions()\r
+       {\r
+               @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);\r
+               @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);\r
+       }\r
+       \r
+\r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('sqlite_open')) return null;\r
+               \r
+               $this->_connectionID = sqlite_open($argHostname);\r
+               if ($this->_connectionID === false) return false;\r
+               $this->_createFunctions();\r
+               return true;\r
+       }\r
+       \r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('sqlite_open')) return null;\r
+               \r
+               $this->_connectionID = sqlite_popen($argHostname);\r
+               if ($this->_connectionID === false) return false;\r
+               $this->_createFunctions();\r
+               return true;\r
+       }\r
+\r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr=false)\r
+       {\r
+               $rez = sqlite_query($sql,$this->_connectionID);\r
+               if (!$rez) {\r
+                       $this->_errorNo = sqlite_last_error($this->_connectionID);\r
+               }\r
+               \r
+               return $rez;\r
+       }\r
+       \r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
+       {\r
+               $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';\r
+               $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');\r
+               if ($secs2cache)\r
+                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);\r
+               else\r
+                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);\r
+                       \r
+               return $rs;\r
+       }\r
+       \r
+       /*\r
+               This algorithm is not very efficient, but works even if table locking\r
+               is not available.\r
+               \r
+               Will return false if unable to generate an ID after $MAXLOOPS attempts.\r
+       */\r
+       var $_genSeqSQL = "create table %s (id integer)";\r
+       \r
+       function GenID($seq='adodbseq',$start=1)\r
+       {       \r
+               // if you have to modify the parameter below, your database is overloaded,\r
+               // or you need to implement generation of id's yourself!\r
+               $MAXLOOPS = 100;\r
+               //$this->debug=1;\r
+               while (--$MAXLOOPS>=0) {\r
+                       $num = $this->GetOne("select id from $seq");\r
+                       if ($num === false) {\r
+                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       \r
+                               $start -= 1;\r
+                               $num = '0';\r
+                               $ok = $this->Execute("insert into $seq values($start)");\r
+                               if (!$ok) return false;\r
+                       } \r
+                       $this->Execute("update $seq set id=id+1 where id=$num");\r
+                       \r
+                       if ($this->affected_rows() > 0) {\r
+                               $num += 1;\r
+                               $this->genID = $num;\r
+                               return $num;\r
+                       }\r
+               }\r
+               if ($fn = $this->raiseErrorFn) {\r
+                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);\r
+               }\r
+               return false;\r
+       }\r
+\r
+       function CreateSequence($seqname='adodbseq',$start=1)\r
+       {\r
+               if (empty($this->_genSeqSQL)) return false;\r
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
+               if (!$ok) return false;\r
+               $start -= 1;\r
+               return $this->Execute("insert into $seqname values($start)");\r
+       }\r
+       \r
+       var $_dropSeqSQL = 'drop table %s';\r
+       function DropSequence($seqname)\r
+       {\r
+               if (empty($this->_dropSeqSQL)) return false;\r
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
+       }\r
+       \r
+       // returns true or false\r
+       function _close()\r
+       {\r
+               return @sqlite_close($this->_connectionID);\r
+       }\r
+\r
+\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+                Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_sqlite extends ADORecordSet {\r
+\r
+       var $databaseType = "sqlite";\r
+       var $bind = false;\r
+\r
+       function ADORecordset_sqlite($queryID,$mode=false)\r
+       {\r
+               \r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               switch($mode) {\r
+               case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break;\r
+               case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;\r
+               default: $this->fetchMode = SQLITE_BOTH; break;\r
+               }\r
+               \r
+               $this->_queryID = $queryID;\r
+       \r
+               $this->_inited = true;\r
+               $this->fields = array();\r
+               if ($queryID) {\r
+                       $this->_currentRow = 0;\r
+                       $this->EOF = !$this->_fetch();\r
+                       @$this->_initrs();\r
+               } else {\r
+                       $this->_numOfRows = 0;\r
+                       $this->_numOfFields = 0;\r
+                       $this->EOF = true;\r
+               }\r
+               \r
+               return $this->_queryID;\r
+       }\r
+\r
+\r
+       function &FetchField($fieldOffset = -1)\r
+       {\r
+               $fld = new ADOFieldObject;\r
+               $fld->name = sqlite_field_name($this->_queryID, $fieldOffset);\r
+               $fld->type = 'VARCHAR';\r
+               $fld->max_length = -1;\r
+               return $fld;\r
+       }\r
+       \r
+   function _initrs()\r
+   {\r
+               $this->_numOfRows = @sqlite_num_rows($this->_queryID);\r
+               $this->_numOfFields = @sqlite_num_fields($this->_queryID);\r
+   }\r
+\r
+       function Fields($colname)\r
+       {\r
+               if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname];\r
+               if (!$this->bind) {\r
+                       $this->bind = array();\r
+                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
+                               $o = $this->FetchField($i);\r
+                               $this->bind[strtoupper($o->name)] = $i;\r
+                       }\r
+               }\r
+               \r
+                return $this->fields[$this->bind[strtoupper($colname)]];\r
+       }\r
+       \r
+   function _seek($row)\r
+   {\r
+               return sqlite_seek($this->_queryID, $row);\r
+   }\r
+\r
+       function _fetch($ignore_fields=false) \r
+       {\r
+               $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);\r
+               return !empty($this->fields);\r
+       }\r
+       \r
+       function _close() \r
+       {\r
+       }\r
+\r
+}\r
 ?>
\ No newline at end of file
diff --git a/lib/adodb/drivers/adodb-sqlitepo.inc.php b/lib/adodb/drivers/adodb-sqlitepo.inc.php
new file mode 100644 (file)
index 0000000..ecd5193
--- /dev/null
@@ -0,0 +1,62 @@
+<?php\r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license.\r
+  Whenever there is any discrepancy between the two licenses,\r
+  the BSD license will take precedence.\r
+\r
+  Portable version of sqlite driver, to make it more similar to other database drivers.\r
+  The main differences are\r
+\r
+   1. When selecting (joining) multiple tables, in assoc mode the table\r
+         names are included in the assoc keys in the "sqlite" driver.\r
+         \r
+         In "sqlitepo" driver, the table names are stripped from the returned column names. \r
+         When this results in a conflict,  the first field get preference.\r
+\r
+       Contributed by Herman Kuiper  herman#ozuzo.net  \r
+*/\r
+\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+include_once(ADODB_DIR.'/drivers/adodb-sqlite.inc.php');\r
+\r
+class ADODB_sqlitepo extends ADODB_sqlite {\r
+   var $databaseType = 'sqlitepo';\r
+\r
+   function ADODB_sqlitepo()\r
+   {\r
+      $this->ADODB_sqlite();\r
+   }\r
+}\r
+\r
+/*--------------------------------------------------------------------------------------\r
+       Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+\r
+class ADORecordset_sqlitepo extends ADORecordset_sqlite {\r
+\r
+   var $databaseType = 'sqlitepo';\r
+\r
+   function ADORecordset_sqlitepo($queryID,$mode=false)\r
+   {\r
+      $this->ADORecordset_sqlite($queryID,$mode);\r
+   }\r
+   \r
+   // Modified to strip table names from returned fields\r
+   function _fetch($ignore_fields=false)\r
+   {\r
+      $this->fields = array();\r
+      $fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);\r
+      if(is_array($fields))\r
+         foreach($fields as $n => $v)\r
+         {\r
+            if(($p = strpos($n, ".")) !== false)\r
+               $n = substr($n, $p+1);\r
+            $this->fields[$n] = $v;\r
+         }\r
+\r
+      return !empty($this->fields);\r
+   }\r
+}\r
+?>
\ No newline at end of file
index 2c8982210fbfbc4d92ce016bc665599901ace4f5..3febfd8589878c4eb7d044e89d2ee5304e60b93e 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 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. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)
-  
-  - MSSQL date patch applied.
-  
-  Date patch by Toni 15 Feb 2002
-*/
-class ADODB_sybase extends ADOConnection {
-       var $databaseType = "sybase";   
-       //var $dataProvider = 'sybase';
-       var $replaceQuote = "''"; // string to use to replace quotes
-       var $fmtDate = "'Y-m-d'";
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";
-       var $hasInsertID = true;
-       var $hasAffectedRows = true;
-       var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";
-       // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
-       var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'";
-       /*
-       "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 $concat_operator = '+'; 
-       var $arrayClass = 'ADORecordSet_array_sybase';
-       var $sysDate = 'GetDate()';
-       var $leftOuter = '*=';
-       var $rightOuter = '=*';
-       
-       function ADODB_sybase() 
-       {                       
-       }
-       // might require begintrans -- committrans
-       function _insertid()
-       {
-               return $this->GetOne('select @@identity');
-       }
-         // might require begintrans -- committrans
-       function _affectedrows()
-       {
-          return $this->GetOne('select @@rowcount');
-       }
-
-                         
-       function BeginTrans()
-       {       
-       
-               if ($this->transOff) return true;
-               $this->transCnt += 1;
-                  
-               $this->Execute('BEGIN TRAN');
-               return true;
-       }
-       
-       function CommitTrans($ok=true) 
-       { 
-               if ($this->transOff) return true;
-               
-               if (!$ok) return $this->RollbackTrans();
-       
-               $this->transCnt -= 1;
-               $this->Execute('COMMIT TRAN');
-               return true;
-       }
-       
-       function RollbackTrans()
-       {
-               if ($this->transOff) return true;
-               $this->transCnt -= 1;
-               $this->Execute('ROLLBACK TRAN');
-               return true;
-       }
-       
-       // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
-       function RowLock($tables,$where) 
-       {
-               if (!$this->_hastrans) $this->BeginTrans();
-               $tables = str_replace(',',' HOLDLOCK,',$tables);
-               return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");
-               
-       }       
-               
-       function SelectDB($dbName) {
-               $this->databaseName = $dbName;
-               if ($this->_connectionID) {
-                       return @sybase_select_db($dbName);              
-               }
-               else return false;      
-       }
-
-       /*      Returns: the last error message from previous database operation
-               Note: This function is NOT available for Microsoft SQL Server.  */      
-
-       function ErrorMsg() 
-       {
-               if ($this->_logsql) return $this->_errorMsg;
-               $this->_errorMsg = sybase_get_last_message();
-               return $this->_errorMsg;
-       }
-
-       // returns true or false
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('sybase_connect')) return false;
-               
-               $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
-               if ($this->_connectionID === false) return false;
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);
-               return true;    
-       }
-       // returns true or false
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-       {
-               if (!function_exists('sybase_connect')) return false;
-               
-               $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)
-       {
-       global $ADODB_COUNTRECS;
-       
-               if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
-                       return sybase_unbuffered_query($sql,$this->_connectionID);
-               else
-                       return sybase_query($sql,$this->_connectionID);
-       }
-       
-       // 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) 
-       {
-               if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-                       return $rs;
-               }
-               $cnt = ($nrows > 0) ? $nrows : 0;
-               if ($offset > 0 && $cnt) $cnt += $offset;
-               
-               $this->Execute("set rowcount $cnt"); 
-               $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-               $this->Execute("set rowcount 0"); 
-               
-               return $rs;
-       }
-
-       // returns true or false
-       function _close()
-       { 
-               return @sybase_close($this->_connectionID);
-       }
-       
-       function UnixDate($v)
-       {
-               return ADORecordSet_array_sybase::UnixDate($v);
-       }
-       
-       function UnixTimeStamp($v)
-       {
-               return ADORecordSet_array_sybase::UnixTimeStamp($v);
-       }       
-       
-       
-
-       # Added 2003-10-05 by Chris Phillipson
-    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25
-    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
-    // 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(yy,$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(qq,$col)";
-                break;
-            case 'D':
-            case 'd':
-                $s .= "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')";
-                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;
-    }
-       
-       # Added 2003-10-07 by Chris Phillipson
-    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
-    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
-    function MetaPrimaryKeys($table)
-    {
-        $sql = "SELECT c.column_name " .
-               "FROM syscolumn c, systable t " .
-               "WHERE t.table_name='$table' AND c.table_id=t.table_id " .
-               "AND t.table_type='BASE' " .
-               "AND c.pkey = 'Y' " .
-               "ORDER BY c.column_id";
-
-        $a = $this->GetCol($sql);
-        if ($a && sizeof($a)>0) return $a;
-        return false;
-    }
-}
-       
-/*--------------------------------------------------------------------------------------
-        Class Name: Recordset
---------------------------------------------------------------------------------------*/
-global $ADODB_sybase_mths;
-$ADODB_sybase_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);
-
-class ADORecordset_sybase extends ADORecordSet {       
-
-       var $databaseType = "sybase";
-       var $canSeek = true;
-       // _mths works only in non-localised system
-       var  $_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);    
-
-       function ADORecordset_sybase($id,$mode=false)
-       {
-               if ($mode === false) { 
-                       global $ADODB_FETCH_MODE;
-                       $mode = $ADODB_FETCH_MODE;
-               }
-               if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
-               else $this->fetchMode = $mode;
-               return $this->ADORecordSet($id,$mode);
-       }
-       
-       /*      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 ($fieldOffset != -1) {
-                       $o = @sybase_fetch_field($this->_queryID, $fieldOffset);
-               }
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
-                       $o = @sybase_fetch_field($this->_queryID);
-               }
-               // older versions of PHP did not support type, only numeric
-               if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';
-               return $o;
-       }
-       
-       function _initrs()
-       {
-       global $ADODB_COUNTRECS;
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;
-               $this->_numOfFields = @sybase_num_fields($this->_queryID);
-       }
-       
-       function _seek($row) 
-       {
-               return @sybase_data_seek($this->_queryID, $row);
-       }               
-
-       function _fetch($ignore_fields=false) 
-       {
-               if ($this->fetchMode == ADODB_FETCH_NUM) {
-                       $this->fields = @sybase_fetch_row($this->_queryID);
-               } else if ($this->fetchMode == ADODB_FETCH_ASSOC) {
-                       $this->fields = @sybase_fetch_row($this->_queryID);
-                       if (is_array($this->fields)) {
-                               $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
-                               return true;
-                       }
-                       return false;
-               }  else {
-                       $this->fields = @sybase_fetch_array($this->_queryID);
-               }
-               if ( is_array($this->fields)) {
-                       return true;
-               }
-
-               return false;
-       }
-       
-       /*      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() {
-               return @sybase_free_result($this->_queryID);            
-       }
-       
-       // sybase/mssql uses a default date like Dec 30 2000 12:00AM
-       function UnixDate($v)
-       {
-               return ADORecordSet_array_sybase::UnixDate($v);
-       }
-       
-       function UnixTimeStamp($v)
-       {
-               return ADORecordSet_array_sybase::UnixTimeStamp($v);
-       }
-}
-
-class ADORecordSet_array_sybase extends ADORecordSet_array {
-       function ADORecordSet_array_sybase($id=-1)
-       {
-               $this->ADORecordSet_array($id);
-       }
-       
-               // sybase/mssql uses a default date like Dec 30 2000 12:00AM
-       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})"
-                       ,$v, $rr)) return parent::UnixDate($v);
-                       
-               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
-               
-               $themth = substr(strtoupper($rr[1]),0,3);
-               $themth = $ADODB_sybase_mths[$themth];
-               if ($themth <= 0) return false;
-               // h-m-s-MM-DD-YY
-               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);
-       }
-       
-       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})"
-                       ,$v, $rr)) return parent::UnixTimeStamp($v);
-               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
-               
-               $themth = substr(strtoupper($rr[1]),0,3);
-               $themth = $ADODB_sybase_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,$rr[2],$rr[3]);
-       }
-}
-?>
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim. All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)\r
+  \r
+  - MSSQL date patch applied.\r
+  \r
+  Date patch by Toni 15 Feb 2002\r
+*/\r
\r
+ // security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class ADODB_sybase extends ADOConnection {\r
+       var $databaseType = "sybase";   \r
+       //var $dataProvider = 'sybase';\r
+       var $replaceQuote = "''"; // string to use to replace quotes\r
+       var $fmtDate = "'Y-m-d'";\r
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
+       var $hasInsertID = true;\r
+       var $hasAffectedRows = true;\r
+       var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";\r
+       // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8\r
+       var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'";\r
+       /*\r
+       "select c.name,t.name,c.length from \r
+       syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id \r
+       where o.name='%s'";\r
+       */\r
+       var $concat_operator = '+'; \r
+       var $arrayClass = 'ADORecordSet_array_sybase';\r
+       var $sysDate = 'GetDate()';\r
+       var $leftOuter = '*=';\r
+       var $rightOuter = '=*';\r
+       \r
+       function ADODB_sybase() \r
+       {                       \r
+       }\r
\r
+       // might require begintrans -- committrans\r
+       function _insertid()\r
+       {\r
+               return $this->GetOne('select @@identity');\r
+       }\r
+         // might require begintrans -- committrans\r
+       function _affectedrows()\r
+       {\r
+          return $this->GetOne('select @@rowcount');\r
+       }\r
+\r
+                         \r
+       function BeginTrans()\r
+       {       \r
+       \r
+               if ($this->transOff) return true;\r
+               $this->transCnt += 1;\r
+                  \r
+               $this->Execute('BEGIN TRAN');\r
+               return true;\r
+       }\r
+       \r
+       function CommitTrans($ok=true) \r
+       { \r
+               if ($this->transOff) return true;\r
+               \r
+               if (!$ok) return $this->RollbackTrans();\r
+       \r
+               $this->transCnt -= 1;\r
+               $this->Execute('COMMIT TRAN');\r
+               return true;\r
+       }\r
+       \r
+       function RollbackTrans()\r
+       {\r
+               if ($this->transOff) return true;\r
+               $this->transCnt -= 1;\r
+               $this->Execute('ROLLBACK TRAN');\r
+               return true;\r
+       }\r
+       \r
+       // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4\r
+       function RowLock($tables,$where) \r
+       {\r
+               if (!$this->_hastrans) $this->BeginTrans();\r
+               $tables = str_replace(',',' HOLDLOCK,',$tables);\r
+               return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");\r
+               \r
+       }       \r
+               \r
+       function SelectDB($dbName) {\r
+               $this->databaseName = $dbName;\r
+               if ($this->_connectionID) {\r
+                       return @sybase_select_db($dbName);              \r
+               }\r
+               else return false;      \r
+       }\r
+\r
+       /*      Returns: the last error message from previous database operation\r
+               Note: This function is NOT available for Microsoft SQL Server.  */      \r
+\r
+       function ErrorMsg() \r
+       {\r
+               if ($this->_logsql) return $this->_errorMsg;\r
+               $this->_errorMsg = sybase_get_last_message();\r
+               return $this->_errorMsg;\r
+       }\r
+\r
+       // returns true or false\r
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('sybase_connect')) return null;\r
+               \r
+               $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       // returns true or false\r
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
+       {\r
+               if (!function_exists('sybase_connect')) return null;\r
+               \r
+               $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);\r
+               if ($this->_connectionID === false) return false;\r
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
+               return true;    \r
+       }\r
+       \r
+       // returns query ID if successful, otherwise false\r
+       function _query($sql,$inputarr)\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+       \r
+               if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)\r
+                       return sybase_unbuffered_query($sql,$this->_connectionID);\r
+               else\r
+                       return sybase_query($sql,$this->_connectionID);\r
+       }\r
+       \r
+       // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
+       {\r
+               if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset\r
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+                       return $rs;\r
+               }\r
+               $cnt = ($nrows > 0) ? $nrows : 0;\r
+               if ($offset > 0 && $cnt) $cnt += $offset;\r
+               \r
+               $this->Execute("set rowcount $cnt"); \r
+               $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+               $this->Execute("set rowcount 0"); \r
+               \r
+               return $rs;\r
+       }\r
+\r
+       // returns true or false\r
+       function _close()\r
+       { \r
+               return @sybase_close($this->_connectionID);\r
+       }\r
+       \r
+       function UnixDate($v)\r
+       {\r
+               return ADORecordSet_array_sybase::UnixDate($v);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+               return ADORecordSet_array_sybase::UnixTimeStamp($v);\r
+       }       \r
+       \r
+       \r
+\r
+       # Added 2003-10-05 by Chris Phillipson\r
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25\r
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version\r
+    // Format date column in sql string given an input format that understands Y M D\r
+    function SQLDate($fmt, $col=false)\r
+    {\r
+        if (!$col) $col = $this->sysTimeStamp;\r
+        $s = '';\r
+\r
+        $len = strlen($fmt);\r
+        for ($i=0; $i < $len; $i++) {\r
+            if ($s) $s .= '+';\r
+            $ch = $fmt[$i];\r
+            switch($ch) {\r
+            case 'Y':\r
+            case 'y':\r
+                $s .= "datename(yy,$col)";\r
+                break;\r
+            case 'M':\r
+                $s .= "convert(char(3),$col,0)";\r
+                break;\r
+            case 'm':\r
+                $s .= "replace(str(month($col),2),' ','0')";\r
+                break;\r
+            case 'Q':\r
+            case 'q':\r
+                $s .= "datename(qq,$col)";\r
+                break;\r
+            case 'D':\r
+            case 'd':\r
+                $s .= "replace(str(datepart(dd,$col),2),' ','0')";\r
+                break;\r
+            case 'h':\r
+                $s .= "substring(convert(char(14),$col,0),13,2)";\r
+                break;\r
+\r
+            case 'H':\r
+                $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
+                break;\r
+\r
+            case 'i':\r
+                $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
+                break;\r
+            case 's':\r
+                $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
+                break;\r
+            case 'a':\r
+            case 'A':\r
+                $s .= "substring(convert(char(19),$col,0),18,2)";\r
+                break;\r
+\r
+            default:\r
+                if ($ch == '\\') {\r
+                    $i++;\r
+                    $ch = substr($fmt,$i,1);\r
+                }\r
+                $s .= $this->qstr($ch);\r
+                break;\r
+            }\r
+        }\r
+        return $s;\r
+    }\r
+       \r
+       # Added 2003-10-07 by Chris Phillipson\r
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8\r
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version\r
+    function MetaPrimaryKeys($table)\r
+    {\r
+        $sql = "SELECT c.column_name " .\r
+               "FROM syscolumn c, systable t " .\r
+               "WHERE t.table_name='$table' AND c.table_id=t.table_id " .\r
+               "AND t.table_type='BASE' " .\r
+               "AND c.pkey = 'Y' " .\r
+               "ORDER BY c.column_id";\r
+\r
+        $a = $this->GetCol($sql);\r
+        if ($a && sizeof($a)>0) return $a;\r
+        return false;\r
+    }\r
+}\r
+       \r
+/*--------------------------------------------------------------------------------------\r
+        Class Name: Recordset\r
+--------------------------------------------------------------------------------------*/\r
+global $ADODB_sybase_mths;\r
+$ADODB_sybase_mths = array(\r
+       'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,\r
+       'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);\r
+\r
+class ADORecordset_sybase extends ADORecordSet {       \r
+\r
+       var $databaseType = "sybase";\r
+       var $canSeek = true;\r
+       // _mths works only in non-localised system\r
+       var  $_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);    \r
+\r
+       function ADORecordset_sybase($id,$mode=false)\r
+       {\r
+               if ($mode === false) { \r
+                       global $ADODB_FETCH_MODE;\r
+                       $mode = $ADODB_FETCH_MODE;\r
+               }\r
+               if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;\r
+               else $this->fetchMode = $mode;\r
+               return $this->ADORecordSet($id,$mode);\r
+       }\r
+       \r
+       /*      Returns: an object containing field information. \r
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
+               fetchField() is retrieved.      */\r
+       function &FetchField($fieldOffset = -1) \r
+       {\r
+               if ($fieldOffset != -1) {\r
+                       $o = @sybase_fetch_field($this->_queryID, $fieldOffset);\r
+               }\r
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
+                       $o = @sybase_fetch_field($this->_queryID);\r
+               }\r
+               // older versions of PHP did not support type, only numeric\r
+               if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';\r
+               return $o;\r
+       }\r
+       \r
+       function _initrs()\r
+       {\r
+       global $ADODB_COUNTRECS;\r
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;\r
+               $this->_numOfFields = @sybase_num_fields($this->_queryID);\r
+       }\r
+       \r
+       function _seek($row) \r
+       {\r
+               return @sybase_data_seek($this->_queryID, $row);\r
+       }               \r
+\r
+       function _fetch($ignore_fields=false) \r
+       {\r
+               if ($this->fetchMode == ADODB_FETCH_NUM) {\r
+                       $this->fields = @sybase_fetch_row($this->_queryID);\r
+               } else if ($this->fetchMode == ADODB_FETCH_ASSOC) {\r
+                       $this->fields = @sybase_fetch_row($this->_queryID);\r
+                       if (is_array($this->fields)) {\r
+                               $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
+                               return true;\r
+                       }\r
+                       return false;\r
+               }  else {\r
+                       $this->fields = @sybase_fetch_array($this->_queryID);\r
+               }\r
+               if ( is_array($this->fields)) {\r
+                       return true;\r
+               }\r
+\r
+               return false;\r
+       }\r
+       \r
+       /*      close() only needs to be called if you are worried about using too much memory while your script\r
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
+       function _close() {\r
+               return @sybase_free_result($this->_queryID);            \r
+       }\r
+       \r
+       // sybase/mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+               return ADORecordSet_array_sybase::UnixDate($v);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+               return ADORecordSet_array_sybase::UnixTimeStamp($v);\r
+       }\r
+}\r
+\r
+class ADORecordSet_array_sybase extends ADORecordSet_array {\r
+       function ADORecordSet_array_sybase($id=-1)\r
+       {\r
+               $this->ADORecordSet_array($id);\r
+       }\r
+       \r
+               // sybase/mssql uses a default date like Dec 30 2000 12:00AM\r
+       function UnixDate($v)\r
+       {\r
+       global $ADODB_sybase_mths;\r
+       \r
+               //Dec 30 2000 12:00AM\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"\r
+                       ,$v, $rr)) return parent::UnixDate($v);\r
+                       \r
+               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_sybase_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);\r
+       }\r
+       \r
+       function UnixTimeStamp($v)\r
+       {\r
+       global $ADODB_sybase_mths;\r
+               //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com\r
+               //Changed [0-9] to [0-9 ] in day conversion\r
+               if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"\r
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
+               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
+               \r
+               $themth = substr(strtoupper($rr[1]),0,3);\r
+               $themth = $ADODB_sybase_mths[$themth];\r
+               if ($themth <= 0) return false;\r
+               \r
+               switch (strtoupper($rr[6])) {\r
+               case 'P':\r
+                       if ($rr[4]<12) $rr[4] += 12;\r
+                       break;\r
+               case 'A':\r
+                       if ($rr[4]==12) $rr[4] = 0;\r
+                       break;\r
+               default:\r
+                       break;\r
+               }\r
+               // h-m-s-MM-DD-YY\r
+               return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);\r
+       }\r
+}\r
+?>\r
index 2032ea4541a7ac02894c20bdbfa7f4b94a58d67a..7b1c227207373cfd5776c7f934baf47b6a7ebeff 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
-*/
-
-if (!defined('_ADODB_ODBC_LAYER')) {
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
-}
-if (!defined('ADODB_VFP')){
-define('ADODB_VFP',1);
-class ADODB_vfp extends ADODB_odbc {
-       var $databaseType = "vfp";      
-       var $fmtDate = "{^Y-m-d}";
-       var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
-       var $replaceQuote = "'+chr(39)+'" ;
-       var $true = '.T.';
-       var $false = '.F.';
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
-       var $upperCase = 'upper';
-       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
-       var $sysTimeStamp = 'datetime()';
-       var $sysDate = 'date()';
-       var $ansiOuter = true;
-       var $hasTransactions = false;
-       var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
-       
-       function ADODB_vfp()
-       {
-               $this->ADODB_odbc();
-       }
-       
-       function BeginTrans() { return false;}
-       
-       // quote string to be sent back to database
-       function qstr($s,$nofixquotes=false)
-       {
-               if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
-               return "'".$s."'";
-       }
-
-       
-       // TOP requires ORDER BY for VFP
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
-       {
-               if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
-               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
-       }
-
-
-};
-
-class  ADORecordSet_vfp extends ADORecordSet_odbc {    
-       
-       var $databaseType = "vfp";              
-
-       
-       function ADORecordSet_vfp($id,$mode=false)
-       {
-               return $this->ADORecordSet_odbc($id,$mode);
-       }
-
-       function MetaType($t,$len=-1)
-       {
-               if (is_object($t)) {
-                       $fieldobj = $t;
-                       $t = $fieldobj->type;
-                       $len = $fieldobj->max_length;
-               }
-               switch (strtoupper($t)) {
-               case 'C':
-                       if ($len <= $this->blobSize) return 'C';
-               case 'M':
-                       return 'X';
-                        
-               case 'D': return 'D';
-               
-               case 'T': return 'T';
-               
-               case 'L': return 'L';
-               
-               case 'I': return 'I';
-               
-               default: return 'N';
-               }
-       }
-}
-
-} //define
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.\r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+if (!defined('_ADODB_ODBC_LAYER')) {\r
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
+}\r
+if (!defined('ADODB_VFP')){\r
+define('ADODB_VFP',1);\r
+class ADODB_vfp extends ADODB_odbc {\r
+       var $databaseType = "vfp";      \r
+       var $fmtDate = "{^Y-m-d}";\r
+       var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";\r
+       var $replaceQuote = "'+chr(39)+'" ;\r
+       var $true = '.T.';\r
+       var $false = '.F.';\r
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
+       var $upperCase = 'upper';\r
+       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably\r
+       var $sysTimeStamp = 'datetime()';\r
+       var $sysDate = 'date()';\r
+       var $ansiOuter = true;\r
+       var $hasTransactions = false;\r
+       var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L\r
+       \r
+       function ADODB_vfp()\r
+       {\r
+               $this->ADODB_odbc();\r
+       }\r
+       \r
+       function Time()\r
+       {\r
+               return time();\r
+       }\r
+       \r
+       \r
+       function BeginTrans() { return false;}\r
+       \r
+       // quote string to be sent back to database\r
+       function qstr($s,$nofixquotes=false)\r
+       {\r
+               if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";\r
+               return "'".$s."'";\r
+       }\r
+\r
+       \r
+       // TOP requires ORDER BY for VFP\r
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
+       {\r
+               $this->hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false;\r
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
+       }\r
+       \r
+\r
+\r
+};\r
\r
+\r
+class  ADORecordSet_vfp extends ADORecordSet_odbc {    \r
+       \r
+       var $databaseType = "vfp";              \r
+\r
+       \r
+       function ADORecordSet_vfp($id,$mode=false)\r
+       {\r
+               return $this->ADORecordSet_odbc($id,$mode);\r
+       }\r
+\r
+       function MetaType($t,$len=-1)\r
+       {\r
+               if (is_object($t)) {\r
+                       $fieldobj = $t;\r
+                       $t = $fieldobj->type;\r
+                       $len = $fieldobj->max_length;\r
+               }\r
+               switch (strtoupper($t)) {\r
+               case 'C':\r
+                       if ($len <= $this->blobSize) return 'C';\r
+               case 'M':\r
+                       return 'X';\r
+                        \r
+               case 'D': return 'D';\r
+               \r
+               case 'T': return 'T';\r
+               \r
+               case 'L': return 'L';\r
+               \r
+               case 'I': return 'I';\r
+               \r
+               default: return 'N';\r
+               }\r
+       }\r
+}\r
+\r
+} //define\r
 ?>
\ No newline at end of file
index 786fc32bfe6f793c86cd5ee5c86d6782e4953f54..2353871c041dc26b34a29f50415dd9eb3f75b831 100644 (file)
-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.
-
-Commercial use of ADOdb is encouraged. Make money and multiply!
-
-BSD Style-License
-=================
-
-Copyright (c) 2000, 2001, 2002, 2003 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. 
-
-
+ADOdb is dual licensed using BSD and LGPL. \r
+\r
+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.\r
+\r
+For more info about ADOdb, visit http://adodb.sourceforge.net/\r
+\r
+BSD Style-License\r
+=================\r
+\r
+Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without modification, \r
+are permitted provided that the following conditions are met:\r
+\r
+Redistributions of source code must retain the above copyright notice, this list \r
+of conditions and the following disclaimer. \r
+\r
+Redistributions in binary form must reproduce the above copyright notice, this list \r
+of conditions and the following disclaimer in the documentation and/or other materials \r
+provided with the distribution. \r
+\r
+Neither the name of the John Lim nor the names of its contributors may be used to \r
+endorse or promote products derived from this software without specific prior written \r
+permission. \r
+\r
+DISCLAIMER:\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY \r
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \r
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL \r
+JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \r
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \r
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \r
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \r
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \r
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+==========================================================\r
+GNU LESSER GENERAL PUBLIC LICENSE\r
+Version 2.1, February 1999 \r
\r
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.\r
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+Everyone is permitted to copy and distribute verbatim copies\r
+of this license document, but changing it is not allowed.\r
+\r
+[This is the first released version of the Lesser GPL.  It also counts\r
+ as the successor of the GNU Library Public License, version 2, hence\r
+ the version number 2.1.]\r
\r
\r
+Preamble\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+\r
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\r
+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". \r
+\r
+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. \r
+\r
+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".) \r
+\r
+"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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+a) The modified work must itself be a software library. \r
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. \r
+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. \r
+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. \r
+(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.) \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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.) \r
+\r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+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.) \r
+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. \r
+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. \r
+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. \r
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. \r
+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. \r
+\r
+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. \r
+\r
+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: \r
+\r
+\r
+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. \r
+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. \r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+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. \r
+\r
+NO WARRANTY \r
+\r
+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. \r
+\r
+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. \r
+\r
+\r
 END OF TERMS AND CONDITIONS
\ No newline at end of file
index 75bc51149c7303f72ec1b3c32101d9ac98b2bbbc..0ede9381cf52b5db7fab829a7a0e4c4cf381d7a9 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-
-// Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575
-
-// SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t
-class perf_db2 extends adodb_perf{
-       var $createTableSQL = "CREATE TABLE adodb_logsql (
-                 created TIMESTAMP 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 
-                               case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 
-                               else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end 
-                               FROM TABLE(SNAPSHOT_APPL('',-2)) as t",
-                       '=WarnCacheRatio'),
-                       
-       'Data Cache',
-               'data cache buffers' => array('DATAC',
-               'select sum(npages) from SYSCAT.BUFFERPOOLS',
-                       'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ),
-               'cache blocksize' => array('DATAC',
-               'select avg(pagesize) from SYSCAT.BUFFERPOOLS',
-                       '' ),
-               'data cache size' => array('DATAC',
-               'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS',
-                       '' ),
-       'Connections',
-               'current connections' => array('SESS',
-                       "SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t",
-                       ''),
-
-               false
-       );
-
-
-       function perf_db2(&$conn)
-       {
-               $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;
-                               }
-                       }
-               }
-               $qno = rand();
-               $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql");
-               ob_start();
-               if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>";
-               else {
-                       $rs = $this->conn->Execute("select * from explain_statement where queryno=$qno");
-                       if ($rs) rs2html($rs);
-               }
-               $s = ob_get_contents();
-               ob_end_clean();
-               $this->conn->LogSQL($save);
-               
-               $s .= $this->Tracer($sql);
-               return $s;
-       }
-       
-       
-       function Tables()
-       {
-               $rs = $this->conn->Execute("select tabschema,tabname,card as rows,
-                       npages pages_used,fpages pages_allocated, tbspace tablespace  
-                       from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2");
-               return rs2html($rs,false,false,false,false);
-       }
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+// Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575\r
+\r
+// SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t\r
+class perf_db2 extends adodb_perf{\r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+                 created TIMESTAMP NOT NULL,\r
+                 sql0 varchar(250) NOT NULL,\r
+                 sql1 varchar(4000) NOT NULL,\r
+                 params varchar(3000) NOT NULL,\r
+                 tracer varchar(500) NOT NULL,\r
+                 timer decimal(16,6) NOT NULL\r
+               )";\r
+               \r
+       var $settings = array(\r
+       'Ratios',\r
+               'data cache hit ratio' => array('RATIO',\r
+                       "SELECT \r
+                               case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 \r
+                               else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end \r
+                               FROM TABLE(SNAPSHOT_APPL('',-2)) as t",\r
+                       '=WarnCacheRatio'),\r
+                       \r
+       'Data Cache',\r
+               'data cache buffers' => array('DATAC',\r
+               'select sum(npages) from SYSCAT.BUFFERPOOLS',\r
+                       'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ),\r
+               'cache blocksize' => array('DATAC',\r
+               'select avg(pagesize) from SYSCAT.BUFFERPOOLS',\r
+                       '' ),\r
+               'data cache size' => array('DATAC',\r
+               'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS',\r
+                       '' ),\r
+       'Connections',\r
+               'current connections' => array('SESS',\r
+                       "SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t",\r
+                       ''),\r
+\r
+               false\r
+       );\r
+\r
+\r
+       function perf_db2(&$conn)\r
+       {\r
+               $this->conn =& $conn;\r
+       }\r
+       \r
+       function Explain($sql,$partial=false)\r
+       {\r
+               $save = $this->conn->LogSQL(false);\r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
+                       if ($arr) {\r
+                               foreach($arr as $row) {\r
+                                       $sql = reset($row);\r
+                                       if (crc32($sql) == $partial) break;\r
+                               }\r
+                       }\r
+               }\r
+               $qno = rand();\r
+               $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql");\r
+               ob_start();\r
+               if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>";\r
+               else {\r
+                       $rs = $this->conn->Execute("select * from explain_statement where queryno=$qno");\r
+                       if ($rs) rs2html($rs);\r
+               }\r
+               $s = ob_get_contents();\r
+               ob_end_clean();\r
+               $this->conn->LogSQL($save);\r
+               \r
+               $s .= $this->Tracer($sql);\r
+               return $s;\r
+       }\r
+       \r
+       \r
+       function Tables()\r
+       {\r
+               $rs = $this->conn->Execute("select tabschema,tabname,card as rows,\r
+                       npages pages_used,fpages pages_allocated, tbspace tablespace  \r
+                       from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2");\r
+               return rs2html($rs,false,false,false,false);\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index b6ac4492835826c1d7ffb1c503e80679827d1ffd..34144f0191d74491bd4312af242f3382faddb5fa 100644 (file)
@@ -1,67 +1,70 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-//
-// Thx to  Fernando Ortiz, mailto:fortiz#lacorona.com.mx
-// With info taken from http://www.oninit.com/oninit/sysmaster/index.html
-//
-class perf_informix extends adodb_perf{
-
-       // Maximum size on varchar upto 9.30 255 chars
-       // better truncate varchar to 255 than char(4000) ?
-       var $createTableSQL = "CREATE TABLE adodb_logsql (
-               created datetime year to second NOT NULL,
-               sql0 varchar(250) NOT NULL,
-               sql1 varchar(255) NOT NULL,
-               params varchar(255) NOT NULL,
-               tracer varchar(255) NOT NULL,
-               timer decimal(16,6) NOT NULL
-       )";
-       
-       var $tablesSQL = "select a.tabname tablename, ti_nptotal*2 size_in_k, ti_nextns extents, ti_nrows records from systables c, sysmaster:systabnames a, sysmaster:systabinfo b where c.tabname not matches 'sys*' and c.partnum = a.partnum and c.partnum = b.ti_partnum";
-       
-       var $settings = array(
-       'Ratios',
-               'data cache hit ratio' => array('RATIOH',
-               "select round((1-(wt.value / (rd.value + wr.value)))*100,2)
-               from sysmaster:sysprofile wr, sysmaster:sysprofile rd, sysmaster:sysprofile wt
-               where rd.name = 'pagreads' and
-               wr.name = 'pagwrites' and
-               wt.name = 'buffwts'",
-               '=WarnCacheRatio'),
-       'IO',
-               'data reads' => array('IO',
-               "select value from sysmaster:sysprofile where name='pagreads'",
-               'Page reads'),
-               
-               'data writes' => array('IO',
-               "select value from sysmaster:sysprofile where name='pagwrites'",
-               'Page writes'),
-       
-       'Connections',
-               'current connections' => array('SESS',
-               'select count(*) from sysmaster:syssessions',
-               'Number of sessions'),
-       
-       false
-       
-       );
-       
-       function perf_informix(&$conn)
-       {
-               $this->conn =& $conn;
-       }
-
-}
-?>
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+//\r
+// Thx to  Fernando Ortiz, mailto:fortiz#lacorona.com.mx\r
+// With info taken from http://www.oninit.com/oninit/sysmaster/index.html\r
+//\r
+class perf_informix extends adodb_perf{\r
+\r
+       // Maximum size on varchar upto 9.30 255 chars\r
+       // better truncate varchar to 255 than char(4000) ?\r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+               created datetime year to second NOT NULL,\r
+               sql0 varchar(250) NOT NULL,\r
+               sql1 varchar(255) NOT NULL,\r
+               params varchar(255) NOT NULL,\r
+               tracer varchar(255) NOT NULL,\r
+               timer decimal(16,6) NOT NULL\r
+       )";\r
+       \r
+       var $tablesSQL = "select a.tabname tablename, ti_nptotal*2 size_in_k, ti_nextns extents, ti_nrows records from systables c, sysmaster:systabnames a, sysmaster:systabinfo b where c.tabname not matches 'sys*' and c.partnum = a.partnum and c.partnum = b.ti_partnum";\r
+       \r
+       var $settings = array(\r
+       'Ratios',\r
+               'data cache hit ratio' => array('RATIOH',\r
+               "select round((1-(wt.value / (rd.value + wr.value)))*100,2)\r
+               from sysmaster:sysprofile wr, sysmaster:sysprofile rd, sysmaster:sysprofile wt\r
+               where rd.name = 'pagreads' and\r
+               wr.name = 'pagwrites' and\r
+               wt.name = 'buffwts'",\r
+               '=WarnCacheRatio'),\r
+       'IO',\r
+               'data reads' => array('IO',\r
+               "select value from sysmaster:sysprofile where name='pagreads'",\r
+               'Page reads'),\r
+               \r
+               'data writes' => array('IO',\r
+               "select value from sysmaster:sysprofile where name='pagwrites'",\r
+               'Page writes'),\r
+       \r
+       'Connections',\r
+               'current connections' => array('SESS',\r
+               'select count(*) from sysmaster:syssessions',\r
+               'Number of sessions'),\r
+       \r
+       false\r
+       \r
+       );\r
+       \r
+       function perf_informix(&$conn)\r
+       {\r
+               $this->conn =& $conn;\r
+       }\r
+\r
+}\r
+?>\r
index 9ea5c497ef61b1ac5c3c21b7eac807862cb073f6..b648ee27fde3a3c3b27cab3d2791c3ced9bd4ab6 100644 (file)
-<?php
-
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-/*
-       MSSQL has moved most performance info to Performance Monitor
-*/
-class perf_mssql 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_mssql(&$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;
-       }
-       
-       
-}
-
+<?php\r
+\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+/*\r
+       MSSQL has moved most performance info to Performance Monitor\r
+*/\r
+class perf_mssql extends adodb_perf{\r
+       var $sql1 = 'cast(sql1 as text)';\r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+                 created datetime NOT NULL,\r
+                 sql0 varchar(250) NOT NULL,\r
+                 sql1 varchar(4000) NOT NULL,\r
+                 params varchar(3000) NOT NULL,\r
+                 tracer varchar(500) NOT NULL,\r
+                 timer decimal(16,6) NOT NULL\r
+               )";\r
+               \r
+       var $settings = array(\r
+       'Ratios',\r
+               'data cache hit ratio' => array('RATIO',\r
+                       "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'",\r
+                       '=WarnCacheRatio'),\r
+               'prepared sql hit ratio' => array('RATIO',\r
+                       array('dbcc cachestats','Prepared',1,100),\r
+                       ''),\r
+               'adhoc sql hit ratio' => array('RATIO',\r
+                       array('dbcc cachestats','Adhoc',1,100),\r
+                       ''),\r
+       'IO',\r
+               'data reads' => array('IO',\r
+               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),\r
+               'data writes' => array('IO',\r
+               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),\r
+                       \r
+       'Data Cache',\r
+               'data cache size' => array('DATAC',\r
+               "select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",\r
+                       '' ),\r
+               'data cache blocksize' => array('DATAC',\r
+                       "select 8192",'page size'),\r
+       'Connections',\r
+               'current connections' => array('SESS',\r
+                       '=sp_who',\r
+                       ''),\r
+               'max connections' => array('SESS',\r
+                       "SELECT @@MAX_CONNECTIONS",\r
+                       ''),\r
+\r
+               false\r
+       );\r
+       \r
+       \r
+       function perf_mssql(&$conn)\r
+       {\r
+               if ($conn->dataProvider == 'odbc') {\r
+                       $this->sql1 = 'sql1';\r
+                       //$this->explain = false;\r
+               }\r
+               $this->conn =& $conn;\r
+       }\r
+       \r
+       function Explain($sql,$partial=false)\r
+       {\r
+               \r
+               $save = $this->conn->LogSQL(false);\r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
+                       if ($arr) {\r
+                               foreach($arr as $row) {\r
+                                       $sql = reset($row);\r
+                                       if (crc32($sql) == $partial) break;\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
+               $this->conn->Execute("SET SHOWPLAN_ALL ON;");\r
+               $sql = str_replace('?',"''",$sql);\r
+               global $ADODB_FETCH_MODE;\r
+               \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $rs =& $this->conn->Execute($sql);\r
+               //adodb_printr($rs);\r
+               $ADODB_FETCH_MODE = $save;\r
+               if ($rs) {\r
+                       $rs->MoveNext();\r
+                       $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>';\r
+                       while (!$rs->EOF) {\r
+                               $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!!!!\r
+                               $rs->MoveNext();\r
+                       }\r
+                       $s .= '</table>';\r
+                       \r
+                       $rs->NextRecordSet();\r
+               }\r
+               \r
+               $this->conn->Execute("SET SHOWPLAN_ALL OFF;");\r
+               $this->conn->LogSQL($save);\r
+               $s .= $this->Tracer($sql);\r
+               return $s;\r
+       }\r
+       \r
+       function Tables()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+       \r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               //$this->conn->debug=1;\r
+               $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>';\r
+               $rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");\r
+               if ($rs1) {\r
+                       while (!$rs1->EOF) {\r
+                               $tab = $rs1->fields[0];\r
+                               $tabq = $this->conn->qstr($tab);\r
+                               $rs2 = $this->conn->Execute("sp_spaceused $tabq");\r
+                               if ($rs2) {\r
+                                       $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>';\r
+                                       $rs2->Close();\r
+                               }\r
+                               $rs1->MoveNext();\r
+                       }\r
+                       $rs1->Close();\r
+               }\r
+               $ADODB_FETCH_MODE = $save;\r
+               return $s.'</table>';\r
+       }\r
+       \r
+       function sp_who()\r
+       {\r
+               $arr = $this->conn->GetArray('sp_who');\r
+               return sizeof($arr);\r
+       }\r
+       \r
+       function HealthCheck($cli=false)\r
+       {\r
+               \r
+               $this->conn->Execute('dbcc traceon(3604)');\r
+               $html =  adodb_perf::HealthCheck($cli);\r
+               $this->conn->Execute('dbcc traceoff(3604)');\r
+               return $html;\r
+       }\r
+       \r
+       \r
+}\r
+\r
 ?>
\ No newline at end of file
index 274bca9b30c42fa45353d781185f763e56acc0e8..4ff94d14ad65b7095f09e310db63b719b2c87583 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-class perf_mysql extends adodb_perf{
-       
-       var $tablesSQL = 'show table status';
-       
-       var $createTableSQL = "CREATE TABLE adodb_logsql (
-                 created datetime NOT NULL,
-                 sql0 varchar(250) NOT NULL,
-                 sql1 text NOT NULL,
-                 params text NOT NULL,
-                 tracer text NOT NULL,
-                 timer decimal(16,6) NOT NULL
-               )";
-               
-       var $settings = array(
-       'Ratios',
-               'MyISAM cache hit ratio' => array('RATIO',
-                       '=GetKeyHitRatio',
-                       '=WarnCacheRatio'),
-               'InnoDB cache hit ratio' => array('RATIO',
-                       '=GetInnoDBHitRatio',
-                       '=WarnCacheRatio'),
-               'data cache hit ratio' => array('HIDE', # only if called
-                       '=FindDBHitRatio',
-                       '=WarnCacheRatio'),
-               'sql cache hit ratio' => array('RATIO',
-                       '=GetQHitRatio',
-                       ''),
-       'IO',
-               'data reads' => array('IO',
-                       '=GetReads',
-                       'Number of selects (Key_reads is not accurate)'),
-               'data writes' => array('IO',
-                       '=GetWrites',
-                       'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
-               
-       'Data Cache',
-               'MyISAM data cache size' => array('DATAC',
-                       array("show variables", 'key_buffer_size'),
-                       '' ),
-               'BDB data cache size' => array('DATAC',
-                       array("show variables", 'bdb_cache_size'),
-                       '' ),
-               'InnoDB data cache size' => array('DATAC',
-                       array("show variables", 'innodb_buffer_pool_size'),
-                       '' ),
-       'Memory Usage',
-               'read buffer size' => array('CACHE',
-                       array("show variables", 'read_buffer_size'),
-                       '(per session)'),
-               'sort buffer size' => array('CACHE',
-                       array("show variables", 'sort_buffer_size'),
-                       'Size of sort buffer (per session)' ),
-               'table cache' => array('CACHE',
-                       array("show variables", 'table_cache'),
-                       'Number of tables to keep open'),
-       'Connections',  
-               'current connections' => array('SESS',
-                       array('show status','Threads_connected'),
-                       ''),
-               'max connections' => array( 'SESS',
-                       array("show variables",'max_connections'),
-                       ''),
-       
-               false
-       );
-       
-       function perf_mysql(&$conn)
-       {
-               $this->conn =& $conn;
-       }
-       
-       function Explain($sql,$partial=false)
-       {
-               
-               if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';
-               $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;
-                               }
-                       }
-               }
-               $sql = str_replace('?',"''",$sql);
-               
-               if ($partial) {
-                       $sqlq = $this->conn->qstr($sql.'%');
-                       $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");
-               }
-               
-               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
-               $rs = $this->conn->Execute('EXPLAIN '.$sql);
-               $s .= rs2html($rs,false,false,false,false);
-               $this->conn->LogSQL($save);
-               $s .= $this->Tracer($sql);
-               return $s;
-       }
-       
-       function Tables()
-       {
-               if (!$this->tablesSQL) return false;
-               
-               $rs = $this->conn->Execute($this->tablesSQL);
-               if (!$rs) return false;
-               
-               $html = rs2html($rs,false,false,false,false);
-               return $html;
-       }
-       
-       function GetReads()
-       {
-       global $ADODB_FETCH_MODE;
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $rs = $this->conn->Execute('show status');
-               $ADODB_FETCH_MODE = $save;
-               
-               if (!$rs) return 0;
-               $val = 0;
-               while (!$rs->EOF) {
-                       switch($rs->fields[0]) {
-                       case 'Com_select': 
-                               $val = $rs->fields[1];
-                               $rs->Close();
-                               return $val;
-                       }
-                       $rs->MoveNext();
-               } 
-               
-               $rs->Close();
-               
-               return $val;
-       }
-       
-       function GetWrites()
-       {
-       global $ADODB_FETCH_MODE;
-               $save = $ADODB_FETCH_MODE;
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-               $rs = $this->conn->Execute('show status');
-               $ADODB_FETCH_MODE = $save;
-               
-               if (!$rs) return 0;
-               $val = 0.0;
-               while (!$rs->EOF) {
-                       switch($rs->fields[0]) {
-                       case 'Com_insert': 
-                               $val += $rs->fields[1]; break;
-                       case 'Com_delete': 
-                               $val += $rs->fields[1]; break;
-                       case 'Com_update': 
-                               $val += $rs->fields[1]/2;
-                               $rs->Close();
-                               return $val;
-                       }
-                       $rs->MoveNext();
-               } 
-               
-               $rs->Close();
-               
-               return $val;
-       }
-       
-       function FindDBHitRatio()
-       {
-               // first find out type of table
-               //$this->conn->debug=1;
-               $rs = $this->conn->Execute('show table status');
-               if (!$rs) return '';
-               $type = strtoupper($rs->fields[1]);
-               $rs->Close();
-               switch($type){
-               case 'MYISAM':
-               case 'ISAM':
-                       return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';
-               case 'INNODB':
-                       return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';
-               default:
-                       return $type.' not supported';
-               }
-               
-       }
-       
-       function GetQHitRatio()
-       {
-               //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached
-               $hits = $this->_DBParameter(array("show status","Qcache_hits"));
-               $total = $this->_DBParameter(array("show status","Qcache_inserts"));
-               $total += $this->_DBParameter(array("show status","Qcache_not_cached"));
-               
-               $total += $hits;
-               if ($total) return ($hits*100)/$total;
-               return 0;
-       }
-       
-       /*
-               Use session variable to store Hit percentage, because MySQL
-               does not remember last value of SHOW INNODB STATUS hit ratio
-               
-               # 1st query to SHOW INNODB STATUS
-               0.00 reads/s, 0.00 creates/s, 0.00 writes/s
-               Buffer pool hit rate 1000 / 1000
-               
-               # 2nd query to SHOW INNODB STATUS
-               0.00 reads/s, 0.00 creates/s, 0.00 writes/s
-               No buffer pool activity since the last printout
-       */
-       function GetInnoDBHitRatio()
-       {
-       global $HTTP_SESSION_VARS;
-       
-               $rs = $this->conn->Execute('show innodb status');
-               if (!$rs || $rs->EOF) return 0;
-               $stat = $rs->fields[0];
-               $rs->Close();
-               $at = strpos($stat,'Buffer pool hit rate');
-               $stat = substr($stat,$at,200);
-               if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {
-                       $val = 100*$arr[1]/$arr[2];
-                       $HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;
-                       return $val;
-               } else {
-                       if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];
-                       return 0;
-               }
-               return 0;
-       }
-       
-       function GetKeyHitRatio()
-       {
-               $hits = $this->_DBParameter(array("show status","Key_read_requests"));
-               $reqs = $this->_DBParameter(array("show status","Key_reads"));
-               if ($reqs == 0) return 0;
-               
-               return ($hits/($reqs+$hits))*100;
-       }
-       
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class perf_mysql extends adodb_perf{\r
+       \r
+       var $tablesSQL = 'show table status';\r
+       \r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+                 created datetime NOT NULL,\r
+                 sql0 varchar(250) NOT NULL,\r
+                 sql1 text NOT NULL,\r
+                 params text NOT NULL,\r
+                 tracer text NOT NULL,\r
+                 timer decimal(16,6) NOT NULL\r
+               )";\r
+               \r
+       var $settings = array(\r
+       'Ratios',\r
+               'MyISAM cache hit ratio' => array('RATIO',\r
+                       '=GetKeyHitRatio',\r
+                       '=WarnCacheRatio'),\r
+               'InnoDB cache hit ratio' => array('RATIO',\r
+                       '=GetInnoDBHitRatio',\r
+                       '=WarnCacheRatio'),\r
+               'data cache hit ratio' => array('HIDE', # only if called\r
+                       '=FindDBHitRatio',\r
+                       '=WarnCacheRatio'),\r
+               'sql cache hit ratio' => array('RATIO',\r
+                       '=GetQHitRatio',\r
+                       ''),\r
+       'IO',\r
+               'data reads' => array('IO',\r
+                       '=GetReads',\r
+                       'Number of selects (Key_reads is not accurate)'),\r
+               'data writes' => array('IO',\r
+                       '=GetWrites',\r
+                       'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),\r
+               \r
+       'Data Cache',\r
+               'MyISAM data cache size' => array('DATAC',\r
+                       array("show variables", 'key_buffer_size'),\r
+                       '' ),\r
+               'BDB data cache size' => array('DATAC',\r
+                       array("show variables", 'bdb_cache_size'),\r
+                       '' ),\r
+               'InnoDB data cache size' => array('DATAC',\r
+                       array("show variables", 'innodb_buffer_pool_size'),\r
+                       '' ),\r
+       'Memory Usage',\r
+               'read buffer size' => array('CACHE',\r
+                       array("show variables", 'read_buffer_size'),\r
+                       '(per session)'),\r
+               'sort buffer size' => array('CACHE',\r
+                       array("show variables", 'sort_buffer_size'),\r
+                       'Size of sort buffer (per session)' ),\r
+               'table cache' => array('CACHE',\r
+                       array("show variables", 'table_cache'),\r
+                       'Number of tables to keep open'),\r
+       'Connections',  \r
+               'current connections' => array('SESS',\r
+                       array('show status','Threads_connected'),\r
+                       ''),\r
+               'max connections' => array( 'SESS',\r
+                       array("show variables",'max_connections'),\r
+                       ''),\r
+       \r
+               false\r
+       );\r
+       \r
+       function perf_mysql(&$conn)\r
+       {\r
+               $this->conn =& $conn;\r
+       }\r
+       \r
+       function Explain($sql,$partial=false)\r
+       {\r
+               \r
+               if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';\r
+               $save = $this->conn->LogSQL(false);\r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
+                       if ($arr) {\r
+                               foreach($arr as $row) {\r
+                                       $sql = reset($row);\r
+                                       if (crc32($sql) == $partial) break;\r
+                               }\r
+                       }\r
+               }\r
+               $sql = str_replace('?',"''",$sql);\r
+               \r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");\r
+               }\r
+               \r
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
+               $rs = $this->conn->Execute('EXPLAIN '.$sql);\r
+               $s .= rs2html($rs,false,false,false,false);\r
+               $this->conn->LogSQL($save);\r
+               $s .= $this->Tracer($sql);\r
+               return $s;\r
+       }\r
+       \r
+       function Tables()\r
+       {\r
+               if (!$this->tablesSQL) return false;\r
+               \r
+               $rs = $this->conn->Execute($this->tablesSQL);\r
+               if (!$rs) return false;\r
+               \r
+               $html = rs2html($rs,false,false,false,false);\r
+               return $html;\r
+       }\r
+       \r
+       function GetReads()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $rs = $this->conn->Execute('show status');\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               if (!$rs) return 0;\r
+               $val = 0;\r
+               while (!$rs->EOF) {\r
+                       switch($rs->fields[0]) {\r
+                       case 'Com_select': \r
+                               $val = $rs->fields[1];\r
+                               $rs->Close();\r
+                               return $val;\r
+                       }\r
+                       $rs->MoveNext();\r
+               } \r
+               \r
+               $rs->Close();\r
+               \r
+               return $val;\r
+       }\r
+       \r
+       function GetWrites()\r
+       {\r
+       global $ADODB_FETCH_MODE;\r
+               $save = $ADODB_FETCH_MODE;\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+               $rs = $this->conn->Execute('show status');\r
+               $ADODB_FETCH_MODE = $save;\r
+               \r
+               if (!$rs) return 0;\r
+               $val = 0.0;\r
+               while (!$rs->EOF) {\r
+                       switch($rs->fields[0]) {\r
+                       case 'Com_insert': \r
+                               $val += $rs->fields[1]; break;\r
+                       case 'Com_delete': \r
+                               $val += $rs->fields[1]; break;\r
+                       case 'Com_update': \r
+                               $val += $rs->fields[1]/2;\r
+                               $rs->Close();\r
+                               return $val;\r
+                       }\r
+                       $rs->MoveNext();\r
+               } \r
+               \r
+               $rs->Close();\r
+               \r
+               return $val;\r
+       }\r
+       \r
+       function FindDBHitRatio()\r
+       {\r
+               // first find out type of table\r
+               //$this->conn->debug=1;\r
+               $rs = $this->conn->Execute('show table status');\r
+               if (!$rs) return '';\r
+               $type = strtoupper($rs->fields[1]);\r
+               $rs->Close();\r
+               switch($type){\r
+               case 'MYISAM':\r
+               case 'ISAM':\r
+                       return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';\r
+               case 'INNODB':\r
+                       return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';\r
+               default:\r
+                       return $type.' not supported';\r
+               }\r
+               \r
+       }\r
+       \r
+       function GetQHitRatio()\r
+       {\r
+               //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached\r
+               $hits = $this->_DBParameter(array("show status","Qcache_hits"));\r
+               $total = $this->_DBParameter(array("show status","Qcache_inserts"));\r
+               $total += $this->_DBParameter(array("show status","Qcache_not_cached"));\r
+               \r
+               $total += $hits;\r
+               if ($total) return ($hits*100)/$total;\r
+               return 0;\r
+       }\r
+       \r
+       /*\r
+               Use session variable to store Hit percentage, because MySQL\r
+               does not remember last value of SHOW INNODB STATUS hit ratio\r
+               \r
+               # 1st query to SHOW INNODB STATUS\r
+               0.00 reads/s, 0.00 creates/s, 0.00 writes/s\r
+               Buffer pool hit rate 1000 / 1000\r
+               \r
+               # 2nd query to SHOW INNODB STATUS\r
+               0.00 reads/s, 0.00 creates/s, 0.00 writes/s\r
+               No buffer pool activity since the last printout\r
+       */\r
+       function GetInnoDBHitRatio()\r
+       {\r
+       global $HTTP_SESSION_VARS;\r
+       \r
+               $rs = $this->conn->Execute('show innodb status');\r
+               if (!$rs || $rs->EOF) return 0;\r
+               $stat = $rs->fields[0];\r
+               $rs->Close();\r
+               $at = strpos($stat,'Buffer pool hit rate');\r
+               $stat = substr($stat,$at,200);\r
+               if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {\r
+                       $val = 100*$arr[1]/$arr[2];\r
+                       $HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;\r
+                       return $val;\r
+               } else {\r
+                       if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];\r
+                       return 0;\r
+               }\r
+               return 0;\r
+       }\r
+       \r
+       function GetKeyHitRatio()\r
+       {\r
+               $hits = $this->_DBParameter(array("show status","Key_read_requests"));\r
+               $reqs = $this->_DBParameter(array("show status","Key_reads"));\r
+               if ($reqs == 0) return 0;\r
+               \r
+               return ($hits/($reqs+$hits))*100;\r
+       }\r
+       \r
+}\r
 ?>
\ No newline at end of file
index ba278e1182e0b385e90be2e22942ea9e269a33d7..bdbfaa1df11b5f1e677e025252af8e049fead2db 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-class perf_oci8 extends ADODB_perf{
-       
-       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,
-                 sql1 varchar(4000) NOT NULL,
-                 params varchar(4000),
-                 tracer varchar(4000),
-                 timer decimal(16,6) NOT NULL
-               )";
-       
-       var $settings = array(
-       'Ratios',
-               'data cache hit ratio' => array('RATIOH',
-                       "select round((1-(phy.value / (cur.value + con.value)))*100,2) 
-                       from v\$sysstat cur, v\$sysstat con, v\$sysstat phy
-                       where cur.name = 'db block gets' and
-                             con.name = 'consistent gets' and
-                             phy.name = 'physical reads'",
-                       '=WarnCacheRatio'),
-               
-               'sql cache hit ratio' => array( 'RATIOH',
-                       'select round(100*(sum(pins)-sum(reloads))/sum(pins),2)  from v$librarycache',
-                       'increase <i>shared_pool_size</i> if too ratio low'),
-                       
-               'datadict cache hit ratio' => array('RATIOH',
-               "select      
-           round((1 - (sum(getmisses) / (sum(gets) +          
-                sum(getmisses))))*100,2)
-               from  v\$rowcache",
-               'increase <i>shared_pool_size</i> if too ratio low'),
-               
-               'memory sort ratio' => array('RATIOH',
-               "SELECT ROUND((100 * b.VALUE) /DECODE ((a.VALUE + b.VALUE), 
-       0,1,(a.VALUE + b.VALUE)),2)
-FROM   v\$sysstat a, 
-       v\$sysstat b
-WHERE  a.name = 'sorts (disk)'
-AND    b.name = 'sorts (memory)'",
-       "% of memory sorts compared to disk sorts - should be over 95%"),
-
-       'IO',
-               'data reads' => array('IO',
-               "select value from v\$sysstat where name='physical reads'"),
-       
-       'data writes' => array('IO',
-               "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'",
-                       'Number of cache buffers. Tune <i>db_cache_size</i> if the <i>data cache hit ratio</i> is too low.'),
-               'data cache blocksize' => array('DATAC',
-                       "select value from v\$parameter where name='db_block_size'",
-                       '' ),                   
-       'Memory Pools',
-               'data cache size' => array('DATAC',
-                       "select value from v\$parameter where name = 'db_cache_size'",
-                       'db_cache_size' ),
-               'shared pool size' => array('DATAC',
-                       "select value from v\$parameter where name = 'shared_pool_size'",
-                       'shared_pool_size, which holds shared cursors, stored procedures and similar shared structs' ),
-               'java pool size' => array('DATAJ',
-                       "select value from v\$parameter where name = 'java_pool_size'",
-                       'java_pool_size' ),
-               'large pool buffer size' => array('CACHE',
-                       "select value from v\$parameter where name='large_pool_size'",
-                       'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ),
-
-               'pga buffer size' => array('CACHE',                     
-                       "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)' ),
-
-               
-               'Connections',
-               'current connections' => array('SESS',
-                       'select count(*) from sys.v_$session where username is not null',
-                       ''),
-               'max connections' => array( 'SESS',
-                       "select value from v\$parameter where name='sessions'",
-                       ''),
-
-       'Memory Utilization',           
-               'data cache utilization ratio' => array('RATIOU',
-                       "select round((1-bytes/sgasize)*100, 2)
-                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
-                       where name = 'free memory' and pool = 'shared pool'",
-               'Percentage of data cache actually in use - too low is bad, too high is worse'),
-               
-               'shared pool utilization ratio' => array('RATIOU',
-               'select round((sga.bytes/p.value)*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\'',
-               'Percentage of shared pool actually used - too low is bad, too high is worse'),
-               
-               'large pool utilization ratio' => array('RATIOU',
-                       "select round((1-bytes/sgasize)*100, 2)
-                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
-                       where name = 'free memory' and pool = 'large pool'",
-               'Percentage of large_pool actually in use - too low is bad, too high is worse'),
-               'sort buffer size' => array('CACHE',
-                       "select value from v\$parameter where name='sort_area_size'",
-                       'sort_area_size (per query), uses memory in pga' ),
-
-               'pga usage at peak' => array('RATIOU',
-               '=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'),
-       'Transactions',
-               'rollback segments' => array('ROLLBACK',
-                       "select count(*) from sys.v_\$rollstat",
-                       ''),
-       
-               'peak transactions' => array('ROLLBACK',
-                       "select max_utilization  tx_hwm
-               from sys.v_\$resource_limit
-               where resource_name = 'transactions'",
-                       'Taken from high-water-mark'),
-               'max transactions' => array('ROLLBACK',
-                       "select value from v\$parameter where name = 'transactions'",
-                       'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'),
-       'Parameters',   
-               'cursor sharing' => array('CURSOR',
-                       "select value from v\$parameter where name = 'cursor_sharing'",
-                       'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.'),
-                       
-               'index cache cost' => array('COST',
-                       "select value from v\$parameter where name = 'optimizer_index_caching'",
-                       '% of indexed data blocks expected in the cache.
-                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.'),
-               
-               'random page cost' => array('COST',
-                       "select value from v\$parameter where name = 'optimizer_index_cost_adj'",
-                       'Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. '),              
-               
-               false
-               
-       );
-       
-       
-       function perf_oci8(&$conn)
-       {
-               $savelog = $conn->LogSQL(false);        
-               $this->version = $conn->ServerInfo();
-               $conn->LogSQL($savelog);        
-               $this->conn =& $conn;
-       }
-       
-       
-       function PGA()
-       {
-               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,
-                  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,
-                  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 
-               b.pct < 100");
-               if (!$rs) return "Only in 9i or later";
-               $rs->Close();
-               if ($rs->EOF) return "PGA could be too big";
-               
-               return reset($rs->fields);
-       }
-       
-       function Explain($sql,$partial=false) 
-       {
-               $savelog = $this->conn->LogSQL(false);
-               $rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");
-               if (!$rs) {
-                       echo "<p><b>Missing PLAN_TABLE</b></p>
-<pre>
-CREATE TABLE PLAN_TABLE (
-  STATEMENT_ID                    VARCHAR2(30),
-  TIMESTAMP                       DATE,
-  REMARKS                         VARCHAR2(80),
-  OPERATION                       VARCHAR2(30),
-  OPTIONS                         VARCHAR2(30),
-  OBJECT_NODE                     VARCHAR2(128),
-  OBJECT_OWNER                    VARCHAR2(30),
-  OBJECT_NAME                     VARCHAR2(30),
-  OBJECT_INSTANCE                 NUMBER(38),
-  OBJECT_TYPE                     VARCHAR2(30),
-  OPTIMIZER                       VARCHAR2(255),
-  SEARCH_COLUMNS                  NUMBER,
-  ID                              NUMBER(38),
-  PARENT_ID                       NUMBER(38),
-  POSITION                        NUMBER(38),
-  COST                            NUMBER(38),
-  CARDINALITY                     NUMBER(38),
-  BYTES                           NUMBER(38),
-  OTHER_TAG                       VARCHAR2(255),
-  PARTITION_START                 VARCHAR2(255),
-  PARTITION_STOP                  VARCHAR2(255),
-  PARTITION_ID                    NUMBER(38),
-  OTHER                           LONG,
-  DISTRIBUTION                    VARCHAR2(30)
-);
-</pre>";
-                       return false;
-               }
-               
-               $rs->Close();
-       //      $this->conn->debug=1;
-       
-               if ($partial) {
-                       $sqlq = $this->conn->qstr($sql.'%');
-                       $arr = $this->conn->GetArray("select distinct 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->BeginTrans();
-               $id = "ADODB ".microtime();
-               $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
-               $m = $this->conn->ErrorMsg();
-               if ($m) {
-                       $this->conn->RollbackTrans();
-                       $this->conn->LogSQL($savelog);
-                       $s .= "<p>$m</p>";
-                       return $s;
-               }
-               $rs = $this->conn->Execute("
-               select 
-  '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, 
-  object_name,COST,CARDINALITY,bytes
-               FROM plan_table 
-START WITH id = 0  and STATEMENT_ID='$id'  
-CONNECT BY prior id=parent_id and statement_id='$id'");
-               
-               $s .= rs2html($rs,false,false,false,false);
-               $this->conn->RollbackTrans();
-               $this->conn->LogSQL($savelog);
-               $s .= $this->Tracer($sql,$partial);
-               return $s;
-       }
-       
-       
-       function CheckMemory()
-       {
-               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");
-               if (!$rs) return false;
-               
-               /*
-               The v$db_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size
-               */
-               $s = "<h3>Data Cache Estimate</h3>";
-               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 .= rs2html($rs,false,false,false,false);
-               }
-               return $s;
-       }
-       
-       /*
-               Generate html for suspicious/expensive sql
-       */
-       function tohtml(&$rs,$type)
-       {
-               $o1 = $rs->FetchField(0);
-               $o2 = $rs->FetchField(1);
-               $o3 = $rs->FetchField(2);
-               if ($rs->EOF) return '<p>None found</p>';
-               $check = '';
-               $sql = '';
-               $s = "\n\n<table border=1 bgcolor=white><tr><td><b>".$o1->name.'</b></td><td><b>'.$o2->name.'</b></td><td><b>'.$o3->name.'</b></td></tr>';
-               while (!$rs->EOF) {
-                       if ($check != $rs->fields[0].'::'.$rs->fields[1]) {
-                               if ($check) {
-                                       $carr = explode('::',$check);
-                                       $prefix = "<a href=\"?$type=1&sql=".rawurlencode($sql).'&x#explain">';
-                                       $suffix = '</a>';
-                                       if (strlen($prefix)>2000) {
-                                               $prefix = '';
-                                               $suffix = '';
-                                       }
-                                       
-                                       $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
-                               }
-                               $sql = $rs->fields[2];
-                               $check = $rs->fields[0].'::'.$rs->fields[1];                    
-                       } else
-                               $sql .= $rs->fields[2];
-                       
-                       $rs->MoveNext();
-               }
-               $rs->Close();
-               
-               $carr = explode('::',$check);
-               $prefix = "<a target=".rand()." href=\"?&hidem=1&$type=1&sql=".rawurlencode($sql).'&x#explain">';
-               $suffix = '</a>';
-               if (strlen($prefix)>2000) {
-                       $prefix = '';
-                       $suffix = '';
-               }
-               $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
-                                       
-               return $s."</table>\n\n";
-       }
-       
-       // code thanks to Ixora. 
-       // http://www.ixora.com.au/scripts/query_opt.htm
-       // requires oracle 8.1.7 or later
-       function SuspiciousSQL($numsql=10)
-       {
-               $sql = "
-select
-  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
-  s.executions  executes,
-  p.sql_text
-from
-  ( 
-    select
-      address,
-      buffer_gets,
-      executions,
-      pct,
-      rank() over (order by buffer_gets desc)  ranking
-    from
-      ( 
-       select
-         address,
-         buffer_gets,
-         executions,
-         100 * ratio_to_report(buffer_gets) over ()  pct
-       from
-         sys.v_\$sql
-       where
-         command_type != 47 and module != 'T.O.A.D.'
-      )
-    where
-      buffer_gets > 50 * executions
-  )  s,
-  sys.v_\$sqltext  p
-where
-  s.ranking <= $numsql and
-  p.address = s.address
-order by
-  1 desc, s.address, p.piece";
-
-               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
-               if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) {
-                               $partial = empty($HTTP_GET_VARS['part']);
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
-               }
-
-               if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL();
-               
-               $save = $ADODB_CACHE_MODE;
-               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;
-               $savelog = $this->conn->LogSQL(false);
-               $rs =& $this->conn->SelectLimit($sql);
-               $this->conn->LogSQL($savelog);
-               $ADODB_CACHE_MODE = $save;
-               if ($rs) {
-                       $s = "\n<h3>Ixora Suspicious SQL</h3>";
-                       $s .= $this->tohtml($rs,'expsixora');
-               } else 
-                       $s = '';
-               
-               if ($s) $s .= '<p>';
-               $s .= $this->_SuspiciousSQL();
-               return $s;
-       }
-       
-       // code thanks to Ixora. 
-       // http://www.ixora.com.au/scripts/query_opt.htm
-       // requires oracle 8.1.7 or later
-       function ExpensiveSQL($numsql = 10)
-       {
-               $sql = "
-select
-  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
-  s.executions  executes,
-  p.sql_text
-from
-  ( 
-    select
-      address,
-      disk_reads,
-      executions,
-      pct,
-      rank() over (order by disk_reads desc)  ranking
-    from
-      (
-       select
-         address,
-         disk_reads,
-         executions,
-         100 * ratio_to_report(disk_reads) over ()  pct
-       from
-         sys.v_\$sql
-       where
-         command_type != 47 and module != 'T.O.A.D.'
-      )
-    where
-      disk_reads > 50 * executions
-  )  s,
-  sys.v_\$sqltext  p
-where
-  s.ranking <= $numsql and
-  p.address = s.address
-order by
-  1 desc, s.address, p.piece
-";
-               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
-               if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) {
-                       $partial = empty($HTTP_GET_VARS['part']);       
-                       echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
-               }
-               
-               if (isset($HTTP_GET_VARS['sql'])) {
-                        $var =& $this->_ExpensiveSQL();
-                        return $var;
-               }
-               $save = $ADODB_CACHE_MODE;
-               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;
-               $savelog = $this->conn->LogSQL(false);
-               $rs =& $this->conn->Execute($sql);
-               $this->conn->LogSQL($savelog);
-               $ADODB_CACHE_MODE = $save;
-               if ($rs) {
-                       $s = "\n<h3>Ixora Expensive SQL</h3>";
-                       $s .= $this->tohtml($rs,'expeixora');
-               } else 
-                       $s = '';
-               
-               
-               if ($s) $s .= '<p>';
-               $s .= $this->_ExpensiveSQL();
-               return $s;
-       }
-       
-}
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+class perf_oci8 extends ADODB_perf{\r
+       \r
+       var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents \r
+          group by segment_name,tablespace_name";\r
+        \r
+       var $version;\r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+                 created date NOT NULL,\r
+                 sql0 varchar(250) NOT NULL,\r
+                 sql1 varchar(4000) NOT NULL,\r
+                 params varchar(4000),\r
+                 tracer varchar(4000),\r
+                 timer decimal(16,6) NOT NULL\r
+               )";\r
+       \r
+       var $settings = array(\r
+       'Ratios',\r
+               'data cache hit ratio' => array('RATIOH',\r
+                       "select round((1-(phy.value / (cur.value + con.value)))*100,2) \r
+                       from v\$sysstat cur, v\$sysstat con, v\$sysstat phy\r
+                       where cur.name = 'db block gets' and\r
+                             con.name = 'consistent gets' and\r
+                             phy.name = 'physical reads'",\r
+                       '=WarnCacheRatio'),\r
+               \r
+               'sql cache hit ratio' => array( 'RATIOH',\r
+                       'select round(100*(sum(pins)-sum(reloads))/sum(pins),2)  from v$librarycache',\r
+                       'increase <i>shared_pool_size</i> if too ratio low'),\r
+                       \r
+               'datadict cache hit ratio' => array('RATIOH',\r
+               "select      \r
+           round((1 - (sum(getmisses) / (sum(gets) +          \r
+                sum(getmisses))))*100,2)\r
+               from  v\$rowcache",\r
+               'increase <i>shared_pool_size</i> if too ratio low'),\r
+               \r
+               'memory sort ratio' => array('RATIOH',\r
+               "SELECT ROUND((100 * b.VALUE) /DECODE ((a.VALUE + b.VALUE), \r
+       0,1,(a.VALUE + b.VALUE)),2)\r
+FROM   v\$sysstat a, \r
+       v\$sysstat b\r
+WHERE  a.name = 'sorts (disk)'\r
+AND    b.name = 'sorts (memory)'",\r
+       "% of memory sorts compared to disk sorts - should be over 95%"),\r
+\r
+       'IO',\r
+               'data reads' => array('IO',\r
+               "select value from v\$sysstat where name='physical reads'"),\r
+       \r
+       'data writes' => array('IO',\r
+               "select value from v\$sysstat where name='physical writes'"),\r
+       \r
+       'Data Cache',\r
+               'data cache buffers' => array( 'DATAC',\r
+               "select a.value/b.value  from v\$parameter a, v\$parameter b \r
+                       where a.name = 'db_cache_size' and b.name= 'db_block_size'",\r
+                       'Number of cache buffers. Tune <i>db_cache_size</i> if the <i>data cache hit ratio</i> is too low.'),\r
+               'data cache blocksize' => array('DATAC',\r
+                       "select value from v\$parameter where name='db_block_size'",\r
+                       '' ),                   \r
+       'Memory Pools',\r
+               'data cache size' => array('DATAC',\r
+                       "select value from v\$parameter where name = 'db_cache_size'",\r
+                       'db_cache_size' ),\r
+               'shared pool size' => array('DATAC',\r
+                       "select value from v\$parameter where name = 'shared_pool_size'",\r
+                       'shared_pool_size, which holds shared sql, stored procedures, dict cache and similar shared structs' ),\r
+               'java pool size' => array('DATAJ',\r
+                       "select value from v\$parameter where name = 'java_pool_size'",\r
+                       'java_pool_size' ),\r
+               'large pool buffer size' => array('CACHE',\r
+                       "select value from v\$parameter where name='large_pool_size'",\r
+                       'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ),\r
+\r
+               'pga buffer size' => array('CACHE',                     \r
+                       "select value from v\$parameter where name='pga_aggregate_target'",\r
+                       'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ),\r
+\r
+               \r
+               'Connections',\r
+               'current connections' => array('SESS',\r
+                       'select count(*) from sys.v_$session where username is not null',\r
+                       ''),\r
+               'max connections' => array( 'SESS',\r
+                       "select value from v\$parameter where name='sessions'",\r
+                       ''),\r
+\r
+       'Memory Utilization',           \r
+               'data cache utilization ratio' => array('RATIOU',\r
+                       "select round((1-bytes/sgasize)*100, 2)\r
+                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f\r
+                       where name = 'free memory' and pool = 'shared pool'",\r
+               'Percentage of data cache actually in use - should be over 85%'),\r
+               \r
+               'shared pool utilization ratio' => array('RATIOU',\r
+               'select round((sga.bytes/p.value)*100,2)\r
+               from v$sgastat sga, v$parameter p\r
+               where sga.name = \'free memory\' and sga.pool = \'shared pool\'\r
+               and p.name = \'shared_pool_size\'',\r
+               'Percentage of shared pool actually used - too low is bad, too high is worse'),\r
+               \r
+               'large pool utilization ratio' => array('RATIOU',\r
+                       "select round((1-bytes/sgasize)*100, 2)\r
+                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f\r
+                       where name = 'free memory' and pool = 'large pool'",\r
+               'Percentage of large_pool actually in use - too low is bad, too high is worse'),\r
+               'sort buffer size' => array('CACHE',\r
+                       "select value from v\$parameter where name='sort_area_size'",\r
+                       'max in-mem sort_area_size (per query), uses memory in pga' ),\r
+\r
+               'pga usage at peak' => array('RATIOU',\r
+               '=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'),\r
+       'Transactions',\r
+               'rollback segments' => array('ROLLBACK',\r
+                       "select count(*) from sys.v_\$rollstat",\r
+                       ''),\r
+       \r
+               'peak transactions' => array('ROLLBACK',\r
+                       "select max_utilization  tx_hwm\r
+               from sys.v_\$resource_limit\r
+               where resource_name = 'transactions'",\r
+                       'Taken from high-water-mark'),\r
+               'max transactions' => array('ROLLBACK',\r
+                       "select value from v\$parameter where name = 'transactions'",\r
+                       'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'),\r
+       'Parameters',   \r
+               'cursor sharing' => array('CURSOR',\r
+                       "select value from v\$parameter where name = 'cursor_sharing'",\r
+                       'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.'),\r
+               /*\r
+               'cursor reuse' => array('CURSOR',\r
+                       "select count(*) from (select sql_text_wo_constants, count(*)\r
+  from t1\r
+ group by sql_text_wo_constants\r
+having count(*) > 100)",'These are sql statements that should be using bind variables'),*/\r
+               'index cache cost' => array('COST',\r
+                       "select value from v\$parameter where name = 'optimizer_index_caching'",\r
+                       '% of indexed data blocks expected in the cache.\r
+                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.'),\r
+               \r
+               'random page cost' => array('COST',\r
+                       "select value from v\$parameter where name = 'optimizer_index_cost_adj'",\r
+                       'Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. '),              \r
+               \r
+               false\r
+               \r
+       );\r
+       \r
+       \r
+       function perf_oci8(&$conn)\r
+       {\r
+               $savelog = $conn->LogSQL(false);        \r
+               $this->version = $conn->ServerInfo();\r
+               $conn->LogSQL($savelog);        \r
+               $this->conn =& $conn;\r
+       }\r
+       \r
+       \r
+       function PGA()\r
+       {\r
+               if ($this->version['version'] < 9) return 'Oracle 9i or later required';\r
+               \r
+               $rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from \r
+          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,\r
+                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r \r
+                  from v\$pga_target_advice) a left join\r
+          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,\r
+                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r \r
+                  from v\$pga_target_advice) b on \r
+         a.r = b.r+1 where \r
+               b.pct < 100");\r
+               if (!$rs) return "Only in 9i or later";\r
+               $rs->Close();\r
+               if ($rs->EOF) return "PGA could be too big";\r
+               \r
+               return reset($rs->fields);\r
+       }\r
+       \r
+       function Explain($sql,$partial=false) \r
+       {\r
+               $savelog = $this->conn->LogSQL(false);\r
+               $rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");\r
+               if (!$rs) {\r
+                       echo "<p><b>Missing PLAN_TABLE</b></p>\r
+<pre>\r
+CREATE TABLE PLAN_TABLE (\r
+  STATEMENT_ID                    VARCHAR2(30),\r
+  TIMESTAMP                       DATE,\r
+  REMARKS                         VARCHAR2(80),\r
+  OPERATION                       VARCHAR2(30),\r
+  OPTIONS                         VARCHAR2(30),\r
+  OBJECT_NODE                     VARCHAR2(128),\r
+  OBJECT_OWNER                    VARCHAR2(30),\r
+  OBJECT_NAME                     VARCHAR2(30),\r
+  OBJECT_INSTANCE                 NUMBER(38),\r
+  OBJECT_TYPE                     VARCHAR2(30),\r
+  OPTIMIZER                       VARCHAR2(255),\r
+  SEARCH_COLUMNS                  NUMBER,\r
+  ID                              NUMBER(38),\r
+  PARENT_ID                       NUMBER(38),\r
+  POSITION                        NUMBER(38),\r
+  COST                            NUMBER(38),\r
+  CARDINALITY                     NUMBER(38),\r
+  BYTES                           NUMBER(38),\r
+  OTHER_TAG                       VARCHAR2(255),\r
+  PARTITION_START                 VARCHAR2(255),\r
+  PARTITION_STOP                  VARCHAR2(255),\r
+  PARTITION_ID                    NUMBER(38),\r
+  OTHER                           LONG,\r
+  DISTRIBUTION                    VARCHAR2(30)\r
+);\r
+</pre>";\r
+                       return false;\r
+               }\r
+               \r
+               $rs->Close();\r
+       //      $this->conn->debug=1;\r
+       \r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
+                       if ($arr) {\r
+                               foreach($arr as $row) {\r
+                                       $sql = reset($row);\r
+                                       if (crc32($sql) == $partial) break;\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               $s = "<p><b>Explain</b>: ".htmlspecialchars($sql)."</p>";       \r
+               \r
+               $this->conn->BeginTrans();\r
+               $id = "ADODB ".microtime();\r
+               $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");\r
+               $m = $this->conn->ErrorMsg();\r
+               if ($m) {\r
+                       $this->conn->RollbackTrans();\r
+                       $this->conn->LogSQL($savelog);\r
+                       $s .= "<p>$m</p>";\r
+                       return $s;\r
+               }\r
+               $rs = $this->conn->Execute("\r
+               select \r
+  '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, \r
+  object_name,COST,CARDINALITY,bytes\r
+               FROM plan_table \r
+START WITH id = 0  and STATEMENT_ID='$id'  \r
+CONNECT BY prior id=parent_id and statement_id='$id'");\r
+               \r
+               $s .= rs2html($rs,false,false,false,false);\r
+               $this->conn->RollbackTrans();\r
+               $this->conn->LogSQL($savelog);\r
+               $s .= $this->Tracer($sql,$partial);\r
+               return $s;\r
+       }\r
+       \r
+       \r
+       function CheckMemory()\r
+       {\r
+               if ($this->version['version'] < 9) return 'Oracle 9i or later required';\r
+               \r
+                $rs =& $this->conn->Execute("\r
+select  a.size_for_estimate as cache_mb_estimate,\r
+       case when a.size_factor=1 then \r
+               '&lt;&lt;= current'\r
+        when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then\r
+               '- BETTER - '\r
+       else ' ' end as currsize, \r
+   a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0\r
+   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice) a , \r
+   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice) b where a.r = b.r-1");\r
+               if (!$rs) return false;\r
+               \r
+               /*\r
+               The v$db_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size\r
+               */\r
+               $s = "<h3>Data Cache Estimate</h3>";\r
+               if ($rs->EOF) {\r
+                       $s .= "<p>Cache that is 50% of current size is still too big</p>";\r
+               } else {\r
+                       $s .= "Ideal size of Data Cache is when \"best_when_0\" changes from a positive number and becomes zero.";\r
+                       $s .= rs2html($rs,false,false,false,false);\r
+               }\r
+               return $s;\r
+       }\r
+       \r
+       /*\r
+               Generate html for suspicious/expensive sql\r
+       */\r
+       function tohtml(&$rs,$type)\r
+       {\r
+               $o1 = $rs->FetchField(0);\r
+               $o2 = $rs->FetchField(1);\r
+               $o3 = $rs->FetchField(2);\r
+               if ($rs->EOF) return '<p>None found</p>';\r
+               $check = '';\r
+               $sql = '';\r
+               $s = "\n\n<table border=1 bgcolor=white><tr><td><b>".$o1->name.'</b></td><td><b>'.$o2->name.'</b></td><td><b>'.$o3->name.'</b></td></tr>';\r
+               while (!$rs->EOF) {\r
+                       if ($check != $rs->fields[0].'::'.$rs->fields[1]) {\r
+                               if ($check) {\r
+                                       $carr = explode('::',$check);\r
+                                       $prefix = "<a href=\"?$type=1&sql=".rawurlencode($sql).'&x#explain">';\r
+                                       $suffix = '</a>';\r
+                                       if (strlen($prefix)>2000) {\r
+                                               $prefix = '';\r
+                                               $suffix = '';\r
+                                       }\r
+                                       \r
+                                       $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';\r
+                               }\r
+                               $sql = $rs->fields[2];\r
+                               $check = $rs->fields[0].'::'.$rs->fields[1];                    \r
+                       } else\r
+                               $sql .= $rs->fields[2];\r
+                       \r
+                       $rs->MoveNext();\r
+               }\r
+               $rs->Close();\r
+               \r
+               $carr = explode('::',$check);\r
+               $prefix = "<a target=".rand()." href=\"?&hidem=1&$type=1&sql=".rawurlencode($sql).'&x#explain">';\r
+               $suffix = '</a>';\r
+               if (strlen($prefix)>2000) {\r
+                       $prefix = '';\r
+                       $suffix = '';\r
+               }\r
+               $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';\r
+                                       \r
+               return $s."</table>\n\n";\r
+       }\r
+       \r
+       // code thanks to Ixora. \r
+       // http://www.ixora.com.au/scripts/query_opt.htm\r
+       // requires oracle 8.1.7 or later\r
+       function SuspiciousSQL($numsql=10)\r
+       {\r
+               $sql = "\r
+select\r
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,\r
+  s.executions  executes,\r
+  p.sql_text\r
+from\r
+  ( \r
+    select\r
+      address,\r
+      buffer_gets,\r
+      executions,\r
+      pct,\r
+      rank() over (order by buffer_gets desc)  ranking\r
+    from\r
+      ( \r
+       select\r
+         address,\r
+         buffer_gets,\r
+         executions,\r
+         100 * ratio_to_report(buffer_gets) over ()  pct\r
+       from\r
+         sys.v_\$sql\r
+       where\r
+         command_type != 47 and module != 'T.O.A.D.'\r
+      )\r
+    where\r
+      buffer_gets > 50 * executions\r
+  )  s,\r
+  sys.v_\$sqltext  p\r
+where\r
+  s.ranking <= $numsql and\r
+  p.address = s.address\r
+order by\r
+  1 desc, s.address, p.piece";\r
+\r
+               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;\r
+               if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) {\r
+                               $partial = empty($HTTP_GET_VARS['part']);\r
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
+               }\r
+\r
+               if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL();\r
+               \r
+               $save = $ADODB_CACHE_MODE;\r
+               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;\r
+               $savelog = $this->conn->LogSQL(false);\r
+               $rs =& $this->conn->SelectLimit($sql);\r
+               $this->conn->LogSQL($savelog);\r
+               $ADODB_CACHE_MODE = $save;\r
+               if ($rs) {\r
+                       $s = "\n<h3>Ixora Suspicious SQL</h3>";\r
+                       $s .= $this->tohtml($rs,'expsixora');\r
+               } else \r
+                       $s = '';\r
+               \r
+               if ($s) $s .= '<p>';\r
+               $s .= $this->_SuspiciousSQL();\r
+               return $s;\r
+       }\r
+       \r
+       // code thanks to Ixora. \r
+       // http://www.ixora.com.au/scripts/query_opt.htm\r
+       // requires oracle 8.1.7 or later\r
+       function ExpensiveSQL($numsql = 10)\r
+       {\r
+               $sql = "\r
+select\r
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,\r
+  s.executions  executes,\r
+  p.sql_text\r
+from\r
+  ( \r
+    select\r
+      address,\r
+      disk_reads,\r
+      executions,\r
+      pct,\r
+      rank() over (order by disk_reads desc)  ranking\r
+    from\r
+      (\r
+       select\r
+         address,\r
+         disk_reads,\r
+         executions,\r
+         100 * ratio_to_report(disk_reads) over ()  pct\r
+       from\r
+         sys.v_\$sql\r
+       where\r
+         command_type != 47 and module != 'T.O.A.D.'\r
+      )\r
+    where\r
+      disk_reads > 50 * executions\r
+  )  s,\r
+  sys.v_\$sqltext  p\r
+where\r
+  s.ranking <= $numsql and\r
+  p.address = s.address\r
+order by\r
+  1 desc, s.address, p.piece\r
+";\r
+               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;\r
+               if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) {\r
+                       $partial = empty($HTTP_GET_VARS['part']);       \r
+                       echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
+               }\r
+               \r
+               if (isset($HTTP_GET_VARS['sql'])) {\r
+                        $var =& $this->_ExpensiveSQL();\r
+                        return $var;\r
+               }\r
+               $save = $ADODB_CACHE_MODE;\r
+               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;\r
+               $savelog = $this->conn->LogSQL(false);\r
+               $rs =& $this->conn->Execute($sql);\r
+               $this->conn->LogSQL($savelog);\r
+               $ADODB_CACHE_MODE = $save;\r
+               if ($rs) {\r
+                       $s = "\n<h3>Ixora Expensive SQL</h3>";\r
+                       $s .= $this->tohtml($rs,'expeixora');\r
+               } else \r
+                       $s = '';\r
+               \r
+               \r
+               if ($s) $s .= '<p>';\r
+               $s .= $this->_ExpensiveSQL();\r
+               return $s;\r
+       }\r
+       \r
+}\r
 ?>
\ No newline at end of file
index 2d5912ce5a16787aa84d1c75dff1d6418b01413b..c3d4be5dc69093cb213e48d479ac5b07df69f1e7 100644 (file)
-<?php
-
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. See License.txt. 
-  Set tabs to 4 for best viewing.
-  
-  Latest version is available at http://php.weblogs.com/
-  
-  Library for basic performance monitoring and tuning 
-  
-*/
-
-/*
-       Notice that PostgreSQL has no sql query cache
-*/
-class perf_postgres extends adodb_perf{
-       
-       var $tablesSQL = 
-       "select a.relname as tablename,(a.relpages+CASE WHEN b.relpages is null THEN 0 ELSE b.relpages END+CASE WHEN c.relpages is null THEN 0 ELSE c.relpages END)*8 as size_in_K,a.relfilenode as \"OID\"  from pg_class a left join pg_class b
-               on b.relname = 'pg_toast_'||trim(a.relfilenode) 
-               left join pg_class c on c.relname = 'pg_toast_'||trim(a.relfilenode)||'_index'
-               where a.relname in (select tablename from pg_tables where tablename not like 'pg_%')";
-       
-       var $createTableSQL = "CREATE TABLE adodb_logsql (
-                 created timestamp NOT NULL,
-                 sql0 varchar(250) NOT NULL,
-                 sql1 text NOT NULL,
-                 params text NOT NULL,
-                 tracer text NOT NULL,
-                 timer decimal(16,6) NOT NULL
-               )";     
-       
-       var $settings = array(
-       'Ratios',
-               'statistics collector' => array('RATIO',
-                       "select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",
-                       'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),
-               'data cache hit ratio' => array('RATIO',
-                       "select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'",
-                       '=WarnCacheRatio'),
-       'IO',
-               'data reads' => array('IO',
-               'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',
-               ),
-               'data writes' => array('IO',
-               'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables',
-               'Count of inserts/updates/deletes * coef'),
-
-       'Data Cache',
-               'data cache buffers' => array('DATAC',
-                       "select setting from pg_settings where name='shared_buffers'",
-                       'Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a>'),
-               'cache blocksize' => array('DATAC',
-                       'select 8192',
-                       '(estimate)' ),
-               'data cache size' => array( 'DATAC',
-               "select setting::integer*8192 from pg_settings where name='shared_buffers'",
-                       '' ),
-               'operating system cache size' => array( 'DATA',
-               "select setting::integer*8192 from pg_settings where name='effective_cache_size'",
-                       '(effective cache size)' ),
-       'Memory Usage',
-               'sort buffer size' => array('CACHE',
-                       "select setting::integer*1024 from pg_settings where name='sort_mem'",
-                       'Size of sort buffer (per query)' ),
-       'Connections',
-               'current connections' => array('SESS',
-                       'select count(*) from pg_stat_activity',
-                       ''),
-               'max connections' => array('SESS',
-                       "select setting from pg_settings where name='max_connections'",
-                       ''),
-       'Parameters',
-               'rollback buffers' => array('COST',
-                       "select setting from pg_settings where name='wal_buffers'",
-                       'WAL buffers'),
-               'random page cost' => array('COST',
-                       "select setting from pg_settings where name='random_page_cost'",
-                       'Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a>'),
-               false
-       );
-       
-       function perf_postgres(&$conn)
-       {
-               $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 distinct sql1 from adodb_logsql where sql1 like $sqlq");
-                       if ($arr) {
-                               foreach($arr as $row) {
-                                       $sql = reset($row);
-                                       if (crc32($sql) == $partial) break;
-                               }
-                       }
-               }
-               $sql = str_replace('?',"''",$sql);
-               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
-               $rs = $this->conn->Execute('EXPLAIN '.$sql);
-               $this->conn->LogSQL($save);
-               $s .= '<pre>';
-               if ($rs)
-                       while (!$rs->EOF) {
-                               $s .= reset($rs->fields)."\n";
-                               $rs->MoveNext();
-                       }
-               $s .= '</pre>';
-               $s .= $this->Tracer($sql,$partial);
-               return $s;
-       }
-}
+<?php\r
+\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. See License.txt. \r
+  Set tabs to 4 for best viewing.\r
+  \r
+  Latest version is available at http://adodb.sourceforge.net\r
+  \r
+  Library for basic performance monitoring and tuning \r
+  \r
+*/\r
+\r
+// security - hide paths\r
+if (!defined('ADODB_DIR')) die();\r
+\r
+/*\r
+       Notice that PostgreSQL has no sql query cache\r
+*/\r
+class perf_postgres extends adodb_perf{\r
+       \r
+       var $tablesSQL = \r
+       "select a.relname as tablename,(a.relpages+CASE WHEN b.relpages is null THEN 0 ELSE b.relpages END+CASE WHEN c.relpages is null THEN 0 ELSE c.relpages END)*8 as size_in_K,a.relfilenode as \"OID\"  from pg_class a left join pg_class b\r
+               on b.relname = 'pg_toast_'||trim(a.relfilenode) \r
+               left join pg_class c on c.relname = 'pg_toast_'||trim(a.relfilenode)||'_index'\r
+               where a.relname in (select tablename from pg_tables where tablename not like 'pg_%')";\r
+       \r
+       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
+                 created timestamp NOT NULL,\r
+                 sql0 varchar(250) NOT NULL,\r
+                 sql1 text NOT NULL,\r
+                 params text NOT NULL,\r
+                 tracer text NOT NULL,\r
+                 timer decimal(16,6) NOT NULL\r
+               )";     \r
+       \r
+       var $settings = array(\r
+       'Ratios',\r
+               'statistics collector' => array('RATIO',\r
+                       "select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",\r
+                       'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),\r
+               'data cache hit ratio' => array('RATIO',\r
+                       "select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'",\r
+                       '=WarnCacheRatio'),\r
+       'IO',\r
+               'data reads' => array('IO',\r
+               'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',\r
+               ),\r
+               'data writes' => array('IO',\r
+               'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables',\r
+               'Count of inserts/updates/deletes * coef'),\r
+\r
+       'Data Cache',\r
+               'data cache buffers' => array('DATAC',\r
+                       "select setting from pg_settings where name='shared_buffers'",\r
+                       'Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a>'),\r
+               'cache blocksize' => array('DATAC',\r
+                       'select 8192',\r
+                       '(estimate)' ),\r
+               'data cache size' => array( 'DATAC',\r
+               "select setting::integer*8192 from pg_settings where name='shared_buffers'",\r
+                       '' ),\r
+               'operating system cache size' => array( 'DATA',\r
+               "select setting::integer*8192 from pg_settings where name='effective_cache_size'",\r
+                       '(effective cache size)' ),\r
+       'Memory Usage',\r
+               'sort buffer size' => array('CACHE',\r
+                       "select setting::integer*1024 from pg_settings where name='sort_mem'",\r
+                       'Size of sort buffer (per query)' ),\r
+       'Connections',\r
+               'current connections' => array('SESS',\r
+                       'select count(*) from pg_stat_activity',\r
+                       ''),\r
+               'max connections' => array('SESS',\r
+                       "select setting from pg_settings where name='max_connections'",\r
+                       ''),\r
+       'Parameters',\r
+               'rollback buffers' => array('COST',\r
+                       "select setting from pg_settings where name='wal_buffers'",\r
+                       'WAL buffers'),\r
+               'random page cost' => array('COST',\r
+                       "select setting from pg_settings where name='random_page_cost'",\r
+                       'Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a>'),\r
+               false\r
+       );\r
+       \r
+       function perf_postgres(&$conn)\r
+       {\r
+               $this->conn =& $conn;\r
+       }\r
+       \r
+       function Explain($sql,$partial=false)\r
+       {\r
+               $save = $this->conn->LogSQL(false);\r
+               \r
+               if ($partial) {\r
+                       $sqlq = $this->conn->qstr($sql.'%');\r
+                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
+                       if ($arr) {\r
+                               foreach($arr as $row) {\r
+                                       $sql = reset($row);\r
+                                       if (crc32($sql) == $partial) break;\r
+                               }\r
+                       }\r
+               }\r
+               $sql = str_replace('?',"''",$sql);\r
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
+               $rs = $this->conn->Execute('EXPLAIN '.$sql);\r
+               $this->conn->LogSQL($save);\r
+               $s .= '<pre>';\r
+               if ($rs)\r
+                       while (!$rs->EOF) {\r
+                               $s .= reset($rs->fields)."\n";\r
+                               $rs->MoveNext();\r
+                       }\r
+               $s .= '</pre>';\r
+               $s .= $this->Tracer($sql,$partial);\r
+               return $s;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 8d0f7a7b0404cffd61eea16ca845e2e890c3396e..a40e3b3f60f5a6711cde7ff4f1dac200c0c0a035 100644 (file)
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
- * Whenever there is any discrepancy between the two licenses, 
- * the BSD license will take precedence. 
- *
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com
- *
- * Requires PHP4.01pl2 or later because it uses include_once
-*/
-
-/*
- * Concept from daniel.lucazeau@ajornet.com. 
- *
- * @param db           Adodb database connection
- * @param tables       List of tables to join
- * @rowfields          List of fields to display on each row
- * @colfield           Pivot field to slice and display in columns, if we want to calculate
- *                                             ranges, we pass in an array (see example2)
- * @where                      Where clause. Optional.
- * @aggfield           This is the field to sum. Optional. 
- *                                             Since 2.3.1, if you can use your own aggregate function 
- *                                             instead of SUM, eg. $sumfield = 'AVG(fieldname)';
- * @sumlabel           Prefix to display in sum columns. Optional.
- * @aggfn                      Aggregate function to use (could be AVG, SUM, COUNT)
- * @showcount          Show count of records
- *
- * @returns                    Sql generated
- */
- function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,
-       $aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)
- {
-       if ($aggfield) $hidecnt = true;
-       else $hidecnt = false;
-       
-       
-       //$hidecnt = false;
-       
-       if ($where) $where = "\nWHERE $where";
-       if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");
-       if (!$aggfield) $hidecnt = false;
-       
-       $sel = "$rowfields, ";
-       if (is_array($colfield)) {
-               foreach ($colfield as $k => $v) {
-                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
-                       if ($aggfield)
-                               $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
-               } 
-       } else {
-               foreach ($colarr as $v) {
-                       if (!is_numeric($v)) $vq = $db->qstr($v);
-                       else $vq = $v;
-                       if (strlen($v) == 0     ) $v = 'null';
-                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
-                       if ($aggfield) {
-                               if ($hidecnt) $label = $v;
-                               else $label = "{$v}_$aggfield";
-                               $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
-                       }
-               }
-       }
-       if ($aggfield && $aggfield != '1'){
-               $agg = "$aggfn($aggfield)";
-               $sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";         
-       }
-       
-       if ($showcount)
-               $sel .= "\n\tSUM(1) as Total";
-       else
-               $sel = substr($sel,0,strlen($sel)-2);
-       
-       $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";
-       return $sql;
- }
-
-/* EXAMPLES USING MS NORTHWIND DATABASE */
-if (0) {
-
-# example1
-#
-# Query the main "product" table
-# Set the rows to CompanyName and QuantityPerUnit
-# and the columns to the Categories
-# and define the joins to link to lookup tables 
-# "categories" and "suppliers"
-#
-
- $sql = PivotTableSQL(
-       $gDB,                                                                                   # adodb connection
-       'products p ,categories c ,suppliers s',                # tables
-       'CompanyName,QuantityPerUnit',                                  # row fields
-       'CategoryName',                                                                 # column fields 
-       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
-);
- print "<pre>$sql";
- $rs = $gDB->Execute($sql);
- rs2html($rs);
-/*
-Generated SQL:
-
-SELECT CompanyName,QuantityPerUnit, 
-       SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", 
-       SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", 
-       SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", 
-       SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", 
-       SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", 
-       SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", 
-       SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", 
-       SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", 
-       SUM(1) as Total 
-FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
-GROUP BY CompanyName,QuantityPerUnit
-*/
-//=====================================================================
-
-# example2
-#
-# Query the main "product" table
-# Set the rows to CompanyName and QuantityPerUnit
-# and the columns to the UnitsInStock for different ranges
-# and define the joins to link to lookup tables 
-# "categories" and "suppliers"
-#
- $sql = PivotTableSQL(
-       $gDB,                                                                           # adodb connection
-       'products p ,categories c ,suppliers s',        # tables
-       'CompanyName,QuantityPerUnit',                          # row fields
-                                                                                               # column ranges
-array(                                                                         
-' 0 ' => 'UnitsInStock <= 0',
-"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
-"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
-"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',
-"16+" =>'15 < UnitsInStock'
-),
-       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
-       'UnitsInStock',                                                         # sum this field
-       'Sum'                                                                           # sum label prefix
-);
- print "<pre>$sql";
- $rs = $gDB->Execute($sql);
- rs2html($rs);
- /*
- Generated SQL:
-SELECT CompanyName,QuantityPerUnit, 
-       SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", 
-       SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", 
-       SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", 
-       SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", 
-       SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
-       SUM(UnitsInStock) AS "Sum UnitsInStock", 
-       SUM(1) as Total 
-FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
-GROUP BY CompanyName,QuantityPerUnit
- */
-}
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+ * Requires PHP4.01pl2 or later because it uses include_once\r
+*/\r
+\r
+/*\r
+ * Concept from daniel.lucazeau@ajornet.com. \r
+ *\r
+ * @param db           Adodb database connection\r
+ * @param tables       List of tables to join\r
+ * @rowfields          List of fields to display on each row\r
+ * @colfield           Pivot field to slice and display in columns, if we want to calculate\r
+ *                                             ranges, we pass in an array (see example2)\r
+ * @where                      Where clause. Optional.\r
+ * @aggfield           This is the field to sum. Optional. \r
+ *                                             Since 2.3.1, if you can use your own aggregate function \r
+ *                                             instead of SUM, eg. $sumfield = 'AVG(fieldname)';\r
+ * @sumlabel           Prefix to display in sum columns. Optional.\r
+ * @aggfn                      Aggregate function to use (could be AVG, SUM, COUNT)\r
+ * @showcount          Show count of records\r
+ *\r
+ * @returns                    Sql generated\r
+ */\r
\r
+ function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,\r
+       $aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)\r
+ {\r
+       if ($aggfield) $hidecnt = true;\r
+       else $hidecnt = false;\r
+       \r
+       \r
+       //$hidecnt = false;\r
+       \r
+       if ($where) $where = "\nWHERE $where";\r
+       if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");\r
+       if (!$aggfield) $hidecnt = false;\r
+       \r
+       $sel = "$rowfields, ";\r
+       if (is_array($colfield)) {\r
+               foreach ($colfield as $k => $v) {\r
+                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";\r
+                       if ($aggfield)\r
+                               $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";\r
+               } \r
+       } else {\r
+               foreach ($colarr as $v) {\r
+                       if (!is_numeric($v)) $vq = $db->qstr($v);\r
+                       else $vq = $v;\r
+                       if (strlen($v) == 0     ) $v = 'null';\r
+                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";\r
+                       if ($aggfield) {\r
+                               if ($hidecnt) $label = $v;\r
+                               else $label = "{$v}_$aggfield";\r
+                               $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";\r
+                       }\r
+               }\r
+       }\r
+       if ($aggfield && $aggfield != '1'){\r
+               $agg = "$aggfn($aggfield)";\r
+               $sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";         \r
+       }\r
+       \r
+       if ($showcount)\r
+               $sel .= "\n\tSUM(1) as Total";\r
+       else\r
+               $sel = substr($sel,0,strlen($sel)-2);\r
+       \r
+       $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";\r
+       return $sql;\r
+ }\r
+\r
+/* EXAMPLES USING MS NORTHWIND DATABASE */\r
+if (0) {\r
+\r
+# example1\r
+#\r
+# Query the main "product" table\r
+# Set the rows to CompanyName and QuantityPerUnit\r
+# and the columns to the Categories\r
+# and define the joins to link to lookup tables \r
+# "categories" and "suppliers"\r
+#\r
+\r
+ $sql = PivotTableSQL(\r
+       $gDB,                                                                                   # adodb connection\r
+       'products p ,categories c ,suppliers s',                # tables\r
+       'CompanyName,QuantityPerUnit',                                  # row fields\r
+       'CategoryName',                                                                 # column fields \r
+       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where\r
+);\r
+ print "<pre>$sql";\r
+ $rs = $gDB->Execute($sql);\r
+ rs2html($rs);\r
\r
+/*\r
+Generated SQL:\r
+\r
+SELECT CompanyName,QuantityPerUnit, \r
+       SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", \r
+       SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", \r
+       SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", \r
+       SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", \r
+       SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", \r
+       SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", \r
+       SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", \r
+       SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", \r
+       SUM(1) as Total \r
+FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID \r
+GROUP BY CompanyName,QuantityPerUnit\r
+*/\r
+//=====================================================================\r
+\r
+# example2\r
+#\r
+# Query the main "product" table\r
+# Set the rows to CompanyName and QuantityPerUnit\r
+# and the columns to the UnitsInStock for different ranges\r
+# and define the joins to link to lookup tables \r
+# "categories" and "suppliers"\r
+#\r
+ $sql = PivotTableSQL(\r
+       $gDB,                                                                           # adodb connection\r
+       'products p ,categories c ,suppliers s',        # tables\r
+       'CompanyName,QuantityPerUnit',                          # row fields\r
+                                                                                               # column ranges\r
+array(                                                                         \r
+' 0 ' => 'UnitsInStock <= 0',\r
+"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',\r
+"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',\r
+"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',\r
+"16+" =>'15 < UnitsInStock'\r
+),\r
+       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where\r
+       'UnitsInStock',                                                         # sum this field\r
+       'Sum'                                                                           # sum label prefix\r
+);\r
+ print "<pre>$sql";\r
+ $rs = $gDB->Execute($sql);\r
+ rs2html($rs);\r
+ /*\r
+ Generated SQL:\r
\r
+SELECT CompanyName,QuantityPerUnit, \r
+       SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", \r
+       SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", \r
+       SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", \r
+       SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", \r
+       SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",\r
+       SUM(UnitsInStock) AS "Sum UnitsInStock", \r
+       SUM(1) as Total \r
+FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID \r
+GROUP BY CompanyName,QuantityPerUnit\r
+ */\r
+}\r
 ?>
\ No newline at end of file
index baa71153c78c01b2b3c08094105d3f230d62820e..cca9c96b165884ace6caf14ad5c67c9651c0b558 100644 (file)
@@ -22,8 +22,9 @@ We hope more people will contribute drivers to support other databases.
 \r
 >> Documentation and Examples\r
 \r
-Refer to readme.htm for full documentation and examples. There is also a \r
-tutorial tute.htm that contrasts ADODB code with mysql code.\r
+Refer to the adodb/docs directory for full documentation and examples. \r
+There is also a  tutorial tute.htm that contrasts ADODB code with \r
+mysql code.\r
 \r
 \r
 >>> Files\r
index 8f377cf1c90d4770054b8101c67a10b0b136e1bc..c4b5ad04ad7afb48b09e9d9246da4cb4fa9f2b21 100644 (file)
@@ -1,54 +1,54 @@
-<?php
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
- * Whenever there is any discrepancy between the two licenses, 
- * the BSD license will take precedence. 
- *
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com
- *
- * Requires PHP4.01pl2 or later because it uses include_once
-*/
-
-/*
-       Filter all fields and all rows in a recordset and returns the 
-       processed recordset. We scroll to the beginning of the new recordset
-       after processing.
-       
-       We pass a recordset and function name to RSFilter($rs,'rowfunc');
-       and the function will be called multiple times, once
-       for each row in the recordset. The function will be passed
-       an array containing one row repeatedly.
-       
-       Example: 
-       
-       // ucwords() every element in the recordset
-       function do_ucwords(&$arr,$rs)
-       {
-               foreach($arr as $k => $v) {
-                       $arr[$k] = ucwords($v);
-               }
-       }
-       $rs = RSFilter($rs,'do_ucwords');
- */
-function &RSFilter($rs,$fn)
-{
-       if ($rs->databaseType != 'array') {
-               if (!$rs->connection) return false;
-               
-               $rs = &$rs->connection->_rs2rs($rs);
-       }
-       $rows = $rs->RecordCount();
-       for ($i=0; $i < $rows; $i++) {
-               $fn($rs->_array[$i],$rs);
-       }
-       if (!$rs->EOF) {
-               $rs->_currentRow = 0;
-               $rs->fields = $rs->_array[0];
-       }
-       
-       return $rs;
-}
+<?php\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+ * Requires PHP4.01pl2 or later because it uses include_once\r
+*/\r
+\r
+/*\r
+       Filter all fields and all rows in a recordset and returns the \r
+       processed recordset. We scroll to the beginning of the new recordset\r
+       after processing.\r
+       \r
+       We pass a recordset and function name to RSFilter($rs,'rowfunc');\r
+       and the function will be called multiple times, once\r
+       for each row in the recordset. The function will be passed\r
+       an array containing one row repeatedly.\r
+       \r
+       Example: \r
+       \r
+       // ucwords() every element in the recordset\r
+       function do_ucwords(&$arr,$rs)\r
+       {\r
+               foreach($arr as $k => $v) {\r
+                       $arr[$k] = ucwords($v);\r
+               }\r
+       }\r
+       $rs = RSFilter($rs,'do_ucwords');\r
+ */\r
+function &RSFilter($rs,$fn)\r
+{\r
+       if ($rs->databaseType != 'array') {\r
+               if (!$rs->connection) return false;\r
+               \r
+               $rs = &$rs->connection->_rs2rs($rs);\r
+       }\r
+       $rows = $rs->RecordCount();\r
+       for ($i=0; $i < $rows; $i++) {\r
+               $fn($rs->_array[$i],$rs);\r
+       }\r
+       if (!$rs->EOF) {\r
+               $rs->_currentRow = 0;\r
+               $rs->fields = $rs->_array[0];\r
+       }\r
+       \r
+       return $rs;\r
+}\r
 ?>
\ No newline at end of file
index 57ee71cbf1903bd1f4c486b8e93e3d4e88969518..0a8f8e1ba76ef90b09036687ddde155d9bc7012c 100644 (file)
@@ -1,98 +1,98 @@
-<?php
-
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 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. 
- */
-/* Documentation on usage is at http://php.weblogs.com/adodb_csv
- *
- * Legal query string parameters:
- * 
- * sql = holds sql string
- * nrows = number of rows to return 
- * offset = skip offset rows of data
- * fetch = $ADODB_FETCH_MODE
- * 
- * example:
- *
- * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2
- */
-
-
-/* 
- * Define the IP address you want to accept requests from 
- * as a security measure. If blank we accept anyone promisciously!
- */
-$ACCEPTIP = '';
-
-/*
- * Connection parameters
- */
-$driver = 'mysql';
-$host = 'localhost'; // DSN for odbc
-$uid = 'root';
-$pwd = '';
-$database = 'test';
-
-/*============================ DO NOT MODIFY BELOW HERE =================================*/
-// $sep must match csv2rs() in adodb.inc.php
-$sep = ' :::: ';
-
-include('./adodb.inc.php');
-include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
-
-function err($s)
-{
-       die('**** '.$s.' ');
-}
-
-// undo stupid magic quotes
-function undomq(&$m) 
-{
-       if (get_magic_quotes_gpc()) {
-               // undo the damage
-               $m = str_replace('\\\\','\\',$m);
-               $m = str_replace('\"','"',$m);
-               $m = str_replace('\\\'','\'',$m);
-               
-       }
-       return $m;
-}
-
-///////////////////////////////////////// DEFINITIONS
-
-
-$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"]; 
-if (empty($HTTP_GET_VARS['sql'])) err('No SQL');
-
-if (!empty($ACCEPTIP))
- if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) 
-       err("Unauthorised client: '$remote'");
-
-
-$conn = &ADONewConnection($driver);
-
-if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
-$sql = undomq($HTTP_GET_VARS['sql']);
-
-if (isset($HTTP_GET_VARS['fetch']))
-       $ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];
-       
-if (isset($HTTP_GET_VARS['nrows'])) {
-       $nrows = $HTTP_GET_VARS['nrows'];
-       $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;
-       $rs = $conn->SelectLimit($sql,$nrows,$offset);
-} else 
-       $rs = $conn->Execute($sql);
-if ($rs){ 
-       //$rs->timeToLive = 1;
-       echo _rs2serialize($rs,$conn,$sql);
-       $rs->Close();
-} else
-       err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
-
+<?php\r
+\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ */\r
\r
+/* Documentation on usage is at http://php.weblogs.com/adodb_csv\r
+ *\r
+ * Legal query string parameters:\r
+ * \r
+ * sql = holds sql string\r
+ * nrows = number of rows to return \r
+ * offset = skip offset rows of data\r
+ * fetch = $ADODB_FETCH_MODE\r
+ * \r
+ * example:\r
+ *\r
+ * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2\r
+ */\r
+\r
+\r
+/* \r
+ * Define the IP address you want to accept requests from \r
+ * as a security measure. If blank we accept anyone promisciously!\r
+ */\r
+$ACCEPTIP = '';\r
+\r
+/*\r
+ * Connection parameters\r
+ */\r
+$driver = 'mysql';\r
+$host = 'localhost'; // DSN for odbc\r
+$uid = 'root';\r
+$pwd = '';\r
+$database = 'test';\r
+\r
+/*============================ DO NOT MODIFY BELOW HERE =================================*/\r
+// $sep must match csv2rs() in adodb.inc.php\r
+$sep = ' :::: ';\r
+\r
+include('./adodb.inc.php');\r
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
+\r
+function err($s)\r
+{\r
+       die('**** '.$s.' ');\r
+}\r
+\r
+// undo stupid magic quotes\r
+function undomq(&$m) \r
+{\r
+       if (get_magic_quotes_gpc()) {\r
+               // undo the damage\r
+               $m = str_replace('\\\\','\\',$m);\r
+               $m = str_replace('\"','"',$m);\r
+               $m = str_replace('\\\'','\'',$m);\r
+               \r
+       }\r
+       return $m;\r
+}\r
+\r
+///////////////////////////////////////// DEFINITIONS\r
+\r
+\r
+$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"]; \r
\r
+if (empty($HTTP_GET_VARS['sql'])) err('No SQL');\r
+\r
+if (!empty($ACCEPTIP))\r
+ if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) \r
+       err("Unauthorised client: '$remote'");\r
+\r
+\r
+$conn = &ADONewConnection($driver);\r
+\r
+if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());\r
+$sql = undomq($HTTP_GET_VARS['sql']);\r
+\r
+if (isset($HTTP_GET_VARS['fetch']))\r
+       $ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];\r
+       \r
+if (isset($HTTP_GET_VARS['nrows'])) {\r
+       $nrows = $HTTP_GET_VARS['nrows'];\r
+       $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;\r
+       $rs = $conn->SelectLimit($sql,$nrows,$offset);\r
+} else \r
+       $rs = $conn->Execute($sql);\r
+if ($rs){ \r
+       //$rs->timeToLive = 1;\r
+       echo _rs2serialize($rs,$conn,$sql);\r
+       $rs->Close();\r
+} else\r
+       err($conn->ErrorNo(). $sep .$conn->ErrorMsg());\r
+\r
 ?>
\ No newline at end of file
index 8a7e93953915e9fbea6b09438effdcbfa42ecd7a..a0d19eb071b46fd4ba1585a3d7caf8fb42c54d22 100644 (file)
@@ -12,6 +12,9 @@ V4.01 23 Oct 2003  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights rese
 \r
 */\r
 \r
+// security - hide paths\r
+if (!defined('ADODB_SESSION')) die();\r
+\r
 include_once ADODB_SESSION . '/crypt.inc.php';\r
 \r
 /**\r
index 7cba4f854e308bc294f12481bdee8dd06b8e9648..d570c68c84fc6b22c8d8d629f3bd30e247c918a3 100644 (file)
@@ -581,6 +581,7 @@ class ADODB_Session {
                }\r
 \r
                if (!$clob) {   // no lobs, simply use replace()\r
+                       $arr[$data] = $conn->qstr($val);\r
                        $rs = $conn->Replace($table, $arr, 'sesskey', $autoQuote = true);\r
                        ADODB_Session::_dumprs($rs);\r
                } else {\r
@@ -680,8 +681,8 @@ class ADODB_Session {
                        if (!$rs->EOF) {\r
                                $ref = $rs->fields[0];\r
                                $key = $rs->fields[1];\r
-                               assert('$ref');\r
-                               assert('$key');\r
+                               //assert('$ref');\r
+                               //assert('$key');\r
                                $fn($ref, $key);\r
                        }\r
                        $rs->Close();\r
index 53636cbf45d43b0afcf78b7898029faa94cc9bf8..f4a208bc5499a2e2f322091f6a6e7eafbfc1b37f 100644 (file)
@@ -1,84 +1,84 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
-       <title>ADODB Benchmarks</title>
-</head> 
-
-<body>
-<?php 
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-  
-  Benchmark code to test the speed to the ADODB library with different databases.
-  This is a simplistic benchmark to be used as the basis for further testing.
-  It should not be used as proof of the superiority of one database over the other.
-*/ 
-$testmssql = true;
-//$testvfp = true;
-$testoracle = true;
-$testado = true; 
-$testibase = true;
-$testaccess = true;
-$testmysql = true;
-$testsqlite = true;;
-
-set_time_limit(240); // increase timeout
-
-include("../tohtml.inc.php");
-include("../adodb.inc.php");
-
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
-{
-GLOBAL $ADODB_version,$ADODB_FETCH_MODE;
-
-       adodb_backtrace();
-       
-       $max = 100;
-       $sql = 'select * from ADOXYZ';
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       
-       //print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";
-       
-       // perform query once to cache results so we are only testing throughput 
-       $rs = $db->Execute($sql);
-       if (!$rs){
-               print "Error in recordset<p>";
-               return;
-       }       
-       $arr = $rs->GetArray();
-       //$db->debug = true;
-       global $ADODB_COUNTRECS;
-       $ADODB_COUNTRECS = false;
-       $start = microtime();
-       for ($i=0; $i < $max; $i++) {
-               $rs =& $db->Execute($sql);      
-               $arr =& $rs->GetArray();
-          //            print $arr[0][1];
-       }
-       $end =  microtime();
-       $start = explode(' ',$start);
-       $end = explode(' ',$end);
-       
-       //print_r($start);
-       //print_r($end);
-       
-         //  print_r($arr);
-       $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);
-       printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));
-       flush();
-
-
-               //$db->Close();
-}
-include("testdatabases.inc.php");
-
-?>
-
-
-</body>
-</html>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
+\r
+<html>\r
+<head>\r
+       <title>ADODB Benchmarks</title>\r
+</head> \r
+\r
+<body>\r
+<?php \r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  \r
+  Benchmark code to test the speed to the ADODB library with different databases.\r
+  This is a simplistic benchmark to be used as the basis for further testing.\r
+  It should not be used as proof of the superiority of one database over the other.\r
+*/ \r
\r
+$testmssql = true;\r
+//$testvfp = true;\r
+$testoracle = true;\r
+$testado = true; \r
+$testibase = true;\r
+$testaccess = true;\r
+$testmysql = true;\r
+$testsqlite = true;;\r
+\r
+set_time_limit(240); // increase timeout\r
+\r
+include("../tohtml.inc.php");\r
+include("../adodb.inc.php");\r
+\r
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
+{\r
+GLOBAL $ADODB_version,$ADODB_FETCH_MODE;\r
+\r
+       adodb_backtrace();\r
+       \r
+       $max = 100;\r
+       $sql = 'select * from ADOXYZ';\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       \r
+       //print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";\r
+       \r
+       // perform query once to cache results so we are only testing throughput \r
+       $rs = $db->Execute($sql);\r
+       if (!$rs){\r
+               print "Error in recordset<p>";\r
+               return;\r
+       }       \r
+       $arr = $rs->GetArray();\r
+       //$db->debug = true;\r
+       global $ADODB_COUNTRECS;\r
+       $ADODB_COUNTRECS = false;\r
+       $start = microtime();\r
+       for ($i=0; $i < $max; $i++) {\r
+               $rs =& $db->Execute($sql);      \r
+               $arr =& $rs->GetArray();\r
+          //            print $arr[0][1];\r
+       }\r
+       $end =  microtime();\r
+       $start = explode(' ',$start);\r
+       $end = explode(' ',$end);\r
+       \r
+       //print_r($start);\r
+       //print_r($end);\r
+       \r
+         //  print_r($arr);\r
+       $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);\r
+       printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));\r
+       flush();\r
+\r
+\r
+               //$db->Close();\r
+}\r
+include("testdatabases.inc.php");\r
+\r
+?>\r
+\r
+\r
+</body>\r
+</html>\r
index c7cca950351e6df2fa5fe08c11d09b0fef37e2c9..6c76389e5c301ca0748750ad08c5d6d83146169a 100644 (file)
-<html>
-<body bgcolor=white>
-<?php
-/** 
- * V4.20 22 Feb 2004  (c) 2001-2002 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
- * 
- * set tabs to 8
- */
- // documentation on usage is at http://php.weblogs.com/adodb_csv
-include('../adodb.inc.php');
-include('../tohtml.inc.php');
-
- function &send2server($url,$sql)
- {
-       $url .= '?sql='.urlencode($sql);
-       print "<p>$url</p>";
-       $rs = csv2rs($url,$err);
-       if ($err) print $err;
-       return $rs;
- }
- function print_pre($s)
- {
-       print "<pre>";print_r($s);print "</pre>";
- }
-
-
-$serverURL = 'http://localhost/php/phplens/adodb/server.php';
-$testhttp = false;
-
-$sql1 = "insertz into products (productname) values ('testprod 1')";
-$sql2 = "insert into products (productname) values ('testprod 1')";
-$sql3 = "insert into products (productname) values ('testprod 2')";
-$sql4 = "delete from products where productid>80";
-$sql5 = 'select * from products';
-       
-if ($testhttp) {
-       print "<a href=#c>Client Driver Tests</a><p>";
-       print "<h3>Test Error</h3>";
-       $rs = send2server($serverURL,$sql1);
-       print_pre($rs);
-       print "<hr>";
-       
-       print "<h3>Test Insert</h3>";
-       
-       $rs = send2server($serverURL,$sql2);
-       print_pre($rs);
-       print "<hr>";
-       
-       print "<h3>Test Insert2</h3>";
-       
-       $rs = send2server($serverURL,$sql3);
-       print_pre($rs);
-       print "<hr>";
-       
-       print "<h3>Test Delete</h3>";
-       
-       $rs = send2server($serverURL,$sql4);
-       print_pre($rs);
-       print "<hr>";
-       
-       
-       print "<h3>Test Select</h3>";
-       $rs = send2server($serverURL,$sql5);
-       if ($rs) rs2html($rs);
-       
-       print "<hr>";
-}
-
-
-print "<a name=c><h1>CLIENT Driver Tests</h1>";
-$conn = ADONewConnection('csv');
-$conn->Connect($serverURL);
-$conn->debug = true;
-
-print "<h3>Bad SQL</h3>";
-
-$rs = $conn->Execute($sql1);
-
-print "<h3>Insert SQL 1</h3>";
-$rs = $conn->Execute($sql2);
-
-print "<h3>Insert SQL 2</h3>";
-$rs = $conn->Execute($sql3);
-
-print "<h3>Select SQL</h3>";
-$rs = $conn->Execute($sql5);
-if ($rs) rs2html($rs);
-
-print "<h3>Delete SQL</h3>";
-$rs = $conn->Execute($sql4);
-
-print "<h3>Select SQL</h3>";
-$rs = $conn->Execute($sql5);
-if ($rs) rs2html($rs);
-
-
-/* EXPECTED RESULTS FOR HTTP TEST:
-
-Test Insert
-http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
-
-adorecordset Object
-(
-       [dataProvider] => native
-       [fields] => 
-       [blobSize] => 64
-       [canSeek] => 
-       [EOF] => 1
-       [emptyTimeStamp] =>  
-       [emptyDate] =>  
-       [debug] => 
-       [timeToLive] => 0
-       [bind] => 
-       [_numOfRows] => -1
-       [_numOfFields] => 0
-       [_queryID] => 1
-       [_currentRow] => -1
-       [_closed] => 
-       [_inited] => 
-       [sql] => insert into products (productname) values ('testprod')
-       [affectedrows] => 1
-       [insertid] => 81
-)
-
-
---------------------------------------------------------------------------------
-
-Test Insert2
-http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
-
-adorecordset Object
-(
-       [dataProvider] => native
-       [fields] => 
-       [blobSize] => 64
-       [canSeek] => 
-       [EOF] => 1
-       [emptyTimeStamp] =>  
-       [emptyDate] =>  
-       [debug] => 
-       [timeToLive] => 0
-       [bind] => 
-       [_numOfRows] => -1
-       [_numOfFields] => 0
-       [_queryID] => 1
-       [_currentRow] => -1
-       [_closed] => 
-       [_inited] => 
-       [sql] => insert into products (productname) values ('testprod')
-       [affectedrows] => 1
-       [insertid] => 82
-)
-
-
---------------------------------------------------------------------------------
-
-Test Delete
-http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80
-
-adorecordset Object
-(
-       [dataProvider] => native
-       [fields] => 
-       [blobSize] => 64
-       [canSeek] => 
-       [EOF] => 1
-       [emptyTimeStamp] =>  
-       [emptyDate] =>  
-       [debug] => 
-       [timeToLive] => 0
-       [bind] => 
-       [_numOfRows] => -1
-       [_numOfFields] => 0
-       [_queryID] => 1
-       [_currentRow] => -1
-       [_closed] => 
-       [_inited] => 
-       [sql] => delete from products where productid>80
-       [affectedrows] => 2
-       [insertid] => 0
-)
-
-[more stuff deleted]
- .
- . 
- .
-*/
-?>
+<html>\r
+<body bgcolor=white>\r
+<?php\r
+/** \r
+ * V4.50 6 July 2004  (c) 2001-2002 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+ * \r
+ * set tabs to 8\r
+ */\r
\r
+ // documentation on usage is at http://php.weblogs.com/adodb_csv\r
\r
+include('../adodb.inc.php');\r
+include('../tohtml.inc.php');\r
+\r
+ function &send2server($url,$sql)\r
+ {\r
+       $url .= '?sql='.urlencode($sql);\r
+       print "<p>$url</p>";\r
+       $rs = csv2rs($url,$err);\r
+       if ($err) print $err;\r
+       return $rs;\r
+ }\r
\r
+ function print_pre($s)\r
+ {\r
+       print "<pre>";print_r($s);print "</pre>";\r
+ }\r
+\r
+\r
+$serverURL = 'http://localhost/php/phplens/adodb/server.php';\r
+$testhttp = false;\r
+\r
+$sql1 = "insertz into products (productname) values ('testprod 1')";\r
+$sql2 = "insert into products (productname) values ('testprod 1')";\r
+$sql3 = "insert into products (productname) values ('testprod 2')";\r
+$sql4 = "delete from products where productid>80";\r
+$sql5 = 'select * from products';\r
+       \r
+if ($testhttp) {\r
+       print "<a href=#c>Client Driver Tests</a><p>";\r
+       print "<h3>Test Error</h3>";\r
+       $rs = send2server($serverURL,$sql1);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Insert</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql2);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Insert2</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql3);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       print "<h3>Test Delete</h3>";\r
+       \r
+       $rs = send2server($serverURL,$sql4);\r
+       print_pre($rs);\r
+       print "<hr>";\r
+       \r
+       \r
+       print "<h3>Test Select</h3>";\r
+       $rs = send2server($serverURL,$sql5);\r
+       if ($rs) rs2html($rs);\r
+       \r
+       print "<hr>";\r
+}\r
+\r
+\r
+print "<a name=c><h1>CLIENT Driver Tests</h1>";\r
+$conn = ADONewConnection('csv');\r
+$conn->Connect($serverURL);\r
+$conn->debug = true;\r
+\r
+print "<h3>Bad SQL</h3>";\r
+\r
+$rs = $conn->Execute($sql1);\r
+\r
+print "<h3>Insert SQL 1</h3>";\r
+$rs = $conn->Execute($sql2);\r
+\r
+print "<h3>Insert SQL 2</h3>";\r
+$rs = $conn->Execute($sql3);\r
+\r
+print "<h3>Select SQL</h3>";\r
+$rs = $conn->Execute($sql5);\r
+if ($rs) rs2html($rs);\r
+\r
+print "<h3>Delete SQL</h3>";\r
+$rs = $conn->Execute($sql4);\r
+\r
+print "<h3>Select SQL</h3>";\r
+$rs = $conn->Execute($sql5);\r
+if ($rs) rs2html($rs);\r
+\r
+\r
+/* EXPECTED RESULTS FOR HTTP TEST:\r
+\r
+Test Insert\r
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
+\r
+adorecordset Object\r
+(\r
+       [dataProvider] => native\r
+       [fields] => \r
+       [blobSize] => 64\r
+       [canSeek] => \r
+       [EOF] => 1\r
+       [emptyTimeStamp] =>  \r
+       [emptyDate] =>  \r
+       [debug] => \r
+       [timeToLive] => 0\r
+       [bind] => \r
+       [_numOfRows] => -1\r
+       [_numOfFields] => 0\r
+       [_queryID] => 1\r
+       [_currentRow] => -1\r
+       [_closed] => \r
+       [_inited] => \r
+       [sql] => insert into products (productname) values ('testprod')\r
+       [affectedrows] => 1\r
+       [insertid] => 81\r
+)\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+Test Insert2\r
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
+\r
+adorecordset Object\r
+(\r
+       [dataProvider] => native\r
+       [fields] => \r
+       [blobSize] => 64\r
+       [canSeek] => \r
+       [EOF] => 1\r
+       [emptyTimeStamp] =>  \r
+       [emptyDate] =>  \r
+       [debug] => \r
+       [timeToLive] => 0\r
+       [bind] => \r
+       [_numOfRows] => -1\r
+       [_numOfFields] => 0\r
+       [_queryID] => 1\r
+       [_currentRow] => -1\r
+       [_closed] => \r
+       [_inited] => \r
+       [sql] => insert into products (productname) values ('testprod')\r
+       [affectedrows] => 1\r
+       [insertid] => 82\r
+)\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+Test Delete\r
+http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80\r
+\r
+adorecordset Object\r
+(\r
+       [dataProvider] => native\r
+       [fields] => \r
+       [blobSize] => 64\r
+       [canSeek] => \r
+       [EOF] => 1\r
+       [emptyTimeStamp] =>  \r
+       [emptyDate] =>  \r
+       [debug] => \r
+       [timeToLive] => 0\r
+       [bind] => \r
+       [_numOfRows] => -1\r
+       [_numOfFields] => 0\r
+       [_queryID] => 1\r
+       [_currentRow] => -1\r
+       [_closed] => \r
+       [_inited] => \r
+       [sql] => delete from products where productid>80\r
+       [affectedrows] => 2\r
+       [insertid] => 0\r
+)\r
+\r
+[more stuff deleted]\r
+ .\r
+ . \r
+ .\r
+*/\r
+?>\r
index 8a6563de1ce1cd18d5603619798fc2701cc45ace..977aced280ef03dca958d37864a0fa86e3d47909 100644 (file)
-<?php
-/*
-
-  V4.20 22 Feb 2004  (c) 2000-2004 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.
-
-*/
-
-error_reporting(E_ALL);
-include_once('../adodb.inc.php');
-
-foreach(array('sybase','mysql','access','oci8','postgres','odbc_mssql','odbc','sybase','firebird','informix','db2') as $dbType) {
-       echo "<h3>$dbType</h3><p>";
-       $db = NewADOConnection($dbType);
-       $dict = NewDataDictionary($db);
-
-       if (!$dict) continue;
-       $dict->debug = 1;
-       
-       $opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS');
-       
-/*     $flds = array(
-               array('id',     'I',                                                            
-                                                       'AUTO','KEY'),
-                                                       
-               array('name' => 'firstname', 'type' => 'varchar','size' => 30,
-                                                       'DEFAULT'=>'Joan'),
-                                                       
-               array('lastname','varchar',28,
-                                                       'DEFAULT'=>'Chen','key'),
-                                                       
-               array('averylonglongfieldname','X',1024,
-                                                       'NOTNULL','default' => 'test'),
-                                                       
-               array('price','N','7.2',
-                                                       'NOTNULL','default' => '0.00'),
-                                                       
-               array('MYDATE', 'D', 
-                                                       'DEFDATE'),
-               array('TS','T',
-                                                       'DEFTIMESTAMP')
-       );*/
-       
-       $flds = "
-ID            I           AUTO KEY,
-FIRSTNAME     VARCHAR(30) DEFAULT 'Joan',
-LASTNAME      VARCHAR(28) DEFAULT 'Chen' key,
-averylonglongfieldname X(1024) DEFAULT 'test',
-price         N(7.2)  DEFAULT '0.00',
-MYDATE        D      DEFDATE,
-BIGFELLOW     X      NOTNULL,
-TS            T      DEFTIMESTAMP";
-
-
-       $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));
-       $dict->SetSchema('KUTU');
-       
-       $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));
-       $sqla =& array_merge($sqla,$sqli);
-       
-       $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));
-       $sqla =& array_merge($sqla,$sqli);
-       $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));
-       $sqla =& array_merge($sqla,$sqli);
-       
-       $addflds = array(array('height', 'F'),array('weight','F'));
-       $sqli = $dict->AddColumnSQL('testtable',$addflds);
-       $sqla =& array_merge($sqla,$sqli);
-       $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));
-       $sqli = $dict->AlterColumnSQL('testtable',$addflds);
-       $sqla =& array_merge($sqla,$sqli);
-       
-       
-       printsqla($dbType,$sqla);
-       
-       if (file_exists('d:\inetpub\wwwroot\php\phplens\adodb\adodb.inc.php'))
-       if ($dbType == 'mysql') {
-               $db->Connect('localhost', "root", "", "test");
-               $dict->SetSchema('');
-               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
-               if ($sqla2) printsqla($dbType,$sqla2);
-       }
-               if ($dbType == 'postgres') {
-               $db->Connect('localhost', "tester", "test", "test");
-               $dict->SetSchema('');
-               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
-               if ($sqla2) printsqla($dbType,$sqla2);
-       }
-       
-}
-
-function printsqla($dbType,$sqla)
-{
-       print "<pre>";
-       //print_r($dict->MetaTables());
-       foreach($sqla as $s) {
-               $s = htmlspecialchars($s);
-               print "$s;\n";
-               if ($dbType == 'oci8') print "/\n";
-       }
-       print "</pre><hr>";
-}
-
-/***
-
-Generated SQL:
-
-mysql
-
-CREATE DATABASE KUTU;
-DROP TABLE KUTU.testtable;
-CREATE TABLE KUTU.testtable (
-id               INTEGER NOT NULL AUTO_INCREMENT,
-firstname        VARCHAR(30) DEFAULT 'Joan',
-lastname         VARCHAR(28) NOT NULL DEFAULT 'Chen',
-averylonglongfieldname LONGTEXT NOT NULL,
-price            NUMERIC(7,2) NOT NULL DEFAULT 0.00,
-MYDATE           DATE DEFAULT CURDATE(),
-                 PRIMARY KEY (id, lastname)
-)TYPE=ISAM;
-CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
-ALTER TABLE KUTU.testtable  ADD height           DOUBLE;
-ALTER TABLE KUTU.testtable  ADD weight           DOUBLE;
-ALTER TABLE KUTU.testtable  MODIFY COLUMN height           DOUBLE NOT NULL;
-ALTER TABLE KUTU.testtable  MODIFY COLUMN weight           DOUBLE NOT NULL;
-
-
---------------------------------------------------------------------------------
-
-oci8
-
-CREATE USER KUTU IDENTIFIED BY tiger;
-/
-GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;
-/
-DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;
-/
-CREATE TABLE KUTU.testtable (
-id               NUMBER(16) NOT NULL,
-firstname        VARCHAR(30) DEFAULT 'Joan',
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
-averylonglongfieldname CLOB NOT NULL,
-price            NUMBER(7,2) DEFAULT 0.00 NOT NULL,
-MYDATE           DATE DEFAULT TRUNC(SYSDATE),
-                 PRIMARY KEY (id, lastname)
-)TABLESPACE USERS;
-/
-DROP SEQUENCE KUTU.SEQ_testtable;
-/
-CREATE SEQUENCE KUTU.SEQ_testtable;
-/
-CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable 
-               FOR EACH ROW
-               BEGIN
-                 select KUTU.SEQ_testtable.nextval into :new.id from dual;
-               END;
-/
-CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);
-/
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
-/
-ALTER TABLE testtable ADD (
- height           NUMBER,
- weight           NUMBER);
-/
-ALTER TABLE testtable MODIFY(
- height           NUMBER NOT NULL,
- weight           NUMBER NOT NULL);
-/
-
-
---------------------------------------------------------------------------------
-
-postgres
-AlterColumnSQL not supported for PostgreSQL
-
-
-CREATE DATABASE KUTU LOCATION='/u01/postdata';
-DROP TABLE KUTU.testtable;
-CREATE TABLE KUTU.testtable (
-id               SERIAL,
-firstname        VARCHAR(30) DEFAULT 'Joan',
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
-averylonglongfieldname TEXT NOT NULL,
-price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
-MYDATE           DATE DEFAULT CURRENT_DATE,
-                 PRIMARY KEY (id, lastname)
-);
-CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
-ALTER TABLE KUTU.testtable  ADD height           FLOAT8;
-ALTER TABLE KUTU.testtable  ADD weight           FLOAT8;
-
-
---------------------------------------------------------------------------------
-
-odbc_mssql
-
-CREATE DATABASE KUTU;
-DROP TABLE KUTU.testtable;
-CREATE TABLE KUTU.testtable (
-id               INT IDENTITY(1,1) NOT NULL,
-firstname        VARCHAR(30) DEFAULT 'Joan',
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
-averylonglongfieldname TEXT NOT NULL,
-price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
-MYDATE           DATETIME DEFAULT GetDate(),
-                 PRIMARY KEY (id, lastname)
-);
-CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
-ALTER TABLE KUTU.testtable  ADD
- height           REAL,
- weight           REAL;
-ALTER TABLE KUTU.testtable  ALTER COLUMN height           REAL NOT NULL;
-ALTER TABLE KUTU.testtable  ALTER COLUMN weight           REAL NOT NULL;
-
-
---------------------------------------------------------------------------------
-*/
-
-echo "<h1>Test XML Schema</h1>";
-$ff = file('xmlschema.xml');
-echo "<pre>";
-foreach($ff as $xml) echo htmlspecialchars($xml);
-echo "</pre>";
-include_once('test-xmlschema.php');
+<?php\r
+/*\r
+\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+       \r
+  Set tabs to 4 for best viewing.\r
+\r
+*/\r
+\r
+error_reporting(E_ALL);\r
+include_once('../adodb.inc.php');\r
+\r
+foreach(array('sybase','mysqlt','access','oci8','postgres','odbc_mssql','odbc','sybase','firebird','informix','db2') as $dbType) {\r
+       echo "<h3>$dbType</h3><p>";\r
+       $db = NewADOConnection($dbType);\r
+       $dict = NewDataDictionary($db);\r
+\r
+       if (!$dict) continue;\r
+       $dict->debug = 1;\r
+       \r
+       $opts = array('REPLACE','mysql' => 'TYPE=INNODB', 'oci8' => 'TABLESPACE USERS');\r
+       \r
+/*     $flds = array(\r
+               array('id',     'I',                                                            \r
+                                                       'AUTO','KEY'),\r
+                                                       \r
+               array('name' => 'firstname', 'type' => 'varchar','size' => 30,\r
+                                                       'DEFAULT'=>'Joan'),\r
+                                                       \r
+               array('lastname','varchar',28,\r
+                                                       'DEFAULT'=>'Chen','key'),\r
+                                                       \r
+               array('averylonglongfieldname','X',1024,\r
+                                                       'NOTNULL','default' => 'test'),\r
+                                                       \r
+               array('price','N','7.2',\r
+                                                       'NOTNULL','default' => '0.00'),\r
+                                                       \r
+               array('MYDATE', 'D', \r
+                                                       'DEFDATE'),\r
+               array('TS','T',\r
+                                                       'DEFTIMESTAMP')\r
+       );*/\r
+       \r
+       $flds = "\r
+ID            I           AUTO KEY,\r
+FIRSTNAME     VARCHAR(30) DEFAULT 'Joan',\r
+LASTNAME      VARCHAR(28) DEFAULT 'Chen' key,\r
+averylonglongfieldname X(1024) DEFAULT 'test',\r
+price         N(7.2)  DEFAULT '0.00',\r
+MYDATE        D      DEFDATE,\r
+BIGFELLOW     X      NOTNULL,\r
+TS            T      DEFTIMESTAMP";\r
+\r
+\r
+       $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));\r
+       $dict->SetSchema('KUTU');\r
+       \r
+       $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));\r
+       $sqla =& array_merge($sqla,$sqli);\r
+       \r
+       $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));\r
+       $sqla =& array_merge($sqla,$sqli);\r
+       $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));\r
+       $sqla =& array_merge($sqla,$sqli);\r
+       \r
+       $addflds = array(array('height', 'F'),array('weight','F'));\r
+       $sqli = $dict->AddColumnSQL('testtable',$addflds);\r
+       $sqla =& array_merge($sqla,$sqli);\r
+       $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));\r
+       $sqli = $dict->AlterColumnSQL('testtable',$addflds);\r
+       $sqla =& array_merge($sqla,$sqli);\r
+       \r
+       \r
+       printsqla($dbType,$sqla);\r
+       \r
+       if (file_exists('d:\inetpub\wwwroot\php\phplens\adodb\adodb.inc.php'))\r
+       if ($dbType == 'mysql') {\r
+               $db->Connect('localhost', "root", "", "test");\r
+               $dict->SetSchema('');\r
+               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);\r
+               if ($sqla2) printsqla($dbType,$sqla2);\r
+       }\r
+               if ($dbType == 'postgres') {\r
+               $db->Connect('localhost', "tester", "test", "test");\r
+               $dict->SetSchema('');\r
+               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);\r
+               if ($sqla2) printsqla($dbType,$sqla2);\r
+       }\r
+       \r
+}\r
+\r
+function printsqla($dbType,$sqla)\r
+{\r
+       print "<pre>";\r
+       //print_r($dict->MetaTables());\r
+       foreach($sqla as $s) {\r
+               $s = htmlspecialchars($s);\r
+               print "$s;\n";\r
+               if ($dbType == 'oci8') print "/\n";\r
+       }\r
+       print "</pre><hr>";\r
+}\r
+\r
+/***\r
+\r
+Generated SQL:\r
+\r
+mysql\r
+\r
+CREATE DATABASE KUTU;\r
+DROP TABLE KUTU.testtable;\r
+CREATE TABLE KUTU.testtable (\r
+id               INTEGER NOT NULL AUTO_INCREMENT,\r
+firstname        VARCHAR(30) DEFAULT 'Joan',\r
+lastname         VARCHAR(28) NOT NULL DEFAULT 'Chen',\r
+averylonglongfieldname LONGTEXT NOT NULL,\r
+price            NUMERIC(7,2) NOT NULL DEFAULT 0.00,\r
+MYDATE           DATE DEFAULT CURDATE(),\r
+                 PRIMARY KEY (id, lastname)\r
+)TYPE=ISAM;\r
+CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);\r
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
+ALTER TABLE KUTU.testtable  ADD height           DOUBLE;\r
+ALTER TABLE KUTU.testtable  ADD weight           DOUBLE;\r
+ALTER TABLE KUTU.testtable  MODIFY COLUMN height           DOUBLE NOT NULL;\r
+ALTER TABLE KUTU.testtable  MODIFY COLUMN weight           DOUBLE NOT NULL;\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+oci8\r
+\r
+CREATE USER KUTU IDENTIFIED BY tiger;\r
+/\r
+GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;\r
+/\r
+DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;\r
+/\r
+CREATE TABLE KUTU.testtable (\r
+id               NUMBER(16) NOT NULL,\r
+firstname        VARCHAR(30) DEFAULT 'Joan',\r
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
+averylonglongfieldname CLOB NOT NULL,\r
+price            NUMBER(7,2) DEFAULT 0.00 NOT NULL,\r
+MYDATE           DATE DEFAULT TRUNC(SYSDATE),\r
+                 PRIMARY KEY (id, lastname)\r
+)TABLESPACE USERS;\r
+/\r
+DROP SEQUENCE KUTU.SEQ_testtable;\r
+/\r
+CREATE SEQUENCE KUTU.SEQ_testtable;\r
+/\r
+CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable \r
+               FOR EACH ROW\r
+               BEGIN\r
+                 select KUTU.SEQ_testtable.nextval into :new.id from dual;\r
+               END;\r
+/\r
+CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);\r
+/\r
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
+/\r
+ALTER TABLE testtable ADD (\r
+ height           NUMBER,\r
+ weight           NUMBER);\r
+/\r
+ALTER TABLE testtable MODIFY(\r
+ height           NUMBER NOT NULL,\r
+ weight           NUMBER NOT NULL);\r
+/\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+postgres\r
+AlterColumnSQL not supported for PostgreSQL\r
+\r
+\r
+CREATE DATABASE KUTU LOCATION='/u01/postdata';\r
+DROP TABLE KUTU.testtable;\r
+CREATE TABLE KUTU.testtable (\r
+id               SERIAL,\r
+firstname        VARCHAR(30) DEFAULT 'Joan',\r
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
+averylonglongfieldname TEXT NOT NULL,\r
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,\r
+MYDATE           DATE DEFAULT CURRENT_DATE,\r
+                 PRIMARY KEY (id, lastname)\r
+);\r
+CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);\r
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
+ALTER TABLE KUTU.testtable  ADD height           FLOAT8;\r
+ALTER TABLE KUTU.testtable  ADD weight           FLOAT8;\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+\r
+odbc_mssql\r
+\r
+CREATE DATABASE KUTU;\r
+DROP TABLE KUTU.testtable;\r
+CREATE TABLE KUTU.testtable (\r
+id               INT IDENTITY(1,1) NOT NULL,\r
+firstname        VARCHAR(30) DEFAULT 'Joan',\r
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
+averylonglongfieldname TEXT NOT NULL,\r
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,\r
+MYDATE           DATETIME DEFAULT GetDate(),\r
+                 PRIMARY KEY (id, lastname)\r
+);\r
+CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);\r
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
+ALTER TABLE KUTU.testtable  ADD\r
+ height           REAL,\r
+ weight           REAL;\r
+ALTER TABLE KUTU.testtable  ALTER COLUMN height           REAL NOT NULL;\r
+ALTER TABLE KUTU.testtable  ALTER COLUMN weight           REAL NOT NULL;\r
+\r
+\r
+--------------------------------------------------------------------------------\r
+*/\r
+\r
+echo "<h1>Test XML Schema</h1>";\r
+$ff = file('xmlschema.xml');\r
+echo "<pre>";\r
+foreach($ff as $xml) echo htmlspecialchars($xml);\r
+echo "</pre>";\r
+include_once('test-xmlschema.php');\r
 ?>
\ No newline at end of file
index c735aa7386546ad8f76f0e33f3c117d969907335..1db718e11c30ff0c6a306e9245c58420395681c6 100644 (file)
@@ -1,58 +1,63 @@
-<?php
-/*
-  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
- */
-
-
-error_reporting(E_ALL);
-
-$path = dirname(__FILE__);
-
-include("$path/../adodb-exceptions.inc.php");
-include("$path/../adodb.inc.php");     
-
-echo "<h3>PHP ".PHP_VERSION."</h3>\n";
-try {
-
-$dbt = 'oci8';
-
-switch($dbt) {
-case 'oci8':
-       $db = NewADOConnection("oci8");
-       $db->Connect('','scott','natsoft');
-       break;
-default:
-case 'mysql':
-       $db = NewADOConnection("mysql");
-       $db->Connect('localhost','root','','test');
-       break;
-}
-
-$db->debug=1;
-
-$cnt = $db->GetOne("select count(*) from adoxyz");
-$rs = $db->Execute("select * from adoxyz order by id");
-
-$i = 0;
-foreach($rs as  $v) {
-       $i += 1;
-       echo "$i: "; adodb_pr($v); adodb_pr($rs->fields);
-       flush();
-}
-
-if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
-
-
-$rs = $db->Execute("select bad from badder");
-
-} catch (exception $e) {
-       adodb_pr($e);
-       echo "<h3>adodb_backtrace:</h3>\n";
-       $e = adodb_backtrace($e->gettrace());
-}
-
+<?php\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+ */\r
+\r
+\r
+error_reporting(E_ALL);\r
+\r
+$path = dirname(__FILE__);\r
+\r
+include("$path/../adodb-exceptions.inc.php");\r
+include("$path/../adodb.inc.php");     \r
+\r
+echo "<h3>PHP ".PHP_VERSION."</h3>\n";\r
+try {\r
+\r
+$dbt = 'mysqli';\r
+\r
+switch($dbt) {\r
+case 'oci8':\r
+       $db = NewADOConnection("oci8");\r
+       $db->Connect('','scott','natsoft');\r
+       break;\r
+default:\r
+case 'mysql':\r
+       $db = NewADOConnection("mysql");\r
+       $db->Connect('localhost','root','','test');\r
+       break;\r
+       \r
+case 'mysqli':\r
+       $db = NewADOConnection("mysqli");\r
+       $db->Connect('localhost','root','','test');\r
+       break;\r
+}\r
+\r
+$db->debug=1;\r
+\r
+$cnt = $db->GetOne("select count(*) from adoxyz");\r
+$rs = $db->Execute("select * from adoxyz order by id");\r
+\r
+$i = 0;\r
+foreach($rs as  $v) {\r
+       $i += 1;\r
+       echo "$i: "; adodb_pr($v); adodb_pr($rs->fields);\r
+       flush();\r
+}\r
+\r
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");\r
+\r
+\r
+$rs = $db->Execute("select bad from badder");\r
+\r
+} catch (exception $e) {\r
+       adodb_pr($e);\r
+       echo "<h3>adodb_backtrace:</h3>\n";\r
+       $e = adodb_backtrace($e->gettrace());\r
+}\r
+\r
 ?>
\ No newline at end of file
index cb3f1fb65f9914d900bc6e88d7d0990629e3bc65..aedfb94d33ab8f4b2974c3d4c711eed80090347c 100644 (file)
@@ -1,34 +1,51 @@
-<?PHP
-
-// V4.20 22 Feb 2004
-
-error_reporting(E_ALL);
-
-require( "../adodb-xmlschema.inc.php" );
-
-// To build the schema, start by creating a normal ADOdb connection:
-$db = ADONewConnection( 'mysql' );
-$db->Connect( 'localhost', 'root', '', 'schematest' );
-
-// To create a schema object and build the query array.
-$schema = new adoSchema( $db );
-
-// To upgrade an existing schema object, use the following 
-// To upgrade an existing database to the provided schema,
-// uncomment the following line:
-#$schema->upgradeSchema();
-
-// Build the SQL array
-$sql = $schema->ParseSchema( "xmlschema.xml" );
-
-print "Here's the SQL to do the build:\n<pre>";
-print_r( $sql );
-print "</pre>\n";
-
-// Execute the SQL on the database
-//$result = $schema->ExecuteSchema( $sql );
-
-// Finally, clean up after the XML parser
-// (PHP won't do this for you!)
-//$schema->Destroy();
+<?PHP\r
+\r
+// V4.50 6 July 2004\r
+\r
+error_reporting(E_ALL);\r
+\r
+require( "../adodb-xmlschema.inc.php" );\r
+\r
+// To build the schema, start by creating a normal ADOdb connection:\r
+$db = ADONewConnection( 'mysql' );\r
+$db->Connect( 'localhost', 'root', '', 'schematest' );\r
+\r
+// To create a schema object and build the query array.\r
+$schema = new adoSchema( $db );\r
+\r
+// To upgrade an existing schema object, use the following \r
+// To upgrade an existing database to the provided schema,\r
+// uncomment the following line:\r
+#$schema->upgradeSchema();\r
+\r
+// Build the SQL array\r
+$sql = $schema->ParseSchema( "xmlschema.xml" );\r
+\r
+print "Here's the SQL to do the build:\n<pre>";\r
+print_r( $sql );\r
+print "</pre>\n";\r
+\r
+// Execute the SQL on the database\r
+//$result = $schema->ExecuteSchema( $sql );\r
+\r
+// Finally, clean up after the XML parser\r
+// (PHP won't do this for you!)\r
+//$schema->Destroy();\r
+\r
+\r
+$db2 = ADONewConnection('mssql');\r
+$db2->Connect('localhost','sa','natsoft','northwind') || die("Fail 2");\r
+\r
+$db2->Execute("drop table simple_table");\r
+\r
+$schema = new adoSchema( $db2 );\r
+$sql = $schema->ParseSchema( "xmlschema-mssql.xml" );\r
+\r
+print "Here's the SQL to do the build:\n<pre>";\r
+print_r( $sql );\r
+print "</pre>\n";\r
+\r
+$db2->debug=1;\r
+\r
+$db2->Execute($sql[0]);\r
 ?>
\ No newline at end of file
index fdcc8ad5da104fce5dd2224d795e288ec0ed4511..c395b3609500e1f2dc2e2d9e3fe80228b2bbbcb8 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-error_reporting(E_ALL);
-$ADODB_FLUSH = true;
-
-define('ADODB_ASSOC_CASE',0);
-
-if (PHP_VERSION < 5) include_once('../adodb-pear.inc.php');
-//--------------------------------------------------------------------------------------
-//define('ADODB_ASSOC_CASE',1);
-//
-function Err($msg)
-{
-       print "<b>$msg</b><br>";
-       flush();
-}
-
-function CheckWS($conn)
-{
-global $ADODB_EXTENSION;
-
-       include_once('../session/adodb-session.php');
-       
-       $saved = $ADODB_EXTENSION;
-       $db = ADONewConnection($conn);
-       $ADODB_EXTENSION = $saved;
-       if (headers_sent()) {
-               print "<p><b>White space detected in adodb-$conn.inc.php or include file...</b></p>";
-               die();
-       }
-}
-
-function do_strtolower(&$arr)
-{
-       foreach($arr as $k => $v) {
-               $arr[$k] = strtolower($v);
-       }
-}
-
-
-function CountExecs($db, $sql, $inputarray)
-{
-global $EXECS;  $EXECS++;
-}
-
-function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
-{
-global $CACHED; $CACHED++;
-}
-
-// the table creation code is specific to the database, so we allow the user 
-// to define their own table creation stuff
-
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
-{
-GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS;
-
-?>     <form method=GET>
-       </p>
-       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
-       </p>
-<?php  
-       $create =false;
-       /*$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       
-       $rs = $db->Execute('select lastname,firstname,lastname,id from adoxyz');
-       $arr = $rs->GetAssoc();
-       echo "<pre>";print_r($arr);
-       die();*/
-       
-       GLOBAL $EXECS, $CACHED;
-       
-       $EXECS = 0;
-       $CACHED = 0;
-       if ((rand()%3) == 0) @$db->Execute("delete from adodb_logsql");
-       $db->debug=1;
-       
-       $db->fnExecute = 'CountExecs';
-       $db->fnCacheExecute = 'CountCachedExecs';
-       
-       if (empty($_GET['nolog'])) {
-               echo "<h3>SQL Logging enabled</h3>";
-               $db->LogSQL();/*
-               $sql =
-"SELECT t1.sid, t1.sid, t1.title, t1.hometext, t1.notes, t1.aid, t1.informant, 
-t2.url, t2.email, t1.catid, t3.title, t1.topic, t4.topicname, t4.topicimage, 
-t4.topictext, t1.score, t1.ratings, t1.counter, t1.comments, t1.acomm 
-FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_topics` `t4` 
-       WHERE ((t2.aid=t1.aid) AND (t3.catid=t1.catid) AND (t4.topicid=t1.topic) 
-       AND ((t1.alanguage='german') OR (t1.alanguage='')) AND (t1.ihome='0')) 
-       ORDER BY t1.time DESC";
-               $db->SelectLimit($sql);
-               echo $db->ErrorMsg();*/
-       }
-       $ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));
-       $db->debug = false;
-       
-       //print $db->UnixTimeStamp('2003-7-22 23:00:00');
-       
-       $phpv = phpversion();
-       if (defined('ADODB_EXTENSION')) $ext = ' &nbsp; Extension '.ADODB_EXTENSION.' installed';
-       else $ext = '';
-       print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv $ext</h3>";
-       flush();
-       $arr = $db->ServerInfo();
-       print_r($arr);
-       echo "<br>";
-       $e = error_reporting(E_ALL-E_WARNING);
-       flush();
-       print "<i>date1</i> (1969-02-20) = ".$db->DBDate('1969-2-20');
-       print "<br><i>date1</i> (1999-02-20) = ".$db->DBDate('1999-2-20');
-       print "<br><i>date1.1</i> 1999 = ".$db->DBDate("'1999'");
-       print "<br><i>date2</i> (1970-1-2) = ".$db->DBDate(24*3600)."<p>";
-       print "<i>ts1</i> (1999-02-20 13:40:50) = ".$db->DBTimeStamp('1999-2-20 1:40:50 pm');
-       print "<br><i>ts1.1</i> (1999-02-20 13:40:00) = ".$db->DBTimeStamp('1999-2-20 13:40');
-       print "<br><i>ts2</i> (1999-02-20) = ".$db->DBTimeStamp('1999-2-20');
-       print "<br><i>ts3</i> (1970-1-2 +/- timezone) = ".$db->DBTimeStamp(24*3600);
-       print "<br> Fractional TS (1999-2-20 13:40:50.91): ".$db->DBTimeStamp($db->UnixTimeStamp('1999-2-20 13:40:50.91+1'));
-        $dd = $db->UnixDate('1999-02-20');
-       print "<br>unixdate</i> 1999-02-20 = ".date('Y-m-d',$dd)."<p>";
-       print "<br><i>ts4</i> =".($db->UnixTimeStamp("19700101000101")+8*3600);
-       print "<br><i>ts5</i> =".$db->DBTimeStamp($db->UnixTimeStamp("20040110092123"));
-       print "<br><i>ts6</i> =".$db->UserTimeStamp("20040110092123");
-       print "<br><i>ts6</i> =".$db->DBTimeStamp("20040110092123");
-       flush();
-       // mssql too slow in failing bad connection
-       if (false && $db->databaseType != 'mssql') {
-               print "<p>Testing bad connection. Ignore following error msgs:<br>";
-               $db2 = ADONewConnection();
-               $rez = $db2->Connect("bad connection");
-               $err = $db2->ErrorMsg();
-               print "<i>Error='$err'</i></p>";
-               if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";
-       }
-       error_reporting($e);
-       flush();
-       
-       //$ADODB_COUNTRECS=false;
-       $rs=$db->Execute('select * from adoxyz order by id');
-
-       //print_r($rs);
-       //OCIFetchStatement($rs->_queryID,$rez,0,-1);//,OCI_ASSOC | OCI_FETCHSTATEMENT_BY_ROW);
-       //print_r($rez);
-       //die();
-       if($rs === false) $create = true;
-       else $rs->Close();
-               
-       //if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");
-       
-       if ($create) {
-               if (false && $db->databaseType == 'ibase') {
-                       print "<b>Please create the following table for testing:</b></p>$createtab</p>";
-                       return;
-               } else {
-                       $db->debug = 1;
-                       $e = error_reporting(E_ALL-E_WARNING);
-                       $db->Execute($createtab);
-                       error_reporting($e);
-               }
-       }
-       $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete
-       if ($rs) {
-               if(! $rs->EOF) print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";
-               $rs->Close();
-       } else print "err=".$db->ErrorMsg();
-
-       print "<p>Test select on empty table, FetchField when EOF, and GetInsertSQL</p>";
-       $rs = &$db->Execute("select id,firstname from ADOXYZ where id=9999");
-       if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";
-       if ($rs->EOF && ($o = $rs->FetchField(0))) {
-               $record['id'] = 99;
-               $record['firstname'] = 'John';
-               $sql =  $db->GetInsertSQL($rs, $record);
-               if ($sql != "INSERT INTO ADOXYZ ( id, firstname ) VALUES ( 99, 'John' )") Err("GetInsertSQL does not work on empty table");
-       } else {
-               Err("FetchField does not work on empty recordset, meaning GetInsertSQL will fail...");
-       }
-       if ($rs) $rs->Close();
-       flush();
-       //$db->debug=true;      
-       print "<p>Testing Commit: ";
-       $time = $db->DBDate(time());
-       if (!$db->BeginTrans()) {
-               print '<b>Transactions not supported</b></p>';
-               if ($db->hasTransactions) Err("hasTransactions should be false");
-       } else { /* COMMIT */
-               if (!$db->hasTransactions) Err("hasTransactions should be true");
-               if ($db->transCnt != 1) Err("Invalid transCnt = $db->transCnt (should be 1)");
-               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (99,'Should Not','Exist (Commit)',$time)");
-               if ($rs && $db->CommitTrans()) {
-                       $rs->Close();
-                       $rs = &$db->Execute("select * from ADOXYZ where id=99");
-                       if ($rs === false || $rs->EOF) {
-                               print '<b>Data not saved</b></p>';
-                               $rs = &$db->Execute("select * from ADOXYZ where id=99");
-                               print_r($rs);
-                               die();
-                       } else print 'OK</p>';
-                       if ($rs) $rs->Close();
-               } else {
-                       if (!$rs) {
-                               print "<b>Insert failed</b></p>";
-                               $db->RollbackTrans();
-                       } else print "<b>Commit failed</b></p>";
-               }
-               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
-               
-               /* ROLLBACK */  
-               if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";
-               print "<p>Testing Rollback: ";
-               $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (100,'Should Not','Exist (Rollback)',$time)");
-               if ($db->RollbackTrans()) {
-                       $rs = $db->Execute("select * from ADOXYZ where id=100");
-                       if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';
-                       else print 'OK</p>';
-                       if ($rs) $rs->Close();
-               } else
-                       print "<b>Commit failed</b></p>";
-                       
-               $rs = &$db->Execute('delete from ADOXYZ where id>50');
-               if ($rs) $rs->Close();
-               
-               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
-       }
-       
-       if (1) {
-               print "<p>Testing MetaDatabases()</p>";
-               print_r( $db->MetaDatabases());
-               
-               print "<p>Testing MetaTables() and MetaColumns()</p>";
-               $a = $db->MetaTables();
-               if ($a===false) print "<b>MetaTables not supported</b></p>";
-               else {
-                       print "Array of tables and views: "; 
-                       foreach($a as $v) print " ($v) ";
-                       print '</p>';
-               }
-               
-               $a = $db->MetaTables('VIEW');
-               if ($a===false) print "<b>MetaTables not supported</b></p>";
-               else {
-                       print "Array of views: "; 
-                       foreach($a as $v) print " ($v) ";
-                       print '</p>';
-               }
-               
-               $a = $db->MetaTables(false,false,'aDo%');
-               if ($a===false) print "<b>MetaTables not supported</b></p>";
-               else {
-                       print "Array of ado%: "; 
-                       foreach($a as $v) print " ($v) ";
-                       print '</p>';
-               }
-               
-               $a = $db->MetaTables('TABLE');
-               if ($a===false) print "<b>MetaTables not supported</b></p>";
-               else {
-                       print "Array of tables: "; 
-                       foreach($a as $v) print " ($v) ";
-                       print '</p>';
-               }
-               
-               $db->debug=1;
-               $a = $db->MetaColumns('ADOXYZ');
-               if ($a===false) print "<b>MetaColumns not supported</b></p>";
-               else {
-                       print "<p>Columns of ADOXYZ: <font size=1><br>";
-                       foreach($a as $v) {print_r($v); echo "<br>";}
-                       echo "</font>";
-               }
-               
-               print "<p>Testing MetaIndexes</p>";
-               $a = $db->MetaIndexes('ADOXYZ',true);
-               if ($a===false) print "<b>MetaIndexes not supported</b></p>";
-               else {
-                       print "<p>Indexes of ADOXYZ: <font size=1><br>";
-                       foreach($a as $v) {print_r($v); echo "<br>";}
-                       echo "</font>";
-               }
-               print "<p>Testing MetaPrimaryKeys</p>";
-               $a = $db->MetaPrimaryKeys('ADOXYZ');
-               var_dump($a);
-       }
-       $rs = &$db->Execute('delete from ADOXYZ');
-       if ($rs) $rs->Close();
-       
-       $db->debug = false;
-       
-       
-       switch ($db->databaseType) {
-       case 'postgres7':
-       case 'postgres64':
-       case 'postgres':
-       case 'ibase':
-               print "<p>Encode=".$db->BlobEncode("abc\0d\"'
-ef")."</p>";//'
-
-               print "<p>Testing Foreign Keys</p>";
-               $arr = $db->MetaForeignKeys('adoxyz',false,true);
-               print_r($arr);
-               if (!$arr) Err("Bad MetaForeignKeys");
-               break;
-       
-       case 'odbc_mssql':
-       case 'mssqlpo':
-               print "<p>Testing Foreign Keys</p>";
-               $arr = $db->MetaForeignKeys('Orders',false,true);
-               print_r($arr);
-               if (!$arr) Err("Bad MetaForeignKeys");
-               if ($db->databaseType == 'odbc_mssql') break;
-       
-       case 'mssql': 
-       
-               
-/*
-ASSUME Northwind available...
-
-CREATE PROCEDURE SalesByCategory
-       @CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
-AS
-IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998' 
-BEGIN
-       SELECT @OrdYear = '1998'
-END
-
-SELECT ProductName,
-       TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
-FROM [Order Details] OD, Orders O, Products P, Categories C
-WHERE OD.OrderID = O.OrderID 
-       AND OD.ProductID = P.ProductID 
-       AND P.CategoryID = C.CategoryID
-       AND C.CategoryName = @CategoryName
-       AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
-GROUP BY ProductName
-ORDER BY ProductName
-GO
-*/
-               print "<h4>Testing Stored Procedures for mssql</h4>";
-               $saved = $db->debug;
-               $db->debug=true;
-               
-               $cat = 'Dairy Products';
-               $yr = '1998';
-               
-               $stmt = $db->PrepareSP('SalesByCategory');
-               $db->InParameter($stmt,$cat,'CategoryName');
-               $db->InParameter($stmt,$yr,'OrdYear');
-               $rs = $db->Execute($stmt);
-               rs2html($rs);
-               
-               $cat = 'Grains/Cereals';
-               $yr = 1998;
-               
-               $stmt = $db->PrepareSP('SalesByCategory');
-               $db->InParameter($stmt,$cat,'CategoryName');
-               $db->InParameter($stmt,$yr,'OrdYear');
-               $rs = $db->Execute($stmt);
-               rs2html($rs);
-               
-               /*
-               Test out params - works in 4.2.3 but not 4.3.0???:
-               
-                       CREATE PROCEDURE at_date_interval 
-                               @days INTEGER, 
-                               @start VARCHAR(20) OUT, 
-                               @end VARCHAR(20) OUT    
-                       AS 
-                       BEGIN 
-                               set @start = CONVERT(VARCHAR(20), getdate(), 101) 
-                               set @end =CONVERT(VARCHAR(20), dateadd(day, @days, getdate()), 101 ) 
-                       END
-                       GO
-               */
-               $db->debug=1;
-               $stmt = $db->PrepareSP('at_date_interval');
-               $days = 10;
-               $begin_date = '';
-               $end_date = '';
-               $db->InParameter($stmt,$days,'days', 4, SQLINT4); 
-               $db->OutParameter($stmt,$begin_date,'start', 20, SQLVARCHAR ); 
-               $db->OutParameter($stmt,$end_date,'end', 20, SQLVARCHAR ); 
-               $db->Execute($stmt);
-               if (empty($begin_date) or empty($end_date)) {
-                       Err("MSSQL SP Test for OUT Failed");
-                       print "begin=$begin_date end=$end_date<p>";
-               } else print "(Today +10days) = (begin=$begin_date end=$end_date)<p>";
-       
-               $db->debug = $saved;
-               break;
-       case 'oci8': 
-       case 'oci8po':
-               $saved = $db->debug;
-               $db->debug=true;
-               
-               print "<h4>Testing Foreign Keys</h4>";
-               $arr = $db->MetaForeignKeys('emp');
-               print_r($arr);
-               if (!$arr) Err("Bad MetaForeignKeys");
-               print "<h4>Testing Cursor Variables</h4>";
-/*
--- TEST PACKAGE
-CREATE OR REPLACE PACKAGE adodb AS
-TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
-PROCEDURE data_out(input IN varchar, output OUT varchar); 
-END adodb;
-/
-
-CREATE OR REPLACE PACKAGE BODY adodb AS
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
-       BEGIN
-               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
-       END open_tab;
-       
-PROCEDURE data_out(input IN varchar, output OUT varchar) IS
-       BEGIN
-               output := 'Cinta Hati '||input;
-       END;
-END adodb;
-/
-*/
-               $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS,'A%'); END;");
-       
-               if ($rs && !$rs->EOF) {
-                       print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
-               } else {
-                       print "<b>Error in using Cursor Variables 1</b><p>";
-               }
-               
-               
-               print "<h4>Testing Stored Procedures for oci8</h4>";
-               
-               $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
-               $a1 = 'Malaysia';
-               //$a2 = ''; # a2 doesn't even need to be defined!
-               $db->InParameter($stmt,$a1,'a1');
-               $db->OutParameter($stmt,$a2,'a2');
-               $rs = $db->Execute($stmt);
-               if ($rs) {
-                       if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
-                       else echo  "OK: a2=$a2<p>";
-               } else {
-                       print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
-               }
-               
-               
-               $tname = 'A%';
-               
-               $stmt = $db->PrepareSP('select * from tab where tname like :tablename');
-               $db->Parameter($stmt,$tname,'tablename');
-               $rs = $db->Execute($stmt);
-               rs2html($rs);
-               
-               $db->debug = $saved;
-               break;
-       
-       default:
-               break;
-       }
-       $arr = array(
-               array(1,'Caroline','Miranda'),
-               array(2,'John','Lim'),
-               array(3,'Wai Hun','See')
-       );
-       $db->debug=1;
-       print "<p>Testing Bulk Insert of 3 rows</p>";
-
-       $sql = "insert into ADOXYZ (id,firstname,lastname) values (".$db->Param('0').",".$db->Param('1').",".$db->Param('2').")";
-       $db->StartTrans();
-       $db->Execute($sql,$arr);
-       $db->CompleteTrans();
-       $rs = $db->Execute('select * from ADOXYZ order by id');
-       if ($rs->RecordCount() != 3) Err("Bad bulk insert");
-       rs2html($rs);
-       
-       $db->Execute('delete from ADOXYZ');
-               
-       print "<p>Inserting 50 rows</p>";
-
-       for ($i = 0; $i < 5; $i++) {    
-
-       $time = $db->DBDate(time());
-       if (empty($HTTP_GET_VARS['hide'])) $db->debug = true;
-       switch($db->databaseType){
-       case 'mssqlpo':
-       case 'mssql':
-               $sqlt = "CREATE TABLE mytable (
-  row1 INT  IDENTITY(1,1) NOT NULL,
-  row2 varchar(16),
-  PRIMARY KEY  (row1))";
-               //$db->debug=1;
-               if (!$db->Execute("delete from mytable")) 
-                       $db->Execute($sqlt);
-                       
-               $ok = $db->Execute("insert into mytable (row2) values ('test')");
-               $ins_id=$db->Insert_ID();
-               echo "Insert ID=";var_dump($ins_id);
-               if ($ins_id == 0) Err("Bad Insert_ID()");
-               $ins_id2 = $db->GetOne("select row1 from mytable");
-               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
-               
-               $arr = array(0=>'Caroline',1=>'Miranda');
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
-               break;
-               
-       case 'mysql':
-               $sqlt = "CREATE TABLE `mytable` (
-  `row1` int(11) NOT NULL auto_increment,
-  `row2` varchar(16) NOT NULL default '',
-  PRIMARY KEY  (`row1`),
-  KEY `myindex` (`row1`,`row2`)
-) ";
-               if (!$db->Execute("delete from mytable")) 
-                       $db->Execute($sqlt);
-                       
-               $ok = $db->Execute("insert into mytable (row2) values ('test')");
-               $ins_id=$db->Insert_ID();
-               echo "Insert ID=";var_dump($ins_id);
-               if ($ins_id == 0) Err("Bad Insert_ID()");
-               $ins_id2 = $db->GetOne("select row1 from mytable");
-               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
-               
-       default:
-               $arr = array(0=>'Caroline',1=>'Miranda');
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
-               break;
-       
-       case 'oci8':
-       case 'oci805':
-               $arr = array('first'=>'Caroline','last'=>'Miranda');
-               $amt = rand() % 100;
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,:first,:last,$time)";                
-               break;
-       }
-       if ($i & 1) {
-               $sql = $db->Prepare($sql);
-       }
-       $rs = $db->Execute($sql,$arr);
-               
-       if ($rs === false) Err( 'Error inserting with parameters');
-       else $rs->Close();
-       $db->debug = false;
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");
-       /*$ins_id=$db->Insert_ID();
-       echo "Insert ID=";var_dump($ins_id);*/
-       if ($db->databaseType == 'mysql') if ($ins_id == 0) Err('Bad Insert_ID');
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan',".$db->quote("Turing'ton").",$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");
-       } // for
-       if (1) {
-       $db->debug=1;
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       $cnt = $db->GetOne("select count(*) from ADOXYZ");
-       $rs = $db->Execute('update ADOXYZ set id=id+1');        
-       if (!is_object($rs)) {
-               print_r($rs);
-               err("Update should return object");
-       }
-       if (!$rs) err("Update generated error");
-       
-       $nrows = $db->Affected_Rows();   
-       if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";
-       else if ($nrows != $cnt)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";
-       else print "<p>Affected_Rows() passed</p>";
-       }
-       $db->debug = false;
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
- //////////////////////////////////////////////////////////////////////////////////////////
-       
-       $rs = $db->Execute("select * from ADOXYZ where firstname = 'not known'");
-       if (!$rs ||  !$rs->EOF) print "<p><b>Error on empty recordset</b></p>";
-       else if ($rs->RecordCount() != 0) {
-               print "<p><b>Error on RecordCount. Should be 0. Was ".$rs->RecordCount()."</b></p>"; 
-               print_r($rs->fields);
-       }
-       if ($db->databaseType !== 'odbc') {
-               $rs = &$db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id");
-               if ($rs) {
-                       if ($rs->RecordCount() != 50) {
-                               print "<p><b>RecordCount returns ".$rs->RecordCount()."</b></p>";
-                               $poc = $rs->PO_RecordCount('ADOXYZ');
-                               if ($poc == 50) print "<p> &nbsp; &nbsp; PO_RecordCount passed</p>";
-                               else print "<p><b>PO_RecordCount returns wrong value: $poc</b></p>";
-                       } else print "<p>RecordCount() passed</p>";
-                       if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';
-                       else {
-                               Err( '<p>The fields columns <i>cannot</i> be indexed by column name.</p>');
-                               print_r($rs->fields);
-                       }
-                       if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);
-               }
-               else print "<b>Error in Execute of SELECT with random</b></p>";
-       }
-       $val = $db->GetOne("select count(*) from ADOXYZ");
-        if ($val == 50) print "<p>GetOne returns ok</p>";
-        else print "<p><b>Fail: GetOne returns $val</b></p>";
-
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       $val = $db->GetRow("select count(*) from ADOXYZ");
-        if ($val[0] == 50 and sizeof($val) == 1) print "<p>GetRow returns ok</p>";
-        else {
-               print_r($val);
-               print "<p><b>Fail: GetRow returns {$val[0]}</b></p>";
-       }
-
-       print "<p>FetchObject/FetchNextObject Test</p>";
-       $rs = &$db->Execute('select * from ADOXYZ');
-       
-       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
-       
-       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
-               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
-                       print_r($o);
-                       print "<p><b>Firstname is not string</b></p>";
-                       break;
-               }
-       }
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       print "<p>FetchObject/FetchNextObject Test 2</p>";
-       
-       $rs = &$db->Execute('select * from ADOXYZ');
-       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
-       print_r($rs->fields);
-       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
-               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
-                       print_r($o);
-                       print "<p><b>Firstname is not string</b></p>";
-                       break;
-               }
-       }
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       
-       $savefetch = $ADODB_FETCH_MODE;
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       
-       print "<p>CacheSelectLimit  Test</p>";
-       $db->debug=1;
-       $rs = $db->CacheSelectLimit('  select  id, firstname from  ADOXYZ order by id',2);
-       if ($rs && !$rs->EOF) {
-               if (isset($rs->fields[0])) {
-                       Err("ASSOC has numeric fields");
-                       print_r($rs->fields);
-               }
-               if ($rs->fields['id'] != 1)  {Err("Error"); print_r($rs->fields);};
-               if (trim($rs->fields['firstname']) != 'Caroline')  {print Err("Error 2"); print_r($rs->fields);};
-               $rs->MoveNext();
-               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};
-               $rs->MoveNext();
-               if (!$rs->EOF) {
-                       Err("Error EOF");
-                       print_r($rs);
-               }
-       }
-       
-       print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',2);
-       if ($rs && !$rs->EOF) {
-               if ($rs->fields['id'] != 1)  {Err("Error 1"); print_r($rs->fields);};
-               if (trim($rs->fields['firstname']) != 'Caroline')  {Err("Error 2"); print_r($rs->fields);};
-               $rs->MoveNext();
-               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};
-               $rs->MoveNext();
-               if (!$rs->EOF) Err("Error EOF");
-               else if (is_array($rs->fields) || $rs->fields) {
-                       Err("Error: ## fields should be set to false on EOF");
-                       print_r($rs->fields);
-               }
-       }
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
-       if ($rs && !$rs->EOF) {
-               if (isset($rs->fields['id'])) Err("FETCH_NUM has ASSOC fields");
-               if ($rs->fields[0] != 1)  {Err("Error 1"); print_r($rs->fields);};
-               if (trim($rs->fields[1]) != 'Caroline')  {Err("Error 2");print_r($rs->fields);};
-               $rs->MoveNext();
-               if (!$rs->EOF) Err("Error EOF");
-
-       }
-       $ADODB_FETCH_MODE = $savefetch;
-       
-       $db->debug = false;
-       print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
-       if ($rs && !$rs->EOF) {
-               $arr = &$rs->GetRowAssoc();
-               if ($arr['ID'] != 1) {Err("Error 1");print_r($arr);};
-               if (trim($arr['FIRSTNAME']) != 'Caroline') {Err("Error 2"); print_r($arr);};
-               $rs->MoveNext();
-               if (!$rs->EOF) Err("Error EOF");
-
-       }
-       print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
-       if ($rs && !$rs->EOF) {
-               $arr = &$rs->GetRowAssoc(false);
-               if ($arr['id'] != 1) {Err("Error 1"); print_r($arr);};
-               if (trim($arr['firstname']) != 'Caroline') {Err("Error 2"); print_r($arr);};
-
-       }
-       
-       print "<p>GetCol Test</p>";
-       $col = $db->GetCol('select distinct firstname from adoxyz order by 1');
-       if (!is_array($col)) Err("Col size is wrong");
-       if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong");
-
-       $db->debug = true;
-       print "<p>SelectLimit Distinct Test 1: Should see Caroline, John and Mary</p>";
-       $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3);
-       $db->debug=false;
-
-       if ($rs && !$rs->EOF) {
-               if (trim($rs->fields[1]) != 'Caroline') Err("Error 1");
-               $rs->MoveNext();
-               if (trim($rs->fields[1]) != 'John') Err("Error 2");
-               $rs->MoveNext();
-               if (trim($rs->fields[1]) != 'Mary') Err("Error 3");
-               $rs->MoveNext();
-               if (! $rs->EOF) Err("Error EOF");
-               //rs2html($rs);
-       } else Err("Failed SelectLimit Test 1");
-       
-       print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";
-       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2);
-       if ($rs && !$rs->EOF) {
-               if (trim($rs->fields[1]) != 'Mary') Err("Error 1");
-               $rs->MoveNext();
-               if (trim($rs->fields[1]) != 'George')Err("Error 2");
-               $rs->MoveNext();
-               if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3");
-               $rs->MoveNext();
-               if (! $rs->EOF) Err("Error EOF");
-       //      rs2html($rs);
-       }
-        else Err("Failed SelectLimit Test 2");
-       
-       print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";
-       $db->debug=1;
-       global $A; $A=1;
-       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',-1,48);
-       $A=0;
-       if ($rs && !$rs->EOF) {
-               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
-               if (trim($rs->fields[1]) != 'Wai Hun') Err("Error 1 ".$rs->fields[1]);
-               $rs->MoveNext();
-               if (trim($rs->fields[1]) != 'Steven') Err("Error 2 ".$rs->fields[1]);
-               $rs->MoveNext();
-               if (! $rs->EOF) {
-                       Err("Error EOF");
-               }
-               //rs2html($rs);
-       }
-        else Err("Failed SelectLimit Test 3");
-               $db->debug = false;
-       
-       
-       $rs = &$db->Execute("select * from ADOXYZ order by id");
-       print "<p>Testing Move()</p>";  
-       if (!$rs)Err( "Failed Move SELECT");
-       else {
-               if (!$rs->Move(2)) {
-                       if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";
-                       else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';
-               } else {
-                       $rs->MoveFirst();
-                       if (trim($rs->Fields("firstname")) != 'Caroline') {
-                               print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";
-                       }
-                       else print "MoveFirst() OK<BR>";
-                                               
-                                               // Move(3) tests error handling -- MoveFirst should not move cursor
-                       $rs->Move(3);
-                       if (trim($rs->Fields("firstname")) != 'George') {
-                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";
-                       } else print "Move(3) OK<BR>";
-                                               
-                       $rs->Move(7);
-                       if (trim($rs->Fields("firstname")) != 'Yat Sun') {
-                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";
-                               print_r($rs);
-                       } else print "Move(7) OK<BR>";
-                       if ($rs->EOF) Err("Move(7) is EOF already");
-                       $rs->MoveLast();
-                       if (trim($rs->Fields("firstname")) != 'Steven'){
-                                print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";
-                                print_r($rs);
-                       }else print "MoveLast() OK<BR>";
-                       $rs->MoveNext();
-                       if (!$rs->EOF) err("Bad MoveNext");
-                       if ($rs->canSeek) {
-                               $rs->Move(3);
-                               if (trim($rs->Fields("firstname")) != 'George') {
-                                       print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) after MoveLast failed</b></p>";
-                                       
-                               } else print "Move(3) after MoveLast() OK<BR>";
-                       }
-                       
-                       print "<p>Empty Move Test";
-                       $rs = $db->Execute("select * from ADOXYZ where id > 0 and id < 0");
-                       $rs->MoveFirst();
-                       if (!$rs->EOF || $rs->fields) Err("Error in empty move first");
-               }
-       }
-       
-       $rs = $db->Execute('select * from ADOXYZ where id = 2');
-       if ($rs->EOF || !is_array($rs->fields)) Err("Error in select");
-       $rs->MoveNext();
-       if (!$rs->EOF) Err("Error in EOF (xx) ");
- //    $db->debug=true;
-       print "<p>Testing ADODB_FETCH_ASSOC and concat: concat firstname and lastname</p>";
-
-       $save = $ADODB_FETCH_MODE;
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       if ($db->dataProvider == 'postgres') {
-               $sql = "select ".$db->Concat('cast(firstname as varchar)',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";
-               $rs = &$db->Execute($sql);
-       } else {
-               $sql = "select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";
-               $rs = &$db->Execute($sql);
-       }
-       if ($rs) {
-               if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);
-       } else {
-               Err( "Failed Concat:".$sql);
-       }
-       $ADODB_FETCH_MODE = $save;
-       print "<hr>Testing GetArray() ";
-       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       
-       $rs = &$db->Execute("select * from ADOXYZ order by id");
-       if ($rs) {
-               $arr = &$rs->GetArray(10);
-               if (sizeof($arr) != 10 || trim($arr[1][1]) != 'John' || trim($arr[1][2]) != 'Lim') print $arr[1][1].' '.$arr[1][2]."<b> &nbsp; ERROR</b><br>";
-               else print " OK<BR>";
-       }
-       
-       $arr = $db->GetArray("select x from ADOXYZ");
-       $e = $db->ErrorMsg(); $e2 = $db->ErrorNo();
-       echo "Testing error handling, should see illegal column 'x' error=<i>$e ($e2) </i><br>";
-       if (!$e || !$e2) Err("Error handling did not work");
-       print "Testing FetchNextObject for 1 object ";
-       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");
-       $fcnt = 0;
-       if ($rs)
-       while ($o = $rs->FetchNextObject()) {
-               $fcnt += 1;     
-       }
-       if ($fcnt == 1) print " OK<BR>";
-       else print "<b>FAILED</b><BR>";
-       
-       $stmt = $db->Prepare("select * from ADOXYZ where id < 3");
-       $rs = $db->Execute($stmt);
-       if (!$rs) Err("Prepare failed");
-       else {
-               $arr = $rs->GetArray();
-               if (!$arr) Err("Prepare failed 2");
-               if (sizeof($arr) != 2) Err("Prepare failed 3");
-       }
-       print "Testing GetAssoc() ";
-       $savecrecs = $ADODB_COUNTRECS;
-       $ADODB_COUNTRECS = false;
-       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ");
-       if ($rs) {
-               $arr = $rs->GetAssoc();
-               //print_r($arr);
-               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
-               else print " OK 1";
-       }
-       
-       $arr = &$db->GetAssoc("select distinct lastname,firstname from ADOXYZ");
-       if ($arr) {
-               //print_r($arr);
-               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
-               else print " OK 2<BR>";
-       }
-       // Comment this out to test countrecs = false
-       $ADODB_COUNTRECS = $savecrecs;
-       
-       for ($loop=0; $loop < 1; $loop++) {
-       print "Testing GetMenu() and CacheExecute<BR>";
-       $db->debug = true;
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       
-       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; 
-       else print " Fail<BR>";
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       
-       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';
-       else print " Fail<BR>";
-       
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';
-       else print " Fail<BR>";
-       print '</p><hr>';
-       
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       if ($rs) {
-               print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);
-               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
-       } else print " Fail<BR>";
-       print '</p><hr>';
-       
-       print "Testing GetMenu2() <BR>";
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; 
-       else print " Fail<BR>";
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
-       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';
-       else print " Fail<BR>";
-       }
-       
-       $db->debug = false;
-       
-       // phplens
-       
-       $sql = 'select * from ADOXYZ where 0=1';
-       echo "<p>**Testing '$sql' (phplens compat 1)</p>";
-       $rs = &$db->Execute($sql);
-       if (!$rs) err( "<b>No recordset returned for '$sql'</b>");
-       if (!$rs->FieldCount()) err( "<b>No fields returned for $sql</b>");
-       if (!$rs->FetchField(1)) err( "<b>FetchField failed for $sql</b>");
-       
-       $sql = 'select * from ADOXYZ order by 1';
-       echo "<p>**Testing '$sql' (phplens compat 2)</p>";
-       $rs = &$db->Execute($sql);
-       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
-       
-       
-       $sql = 'select * from ADOXYZ order by 1,1';
-       echo "<p>**Testing '$sql' (phplens compat 3)</p>";
-       $rs = &$db->Execute($sql);
-       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
-       
-       
-       // Move
-       $rs1 = &$db->Execute("select id from ADOXYZ where id <= 2 order by 1");
-       $rs2 = &$db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");
-
-       if ($rs1) $rs1->MoveLast();
-       if ($rs2) $rs2->MoveLast();
-       
-       if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {
-               $a = $rs1->fields[0];
-               $b = $rs2->fields[0];
-               print "<p><b>Error in multiple recordset test rs1=$a rs2=$b (should be rs1=2 rs2=4)</b></p>";
-       } else
-               print "<p>Testing multiple recordsets OK</p>";
-               
-       
-       echo "<p> GenID test: ";
-       for ($i=1; $i <= 10; $i++) 
-               echo  "($i: ",$val = $db->GenID($db->databaseType.'abcseq6' ,5), ") ";
-       if ($val == 0) Err("GenID not supported");
-       
-       if ($val) {
-               $db->DropSequence('abc_seq2');
-               $db->CreateSequence('abc_seq2');
-               $val = $db->GenID('abc_seq2');
-               $db->DropSequence('abc_seq2');
-               $db->CreateSequence('abc_seq2');
-               $val = $db->GenID('abc_seq2');
-               if ($val != 1) Err("Drop and Create Sequence not supported ($val)");
-       }
-       echo "<p>";
-       
-       if (substr($db->dataProvider,0,3) != 'notused') { // used to crash ado
-               $sql = "select firstnames from adoxyz";
-               print "<p>Testing execution of illegal statement: <i>$sql</i></p>";
-               if ($db->Execute($sql) === false) {
-                       print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';
-               } else 
-                       print "<p><b>Error in error handling -- Execute() should return false</b></p>";
-       } else 
-               print "<p><b>ADO skipped error handling of bad select statement</b></p>";
-       
-       print "<p>ASSOC TEST 2<br>";
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       $rs = $db->query('select * from adoxyz order by id');
-       if ($ee = $db->ErrorMsg()) {
-               Err("Error message=$ee");
-       }
-       if ($ee = $db->ErrorNo()) {
-               Err("Error No = $ee");
-       }
-       print_r($rs->fields);
-       for($i=0;$i<$rs->FieldCount();$i++) 
-       { 
-               $fld=$rs->FetchField($i); 
-               print "<br> Field name is ".$fld->name; 
-               print " ".$rs->Fields($fld->name); 
-       } 
-
-               
-       print "<p>BOTH TEST 2<br>";
-       if ($db->dataProvider == 'ado') {
-               print "<b>ADODB_FETCH_BOTH not supported</b> for dataProvider=".$db->dataProvider."<br>";
-       } else {
-               $ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
-               $rs = $db->query('select * from adoxyz order by id');
-               for($i=0;$i<$rs->FieldCount();$i++) 
-               { 
-                       $fld=$rs->FetchField($i); 
-                       print "<br> Field name is ".$fld->name; 
-                       print " ".$rs->Fields($fld->name); 
-               } 
-       }
-       
-       print "<p>NUM TEST 2<br>";
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       $rs = $db->query('select * from adoxyz order by id');
-       for($i=0;$i<$rs->FieldCount();$i++) 
-       { 
-               $fld=$rs->FetchField($i); 
-               print "<br> Field name is ".$fld->name; 
-               print " ".$rs->Fields($fld->name); 
-       } 
-       
-       print "<p>ASSOC Test of SelectLimit<br>";
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       $rs = $db->selectlimit('select * from adoxyz order by id',3,4);
-       $cnt = 0;
-       while ($rs && !$rs->EOF) {
-               $cnt += 1;
-               if (!isset($rs->fields['firstname'])) {
-                       print "<br><b>ASSOC returned numeric field</b></p>";
-                       break;
-               }
-               $rs->MoveNext();
-       }
-       if ($cnt != 3) print "<br><b>Count should be 3, instead it was $cnt</b></p>";
-       
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       if ($db->sysDate) {
-               $saved = $db->debug;
-               $db->debug = 1;
-               $rs = $db->Execute("select {$db->sysDate} from adoxyz where id=1");
-               if (ADORecordSet::UnixDate(date('Y-m-d')) != $rs->UnixDate($rs->fields[0])) {
-                       print "<p><b>Invalid date {$rs->fields[0]}</b></p>";
-               } else
-                       print "<p>Passed \$sysDate test ({$rs->fields[0]})</p>";
-               
-               print_r($rs->FetchField(0));
-               print time();
-               $db->debug=$saved;
-       } else {
-               print "<p><b>\$db->sysDate not defined</b></p>";
-       }
-
-       print "<p>Test CSV</p>";
-       include_once('../toexport.inc.php');
-       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'He, he\' he,\'"\' q  from adoxyz',10);   
-       
-       print "<pre>";
-       print rs2csv($rs);
-       print "</pre>";
-       
-       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'The      "young man", he said\' from adoxyz',10);        
-       
-       print "<pre>";
-       rs2tabout($rs);
-       print "</pre>";
-       
-       //print " CacheFlush ";
-       //$db->CacheFlush();
-       
-       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A');
-       $sql = "SELECT $date from ADOXYZ";
-       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
-       $rs = $db->SelectLimit($sql,1);
-       $d = date('d-m-M-Y-').'Q'.(ceil(date('m')/3.0)).date(' h:i:s A');
-       if (!$rs) Err("SQLDate query returned no recordset");
-       else if ($d != $rs->fields[0]) Err("SQLDate 1 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);
-       
-       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A',$db->DBDate("1974-02-25"));
-       $sql = "SELECT $date from ADOXYZ";
-       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
-       $rs = $db->SelectLimit($sql,1);
-       $ts = ADOConnection::UnixDate('1974-02-25');
-       $d = date('d-m-M-Y-',$ts).'Q'.(ceil(date('m',$ts)/3.0)).date(' h:i:s A',$ts);
-       if (!$rs) Err("SQLDate query returned no recordset");
-       else if ($d != $rs->fields[0]) Err("SQLDate 2 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);
-       
-       
-       print "<p>Test Filter</p>";
-       $db->debug = 1;
-       
-       $rs = $db->SelectLimit('select * from ADOXYZ where id < 3 order by id');
-       
-       $rs = RSFilter($rs,'do_strtolower');
-       if (trim($rs->fields[1]) != 'caroline'  && trim($rs->fields[2]) != 'miranda') {
-               err('**** RSFilter failed');
-               print_r($rs->fields);
-       }
-       
-       rs2html($rs);
-               
-       $db->debug=1;
-       
-       
-       print "<p>Test Replace</p>";
-       
-       $ret = $db->Replace('adoxyz', 
-               array('id'=>1,'firstname'=>'Caroline','lastname'=>'Miranda'),
-               array('id'),
-               $autoq = true);
-       if (!$ret) echo "<p>Error in replacing existing record</p>";
-       else {
-               $saved = $db->debug;
-               $db->debug = 0;
-               $savec = $ADODB_COUNTRECS;
-               $ADODB_COUNTRECS = true;
-               $rs = $db->Execute('select * FROM ADOXYZ where id=1');
-               $db->debug = $saved;
-               if ($rs->RecordCount() != 1) {
-                       $cnt = $rs->RecordCount();
-                       rs2html($rs);
-                       print "<b>Error - Replace failed, count=$cnt</b><p>";
-               }
-               $ADODB_COUNTRECS = $savec;
-       }
-       $ret = $db->Replace('adoxyz', 
-               array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
-               array('id','firstname'),
-               $autoq = true);
-       if ($ret != 2) print "<b>Replace failed: </b>";
-       print "test A return value=$ret (2 expected) <p>";
-       
-       $ret = $db->Replace('adoxyz', 
-               array('id'=>1000,'firstname'=>'Sherazade','lastname'=>'Al-Rashid'),
-               'id',
-               $autoq = true);
-       if ($ret != 1) 
-               if ($db->dataProvider == 'ibase' && $ret == 2);
-               else print "<b>Replace failed: </b>";
-       print "test B return value=$ret (1 or if ibase then 2 expected) <p>";
-       
-       print "<h3>rs2rs Test</h3>";
-       
-       $rs = $db->Execute('select * from adoxyz order by id');
-       $rs = $db->_rs2rs($rs);
-       $rs->valueX = 'X';
-       $rs->MoveNext();
-       $rs = $db->_rs2rs($rs);
-       if (!isset($rs->valueX)) err("rs2rs does not preserve array recordsets");
-       if (reset($rs->fields) != 1) err("rs2rs does not move to first row");
-
-       /////////////////////////////////////////////////////////////
-       include_once('../pivottable.inc.php');
-       print "<h3>Pivot Test</h3>";
-       $db->debug=true;
-       $sql = PivotTableSQL(
-               $db,                    # adodb connection
-               'adoxyz',               # tables
-               'firstname',    # row fields
-               'lastname',             # column fields 
-               false,                  # join
-               'ID',                   # sum
-               'Sum ',                 # label for sum
-               'sum',                  # aggregate function
-               true
-       );
-       $rs = $db->Execute($sql);
-       if ($rs) rs2html($rs);
-       else Err("Pivot sql error");
-       
-       $db->debug=false;
-       include_once "PEAR.php";
-       
-       // PEAR TESTS BELOW
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-       $pear = true;
-       $rs = $db->query('select * from adoxyz where id>0 and id<10 order by id');
-       
-       $i = 0;
-       if ($rs && !$rs->EOF) {
-               while ($arr = $rs->fetchRow()) {
-                       $i++;
-                       //print "$i ";
-                       if ($arr[0] != $i) {
-                               print_r($arr);
-                               print "<p><b>PEAR DB emulation error 1.</b></p>";
-                               $pear = false;
-                               break;
-                       }
-               }
-               $rs->Close();
-       }
-       
-       
-       if ($i != $db->GetOne('select count(*) from adoxyz where id>0 and id<10')) {
-               print "<p><b>PEAR DB emulation error 1.1 EOF ($i)</b></p>";
-               $pear = false;
-       }
-       
-       $rs = $db->limitQuery('select * from adoxyz where id>0 order by id',$i=3,$top=3);
-       $i2 = $i;
-       if ($rs && !$rs->EOF) {
-
-               while (!is_object($rs->fetchInto($arr))) {
-                       $i2++;
-                       
-       //                      print_r($arr);
-       //              print "$i ";print_r($arr);
-                       if ($arr[0] != $i2) {
-                               print "<p><b>PEAR DB emulation error 2.</b></p>";
-                               $pear = false;
-                               break;
-                       }
-               }
-               $rs->Close();
-       }
-       if ($i2 != $i+$top) {
-               print "<p><b>PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)</b></p>";
-               $pear = false;
-       }
-       
-       if ($pear) print "<p>PEAR DB emulation passed.</p>";
-       
-       $rs = $db->SelectLimit("select ".$db->sysDate." from adoxyz",1);
-       $date = $rs->fields[0];
-       if (!$date) Err("Bad sysDate");
-       else {
-               $ds = $db->UserDate($date,"d m Y");
-               if ($ds != date("d m Y")) Err("Bad UserDate: ".$ds);
-               else echo "Passed UserDate: $ds<p>";
-       }
-       $db->debug=1;
-       if ($db->dataProvider == 'oci8') 
-               $rs = $db->SelectLimit("select to_char(".$db->sysTimeStamp.",'YYYY-MM-DD HH24:MI:SS') from adoxyz",1);
-       else 
-               $rs = $db->SelectLimit("select ".$db->sysTimeStamp." from adoxyz",1);
-       $date = $rs->fields[0];
-       if (!$date) Err("Bad sysTimeStamp");
-       else {
-               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
-               if ($ds != date("H \\h\\r\\s-d m Y")) Err("Bad UserTimeStamp: ".$ds.", correct is ".date("H \\h\\r\\s-d m Y"));
-               else echo "Passed UserTimeStamp: $ds<p>";
-               
-               $date = 100;
-               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
-               $ds2 = date("H \\h\\r\\s-d m Y",$date);
-               if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2");
-               else echo "Passed UserTimeStamp 2: $ds<p>";
-       }
-       if ($db->hasTransactions) {
-               //$db->debug=1;
-               echo "<p>Testing StartTrans CompleteTrans</p>";
-               $db->raiseErrorFn = false;
-               $db->StartTrans();
-               $rs = $db->Execute('select * from notable');
-                       $db->StartTrans();
-                               $db->BeginTrans();
-                       $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
-                               $db->CommitTrans();
-                       $db->CompleteTrans();
-               $rez = $db->CompleteTrans();
-               if ($rez !== false) {
-                       if (is_null($rez)) Err("Error: _transOK not modified");
-                       else Err("Error: CompleteTrans (1) should have failed");
-               } else {
-                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");
-                       if ($name == "Carolx") Err("Error: CompleteTrans (2) should have failed");
-                       else echo "<p> -- Passed StartTrans test1 - rolling back</p>";
-               }
-               
-               $db->StartTrans();
-                       $db->BeginTrans();
-               $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
-                       $db->RollbackTrans();
-               $rez = $db->CompleteTrans();
-               if ($rez !== true) Err("Error: CompleteTrans (1) should have succeeded");
-               else {
-                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");
-                       if (trim($name) != "Carolx") Err("Error: CompleteTrans (2) should have succeeded, returned name=$name");
-                       else echo "<p> -- Passed StartTrans test2 - commiting</p>";
-               }
-       }
-       
-       
-       global $TESTERRS;
-       $debugerr = true;
-       
-       global $ADODB_LANG;$ADODB_LANG = 'fr';
-       $db->debug = false;
-       $TESTERRS = 0;
-       $db->raiseErrorFn = 'adodb_test_err';
-       global $ERRNO; // from adodb_test_err
-       $db->Execute('select * from nowhere');
-       $metae = $db->MetaError($ERRNO);
-       if ($metae !== DB_ERROR_NOSUCHTABLE) print "<p><b>MetaError=".$metae." wrong</b>, should be ".DB_ERROR_NOSUCHTABLE."</p>";
-       else print "<p>MetaError ok (".DB_ERROR_NOSUCHTABLE."): ".$db->MetaErrorMsg($metae)."</p>";
-       if ($TESTERRS != 1) print "<b>raiseErrorFn select nowhere failed</b><br>";
-       $rs = $db->Execute('select * from adoxyz');
-       if ($debugerr) print " Move";
-       $rs->Move(100);
-       $rs->_queryID = false;
-       if ($debugerr) print " MoveNext";
-       $rs->MoveNext();
-       if ($debugerr) print " $rs=false";
-       $rs = false;
-
-       print "<p>SetFetchMode() tests</p>";
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);
-       //      var_dump($rs->fields);
-       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;    
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);
-       //var_dump($rs->fields);
-       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
-       
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;  
-       $db->SetFetchMode(ADODB_FETCH_NUM);
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);
-       if (!isset($rs->fields[0])) Err("BAD FETCH NUM");
-       
-       print "<p>Test MetaTables again with SetFetchMode()</p>";
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);
-       print_r($db->MetaTables());
-       print "<p>";
-       ////////////////////////////////////////////////////////////////////
-       
-       $conn = NewADOConnection($db->databaseType);
-       $conn->raiseErrorFn = 'adodb_test_err';
-       @$conn->Connect('abc');
-       if ($TESTERRS == 2) print "raiseErrorFn tests passed<br>";
-       else print "<b>raiseErrorFn tests failed ($TESTERRS)</b><br>";
-       
-       
-       ////////////////////////////////////////////////////////////////////
-       
-       global $nocountrecs;
-       
-       if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set");
-       if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set");
-
-       
-?>
-       </p>
-       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
-       </p></form>
-<?php
-
-       if ($rs1) $rs1->Close();
-       if ($rs2) $rs2->Close();
-       if ($rs) $rs->Close();
-       $db->Close();
-       
-       if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)");
-       
-       
-       printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);
-}
-
-function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
-{
-global $TESTERRS,$ERRNO;
-
-       $ERRNO = $errno;
-       $TESTERRS += 1;
-       print "<i>** $dbms ($fn): errno=$errno &nbsp; errmsg=$errmsg ($p1,$p2)</i><br>";
-}
-
-//--------------------------------------------------------------------------------------
-
-
-set_time_limit(240); // increase timeout
-
-include("../tohtml.inc.php");
-include("../adodb.inc.php");
-include("../rsfilter.inc.php");
-
-/* White Space Check */
-
-if (isset($_SERVER['argv'][1])) {
-       //print_r($_SERVER['argv']);
-       $HTTP_GET_VARS[$_SERVER['argv'][1]] = 1;
-}
-
-if (@$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') {
-       CheckWS('mysqlt');
-       CheckWS('postgres');
-       CheckWS('oci8po');
-       
-       CheckWS('firebird');
-       CheckWS('sybase');
-       CheckWS('informix');
-
-       CheckWS('ado_mssql');
-       CheckWS('ado_access');
-       CheckWS('mssql');
-       
-       CheckWS('vfp');
-       CheckWS('sqlanywhere');
-       CheckWS('db2');
-       CheckWS('access');
-       CheckWS('odbc_mssql');
-       //
-       CheckWS('oracle');
-       CheckWS('proxy');
-       CheckWS('fbsql');
-       print "White Space Check complete<p>";
-}
-if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true;
-
-
-foreach($HTTP_GET_VARS as $k=>$v)  {
-       //global $$k;
-       $$k = $v;
-}      
-if (strpos(PHP_VERSION,'5') === 0) {
-       //$testaccess=1;
-       //$testmssql = 1;
-       //$testsqlite=1;
-}
-?>
-<html>
-<title>ADODB Testing</title>
-<body bgcolor=white>
-<H1>ADODB Test</H1>
-
-This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). 
-There is also support for Sybase, PostgreSQL.</p>
-For the latest version of ADODB, visit <a href=http://php.weblogs.com/ADODB>php.weblogs.com</a>.</p>
-
-Test <a href=test4.php>GetInsertSQL/GetUpdateSQL</a> &nbsp; 
-       <a href=testsessions.php>Sessions</a> &nbsp;
-       <a href=testpaging.php>Paging</a> &nbsp;
-       <a href=test-perf.php>Perf Monitor</a><p>
-<?php
-include('./testdatabases.inc.php');
-?>
-       
-<?php
-
-include_once('../adodb-time.inc.php');
-adodb_date_test();
-?>
-<p><i>ADODB Database Library  (c) 2000-2004 John Lim. All rights reserved. Released under BSD and LGPL.</i></p>
-</body>
-</html>
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+error_reporting(E_ALL);\r
+\r
+$ADODB_FLUSH = true;\r
+\r
+define('ADODB_ASSOC_CASE',0);\r
+\r
+if (PHP_VERSION < 5) include_once('../adodb-pear.inc.php');\r
+//--------------------------------------------------------------------------------------\r
+//define('ADODB_ASSOC_CASE',1);\r
+//\r
+function Err($msg)\r
+{\r
+       print "<b>$msg</b><br>";\r
+       flush();\r
+}\r
+\r
+function CheckWS($conn)\r
+{\r
+global $ADODB_EXTENSION;\r
+\r
+       include_once('../session/adodb-session.php');\r
+       if (defined('CHECKWSFAIL')){ echo " TESTING $conn ";flush();}\r
+       $saved = $ADODB_EXTENSION;\r
+       $db = ADONewConnection($conn);\r
+       $ADODB_EXTENSION = $saved;\r
+       if (headers_sent()) {\r
+               print "<p><b>White space detected in adodb-$conn.inc.php or include file...</b></p>";\r
+               //die();\r
+       }\r
+}\r
+\r
+function do_strtolower(&$arr)\r
+{\r
+       foreach($arr as $k => $v) {\r
+               $arr[$k] = strtolower($v);\r
+       }\r
+}\r
+\r
+\r
+function CountExecs($db, $sql, $inputarray)\r
+{\r
+global $EXECS;  $EXECS++;\r
+}\r
+\r
+function CountCachedExecs($db, $secs2cache, $sql, $inputarray)\r
+{\r
+global $CACHED; $CACHED++;\r
+}\r
+\r
+// the table creation code is specific to the database, so we allow the user \r
+// to define their own table creation stuff\r
+\r
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
+{\r
+GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS;\r
+\r
+?>     <form method=GET>\r
+       </p>\r
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
+       </p>\r
+<?php  \r
+       $create =false;\r
+       /*$ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       \r
+       $rs = $db->Execute('select lastname,firstname,lastname,id from adoxyz');\r
+       $arr = $rs->GetAssoc();\r
+       echo "<pre>";print_r($arr);\r
+       die();*/\r
+       \r
+       GLOBAL $EXECS, $CACHED;\r
+       \r
+       $EXECS = 0;\r
+       $CACHED = 0;\r
+       //$db->Execute("drop table adodb_logsql");\r
+       if ((rand()%3) == 0) @$db->Execute("delete from adodb_logsql");\r
+       $db->debug=1;\r
+       \r
+       $db->fnExecute = 'CountExecs';\r
+       $db->fnCacheExecute = 'CountCachedExecs';\r
+       \r
+       if (empty($_GET['nolog'])) {\r
+               echo "<h3>SQL Logging enabled</h3>";\r
+               $db->LogSQL();/*\r
+               $sql =\r
+"SELECT t1.sid, t1.sid, t1.title, t1.hometext, t1.notes, t1.aid, t1.informant, \r
+t2.url, t2.email, t1.catid, t3.title, t1.topic, t4.topicname, t4.topicimage, \r
+t4.topictext, t1.score, t1.ratings, t1.counter, t1.comments, t1.acomm \r
+FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_topics` `t4` \r
+       WHERE ((t2.aid=t1.aid) AND (t3.catid=t1.catid) AND (t4.topicid=t1.topic) \r
+       AND ((t1.alanguage='german') OR (t1.alanguage='')) AND (t1.ihome='0')) \r
+       ORDER BY t1.time DESC";\r
+               $db->SelectLimit($sql);\r
+               echo $db->ErrorMsg();*/\r
+       }\r
+       $ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));\r
+       $db->debug = false;\r
+       //print $db->UnixTimeStamp('2003-7-22 23:00:00');\r
+       \r
+       $phpv = phpversion();\r
+       if (defined('ADODB_EXTENSION')) $ext = ' &nbsp; Extension '.ADODB_EXTENSION.' installed';\r
+       else $ext = '';\r
+       print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv $ext</h3>";\r
+       flush();\r
+       $arr = $db->ServerInfo();\r
+       print_r($arr);\r
+       echo "<br>";\r
+       $e = error_reporting(E_ALL-E_WARNING);\r
+       flush();\r
+       \r
+       $tt  = $db->Time(); \r
+       if ($tt == 0) echo '<br><b>$db->Time failed</b>';\r
+       else echo "<br>db->Time: ".date('d-m-Y H:i:s',$tt);\r
+       echo '<br>';\r
+\r
+       echo "Date=",$db->UserDate('2002-04-07'),'<br>';\r
+       print "<i>date1</i> (1969-02-20) = ".$db->DBDate('1969-2-20');\r
+       print "<br><i>date1</i> (1999-02-20) = ".$db->DBDate('1999-2-20');\r
+       print "<br><i>date1.1</i> 1999 = ".$db->DBDate("'1999'");\r
+       print "<br><i>date2</i> (1970-1-2) = ".$db->DBDate(24*3600)."<p>";\r
+       print "<i>ts1</i> (1999-02-20 13:40:50) = ".$db->DBTimeStamp('1999-2-20 1:40:50 pm');\r
+       print "<br><i>ts1.1</i> (1999-02-20 13:40:00) = ".$db->DBTimeStamp('1999-2-20 13:40');\r
+       print "<br><i>ts2</i> (1999-02-20) = ".$db->DBTimeStamp('1999-2-20');\r
+       print "<br><i>ts3</i> (1970-1-2 +/- timezone) = ".$db->DBTimeStamp(24*3600);\r
+       print "<br> Fractional TS (1999-2-20 13:40:50.91): ".$db->DBTimeStamp($db->UnixTimeStamp('1999-2-20 13:40:50.91+1'));\r
+        $dd = $db->UnixDate('1999-02-20');\r
+       print "<br>unixdate</i> 1999-02-20 = ".date('Y-m-d',$dd)."<p>";\r
+       print "<br><i>ts4</i> =".($db->UnixTimeStamp("19700101000101")+8*3600);\r
+       print "<br><i>ts5</i> =".$db->DBTimeStamp($db->UnixTimeStamp("20040110092123"));\r
+       print "<br><i>ts6</i> =".$db->UserTimeStamp("20040110092123");\r
+       print "<br><i>ts6</i> =".$db->DBTimeStamp("20040110092123");\r
+       flush();\r
+       // mssql too slow in failing bad connection\r
+       if (false && $db->databaseType != 'mssql') {\r
+               print "<p>Testing bad connection. Ignore following error msgs:<br>";\r
+               $db2 = ADONewConnection();\r
+               $rez = $db2->Connect("bad connection");\r
+               $err = $db2->ErrorMsg();\r
+               print "<i>Error='$err'</i></p>";\r
+               if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";\r
+       }\r
+       error_reporting($e);\r
+       flush();\r
+       \r
+       //$ADODB_COUNTRECS=false;\r
+       $rs=$db->Execute('select * from adoxyz order by id');\r
+\r
+       //print_r($rs);\r
+       //OCIFetchStatement($rs->_queryID,$rez,0,-1);//,OCI_ASSOC | OCI_FETCHSTATEMENT_BY_ROW);\r
+       //print_r($rez);\r
+       //die();\r
+       if($rs === false) $create = true;\r
+       else $rs->Close();\r
+               \r
+       //if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");\r
+       \r
+       if ($create) {\r
+               if (false && $db->databaseType == 'ibase') {\r
+                       print "<b>Please create the following table for testing:</b></p>$createtab</p>";\r
+                       return;\r
+               } else {\r
+                       $db->debug = 1;\r
+                       $e = error_reporting(E_ALL-E_WARNING);\r
+                       $db->Execute($createtab);\r
+                       error_reporting($e);\r
+               }\r
+       }\r
+       $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete\r
+       if ($rs) {\r
+               if(! $rs->EOF) print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";\r
+               $rs->Close();\r
+       } else print "err=".$db->ErrorMsg();\r
+\r
+       print "<p>Test select on empty table, FetchField when EOF, and GetInsertSQL</p>";\r
+       $rs = &$db->Execute("select id,firstname from ADOXYZ where id=9999");\r
+       if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";\r
+       if ($rs->EOF && ($o = $rs->FetchField(0))) {\r
+               $record['id'] = 99;\r
+               $record['firstname'] = 'John';\r
+               $sql =  $db->GetInsertSQL($rs, $record);\r
+               if ($sql != "INSERT INTO ADOXYZ ( id, firstname ) VALUES ( 99, 'John' )") Err("GetInsertSQL does not work on empty table");\r
+       } else {\r
+               Err("FetchField does not work on empty recordset, meaning GetInsertSQL will fail...");\r
+       }\r
+       if ($rs) $rs->Close();\r
+       flush();\r
+       //$db->debug=true;      \r
+       print "<p>Testing Commit: ";\r
+       $time = $db->DBDate(time());\r
+       if (!$db->BeginTrans()) {\r
+               print '<b>Transactions not supported</b></p>';\r
+               if ($db->hasTransactions) Err("hasTransactions should be false");\r
+       } else { /* COMMIT */\r
+               if (!$db->hasTransactions) Err("hasTransactions should be true");\r
+               if ($db->transCnt != 1) Err("Invalid transCnt = $db->transCnt (should be 1)");\r
+               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (99,'Should Not','Exist (Commit)',$time)");\r
+               if ($rs && $db->CommitTrans()) {\r
+                       $rs->Close();\r
+                       $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
+                       if ($rs === false || $rs->EOF) {\r
+                               print '<b>Data not saved</b></p>';\r
+                               $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
+                               print_r($rs);\r
+                               die();\r
+                       } else print 'OK</p>';\r
+                       if ($rs) $rs->Close();\r
+               } else {\r
+                       if (!$rs) {\r
+                               print "<b>Insert failed</b></p>";\r
+                               $db->RollbackTrans();\r
+                       } else print "<b>Commit failed</b></p>";\r
+               }\r
+               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");\r
+               \r
+               /* ROLLBACK */  \r
+               if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";\r
+               print "<p>Testing Rollback: ";\r
+               $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (100,'Should Not','Exist (Rollback)',$time)");\r
+               if ($db->RollbackTrans()) {\r
+                       $rs = $db->Execute("select * from ADOXYZ where id=100");\r
+                       if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';\r
+                       else print 'OK</p>';\r
+                       if ($rs) $rs->Close();\r
+               } else\r
+                       print "<b>Commit failed</b></p>";\r
+                       \r
+               $rs = &$db->Execute('delete from ADOXYZ where id>50');\r
+               if ($rs) $rs->Close();\r
+               \r
+               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");\r
+       }\r
+       \r
+       if (1) {\r
+               print "<p>Testing MetaDatabases()</p>";\r
+               print_r( $db->MetaDatabases());\r
+\r
+               print "<p>Testing MetaTables() and MetaColumns()</p>";\r
+               $a = $db->MetaTables();\r
+               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
+               else {\r
+                       print "Array of tables and views: "; \r
+                       foreach($a as $v) print " ($v) ";\r
+                       print '</p>';\r
+               }\r
+               \r
+               $a = $db->MetaTables('VIEW');\r
+               if ($a===false) print "<b>MetaTables not supported (views)</b></p>";\r
+               else {\r
+                       print "Array of views: "; \r
+                       foreach($a as $v) print " ($v) ";\r
+                       print '</p>';\r
+               }\r
+               \r
+               $a = $db->MetaTables(false,false,'aDo%');\r
+               if ($a===false) print "<b>MetaTables not supported (mask)</b></p>";\r
+               else {\r
+                       print "Array of ado%: "; \r
+                       foreach($a as $v) print " ($v) ";\r
+                       print '</p>';\r
+               }\r
+               \r
+               $a = $db->MetaTables('TABLE');\r
+               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
+               else {\r
+                       print "Array of tables: "; \r
+                       foreach($a as $v) print " ($v) ";\r
+                       print '</p>';\r
+               }\r
+               \r
+               $db->debug=1;\r
+               $a = $db->MetaColumns('ADOXYZ');\r
+               if ($a===false) print "<b>MetaColumns not supported</b></p>";\r
+               else {\r
+                       print "<p>Columns of ADOXYZ: <font size=1><br>";\r
+                       foreach($a as $v) {print_r($v); echo "<br>";}\r
+                       echo "</font>";\r
+               }\r
+               \r
+               print "<p>Testing MetaIndexes</p>";\r
+               \r
+               $a = $db->MetaIndexes(('ADOXYZ'),true);\r
+               if ($a===false) print "<b>MetaIndexes not supported</b></p>";\r
+               else {\r
+                       print "<p>Indexes of ADOXYZ: <font size=1><br>";\r
+                       adodb_pr($a);\r
+                       echo "</font>";\r
+               }\r
+               print "<p>Testing MetaPrimaryKeys</p>";\r
+               $a = $db->MetaPrimaryKeys('ADOXYZ');\r
+               var_dump($a);\r
+       }\r
+       $rs = &$db->Execute('delete from ADOXYZ');\r
+       if ($rs) $rs->Close();\r
+       \r
+       $db->debug = false;\r
+       \r
+       \r
+       switch ($db->databaseType) {\r
+       case 'postgres7':\r
+       case 'postgres64':\r
+       case 'postgres':\r
+       case 'ibase':\r
+               print "<p>Encode=".$db->BlobEncode("abc\0d\"'\r
+ef")."</p>";//'\r
+\r
+               print "<p>Testing Foreign Keys</p>";\r
+               $arr = $db->MetaForeignKeys('adoxyz',false,true);\r
+               print_r($arr);\r
+               if (!$arr) Err("Bad MetaForeignKeys");\r
+               break;\r
+       \r
+       case 'odbc_mssql':\r
+       case 'mssqlpo':\r
+               print "<p>Testing Foreign Keys</p>";\r
+               $arr = $db->MetaForeignKeys('Orders',false,true);\r
+               print_r($arr);\r
+               if (!$arr) Err("Bad MetaForeignKeys");\r
+               if ($db->databaseType == 'odbc_mssql') break;\r
+       \r
+       case 'mssql': \r
+       \r
+               \r
+/*\r
+ASSUME Northwind available...\r
+\r
+CREATE PROCEDURE SalesByCategory\r
+       @CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'\r
+AS\r
+IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998' \r
+BEGIN\r
+       SELECT @OrdYear = '1998'\r
+END\r
+\r
+SELECT ProductName,\r
+       TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)\r
+FROM [Order Details] OD, Orders O, Products P, Categories C\r
+WHERE OD.OrderID = O.OrderID \r
+       AND OD.ProductID = P.ProductID \r
+       AND P.CategoryID = C.CategoryID\r
+       AND C.CategoryName = @CategoryName\r
+       AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear\r
+GROUP BY ProductName\r
+ORDER BY ProductName\r
+GO\r
+*/\r
+               print "<h4>Testing Stored Procedures for mssql</h4>";\r
+               $saved = $db->debug;\r
+               $db->debug=true;\r
+               \r
+               $cat = 'Dairy Products';\r
+               $yr = '1998';\r
+               \r
+               $stmt = $db->PrepareSP('SalesByCategory');\r
+               $db->InParameter($stmt,$cat,'CategoryName');\r
+               $db->InParameter($stmt,$yr,'OrdYear');\r
+               $rs = $db->Execute($stmt);\r
+               rs2html($rs);\r
+               \r
+               $cat = 'Grains/Cereals';\r
+               $yr = 1998;\r
+               \r
+               $stmt = $db->PrepareSP('SalesByCategory');\r
+               $db->InParameter($stmt,$cat,'CategoryName');\r
+               $db->InParameter($stmt,$yr,'OrdYear');\r
+               $rs = $db->Execute($stmt);\r
+               rs2html($rs);\r
+               \r
+               /*\r
+               Test out params - works in 4.2.3 and 4.3.3 but not 4.3.0:\r
+               \r
+                       CREATE PROCEDURE at_date_interval \r
+                               @days INTEGER, \r
+                               @start VARCHAR(20) OUT, \r
+                               @end VARCHAR(20) OUT    \r
+                       AS \r
+                       BEGIN \r
+                               set @start = CONVERT(VARCHAR(20), getdate(), 101) \r
+                               set @end =CONVERT(VARCHAR(20), dateadd(day, @days, getdate()), 101 ) \r
+                       END\r
+                       GO\r
+               */\r
+               $db->debug=1;\r
+               $stmt = $db->PrepareSP('at_date_interval');\r
+               $days = 10;\r
+               $begin_date = '';\r
+               $end_date = '';\r
+               $db->InParameter($stmt,$days,'days', 4, SQLINT4); \r
+               $db->OutParameter($stmt,$begin_date,'start', 20, SQLVARCHAR ); \r
+               $db->OutParameter($stmt,$end_date,'end', 20, SQLVARCHAR ); \r
+               $db->Execute($stmt);\r
+               if (empty($begin_date) or empty($end_date)) {\r
+                       Err("MSSQL SP Test for OUT Failed");\r
+                       print "begin=$begin_date end=$end_date<p>";\r
+               } else print "(Today +10days) = (begin=$begin_date end=$end_date)<p>";\r
+       \r
+               $db->debug = $saved;\r
+               break;\r
+       case 'oci8': \r
+       case 'oci8po':\r
+               $saved = $db->debug;\r
+               $db->debug=true;\r
+               \r
+               print "<h4>Testing Foreign Keys</h4>";\r
+               $arr = $db->MetaForeignKeys('emp');\r
+               print_r($arr);\r
+               if (!$arr) Err("Bad MetaForeignKeys");\r
+               print "<h4>Testing Cursor Variables</h4>";\r
+/*\r
+-- TEST PACKAGE\r
+CREATE OR REPLACE PACKAGE adodb AS\r
+TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;\r
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);\r
+PROCEDURE data_out(input IN varchar, output OUT varchar); \r
+END adodb;\r
+/\r
+\r
+CREATE OR REPLACE PACKAGE BODY adodb AS\r
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS\r
+       BEGIN\r
+               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;\r
+       END open_tab;\r
+       \r
+PROCEDURE data_out(input IN varchar, output OUT varchar) IS\r
+       BEGIN\r
+               output := 'Cinta Hati '||input;\r
+       END;\r
+END adodb;\r
+/\r
+*/\r
+               $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS,'A%'); END;");\r
+       \r
+               if ($rs && !$rs->EOF) {\r
+                       print "Test 1 RowCount: ".$rs->RecordCount()."<p>";\r
+               } else {\r
+                       print "<b>Error in using Cursor Variables 1</b><p>";\r
+               }\r
+               \r
+               print "<h4>Testing Stored Procedures for oci8</h4>";\r
+               \r
+               $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");\r
+               $a1 = 'Malaysia';\r
+               //$a2 = ''; # a2 doesn't even need to be defined!\r
+               $db->InParameter($stmt,$a1,'a1');\r
+               $db->OutParameter($stmt,$a2,'a2');\r
+               $rs = $db->Execute($stmt);\r
+               if ($rs) {\r
+                       if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";\r
+                       else echo  "OK: a2=$a2<p>";\r
+               } else {\r
+                       print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";\r
+               }\r
+               \r
+               \r
+               $tname = 'A%';\r
+               \r
+               $stmt = $db->PrepareSP('select * from tab where tname like :tablename');\r
+               $db->Parameter($stmt,$tname,'tablename');\r
+               $rs = $db->Execute($stmt);\r
+               rs2html($rs);\r
+               \r
+               $db->debug = $saved;\r
+               break;\r
+       \r
+       default:\r
+               break;\r
+       }\r
+       $arr = array(\r
+               array(1,'Caroline','Miranda'),\r
+               array(2,'John','Lim'),\r
+               array(3,'Wai Hun','See')\r
+       );\r
+       $db->debug=1;\r
+       print "<p>Testing Bulk Insert of 3 rows</p>";\r
+\r
+       $sql = "insert into ADOXYZ (id,firstname,lastname) values (".$db->Param('0').",".$db->Param('1').",".$db->Param('2').")";\r
+       $db->StartTrans();\r
+       $db->Execute($sql,$arr);\r
+       $db->CompleteTrans();\r
+       $rs = $db->Execute('select * from ADOXYZ order by id');\r
+       if ($rs->RecordCount() != 3) Err("Bad bulk insert");\r
+       rs2html($rs);\r
+       \r
+       $db->Execute('delete from ADOXYZ');\r
+               \r
+       print "<p>Inserting 50 rows</p>";\r
+\r
+       for ($i = 0; $i < 5; $i++) {    \r
+\r
+       $time = $db->DBDate(time());\r
+       if (empty($HTTP_GET_VARS['hide'])) $db->debug = true;\r
+       switch($db->databaseType){\r
+       case 'mssqlpo':\r
+       case 'mssql':\r
+               $sqlt = "CREATE TABLE mytable (\r
+  row1 INT  IDENTITY(1,1) NOT NULL,\r
+  row2 varchar(16),\r
+  PRIMARY KEY  (row1))";\r
+               //$db->debug=1;\r
+               if (!$db->Execute("delete from mytable")) \r
+                       $db->Execute($sqlt);\r
+                       \r
+               $ok = $db->Execute("insert into mytable (row2) values ('test')");\r
+               $ins_id=$db->Insert_ID();\r
+               echo "Insert ID=";var_dump($ins_id);\r
+               if ($ins_id == 0) Err("Bad Insert_ID()");\r
+               $ins_id2 = $db->GetOne("select row1 from mytable");\r
+               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");\r
+               \r
+               $arr = array(0=>'Caroline',1=>'Miranda');\r
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";\r
+               break;\r
+               \r
+       case 'mysql':\r
+               $sqlt = "CREATE TABLE `mytable` (\r
+  `row1` int(11) NOT NULL auto_increment,\r
+  `row2` varchar(16) NOT NULL default '',\r
+  PRIMARY KEY  (`row1`),\r
+  KEY `myindex` (`row1`,`row2`)\r
+) ";\r
+               if (!$db->Execute("delete from mytable")) \r
+                       $db->Execute($sqlt);\r
+                       \r
+               $ok = $db->Execute("insert into mytable (row2) values ('test')");\r
+               $ins_id=$db->Insert_ID();\r
+               echo "Insert ID=";var_dump($ins_id);\r
+               if ($ins_id == 0) Err("Bad Insert_ID()");\r
+               $ins_id2 = $db->GetOne("select row1 from mytable");\r
+               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");\r
+               \r
+       default:\r
+               $arr = array(0=>'Caroline',1=>'Miranda');\r
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";\r
+               break;\r
+       \r
+       case 'oci8':\r
+       case 'oci805':\r
+               $arr = array('first'=>'Caroline','last'=>'Miranda');\r
+               $amt = rand() % 100;\r
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,:first,:last,$time)";                \r
+               break;\r
+       }\r
+       if ($i & 1) {\r
+               $sql = $db->Prepare($sql);\r
+       }\r
+       $rs = $db->Execute($sql,$arr);\r
+               \r
+       if ($rs === false) Err( 'Error inserting with parameters');\r
+       else $rs->Close();\r
+       $db->debug = false;\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");\r
+       /*$ins_id=$db->Insert_ID();\r
+       echo "Insert ID=";var_dump($ins_id);*/\r
+       if ($db->databaseType == 'mysql') if ($ins_id == 0) Err('Bad Insert_ID');\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan',".$db->quote("Turing'ton").",$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");\r
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");\r
+       } // for\r
+       if (1) {\r
+       $db->debug=1;\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       $cnt = $db->GetOne("select count(*) from ADOXYZ");\r
+       $rs = $db->Execute('update ADOXYZ set id=id+1');        \r
+       if (!is_object($rs)) {\r
+               print_r($rs);\r
+               err("Update should return object");\r
+       } \r
+       if (!$rs) err("Update generated error");\r
+       \r
+       $nrows = $db->Affected_Rows();   \r
+       if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";\r
+       else if ($nrows != $cnt)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";\r
+       else print "<p>Affected_Rows() passed</p>";\r
+       }\r
+       \r
+       \r
+       $array = array('zid'=>1,'zdate'=>date('Y-m-d',time()));\r
+       $id = $db->GetOne("select id from ADOXYZ \r
+               where id=".$db->Param('zid')." and created>=".$db->Param('ZDATE')."",\r
+               $array);\r
+       if ($id != 1) Err("Bad bind; id=$id");\r
+       else echo "<br>Bind date/integer passed";\r
+       \r
+       $db->debug = false;\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+ //////////////////////////////////////////////////////////////////////////////////////////\r
+       \r
+       $rs = $db->Execute("select * from ADOXYZ where firstname = 'not known'");\r
+       if (!$rs ||  !$rs->EOF) print "<p><b>Error on empty recordset</b></p>";\r
+       else if ($rs->RecordCount() != 0) {\r
+               print "<p><b>Error on RecordCount. Should be 0. Was ".$rs->RecordCount()."</b></p>"; \r
+               print_r($rs->fields);\r
+       }\r
+       if ($db->databaseType !== 'odbc') {\r
+               $rs = &$db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id");\r
+               if ($rs) {\r
+                       if ($rs->RecordCount() != 50) {\r
+                               print "<p><b>RecordCount returns ".$rs->RecordCount()."</b></p>";\r
+                               $poc = $rs->PO_RecordCount('ADOXYZ');\r
+                               if ($poc == 50) print "<p> &nbsp; &nbsp; PO_RecordCount passed</p>";\r
+                               else print "<p><b>PO_RecordCount returns wrong value: $poc</b></p>";\r
+                       } else print "<p>RecordCount() passed</p>";\r
+                       if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';\r
+                       else {\r
+                               Err( '<p>The fields columns <i>cannot</i> be indexed by column name.</p>');\r
+                               print_r($rs->fields);\r
+                       }\r
+                       if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);\r
+               }\r
+               else print "<p><b>Error in Execute of SELECT with random</b></p>";\r
+       }\r
+       $val = $db->GetOne("select count(*) from ADOXYZ");\r
+        if ($val == 50) print "<p>GetOne returns ok</p>";\r
+        else print "<p><b>Fail: GetOne returns $val</b></p>";\r
+\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       $val = $db->GetRow("select count(*) from ADOXYZ");\r
+        if ($val[0] == 50 and sizeof($val) == 1) print "<p>GetRow returns ok</p>";\r
+        else {\r
+               print_r($val);\r
+               print "<p><b>Fail: GetRow returns {$val[0]}</b></p>";\r
+       }\r
+\r
+       print "<p>FetchObject/FetchNextObject Test</p>";\r
+       $rs = &$db->Execute('select * from ADOXYZ');\r
+       \r
+       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
+       \r
+       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally\r
+               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {\r
+                       print_r($o);\r
+                       print "<p><b>Firstname is not string</b></p>";\r
+                       break;\r
+               }\r
+       }\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       print "<p>FetchObject/FetchNextObject Test 2</p>";\r
+       \r
+       $rs = &$db->Execute('select * from ADOXYZ');\r
+       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
+       print_r($rs->fields);\r
+       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally\r
+               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {\r
+                       print_r($o);\r
+                       print "<p><b>Firstname is not string</b></p>";\r
+                       break;\r
+               }\r
+       }\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       \r
+       $savefetch = $ADODB_FETCH_MODE;\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       \r
+       print "<p>CacheSelectLimit  Test</p>";\r
+       $db->debug=1;\r
+       $rs = $db->CacheSelectLimit('  select  id, firstname from  ADOXYZ order by id',2);\r
+       if ($rs && !$rs->EOF) {\r
+               if (isset($rs->fields[0])) {\r
+                       Err("ASSOC has numeric fields");\r
+                       print_r($rs->fields);\r
+               }\r
+               if ($rs->fields['id'] != 1)  {Err("Error"); print_r($rs->fields);};\r
+               if (trim($rs->fields['firstname']) != 'Caroline')  {print Err("Error 2"); print_r($rs->fields);};\r
+               $rs->MoveNext();\r
+               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};\r
+               $rs->MoveNext();\r
+               if (!$rs->EOF) {\r
+                       Err("Error EOF");\r
+                       print_r($rs);\r
+               }\r
+       }\r
+       \r
+       print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',2);\r
+       if ($rs && !$rs->EOF) {\r
+               if (ADODB_ASSOC_CASE == 2) {\r
+                       $id = 'ID';\r
+                       $fname = 'FIRSTNAME';\r
+               }else {\r
+                       $id = 'id';\r
+                       $fname = 'firstname';\r
+               }\r
+               if ($rs->fields[$id] != 1)  {Err("Error 1"); print_r($rs->fields);};\r
+               if (trim($rs->fields[$fname]) != 'Caroline')  {Err("Error 2"); print_r($rs->fields);};\r
+               $rs->MoveNext();\r
+               if ($rs->fields[$id] != 2)  {Err("Error 3"); print_r($rs->fields);};\r
+               $rs->MoveNext();\r
+               if (!$rs->EOF) Err("Error EOF");\r
+               else if (is_array($rs->fields) || $rs->fields) {\r
+                       Err("Error: ## fields should be set to false on EOF");\r
+                       print_r($rs->fields);\r
+               }\r
+       }\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               if (isset($rs->fields['id'])) Err("FETCH_NUM has ASSOC fields");\r
+               if ($rs->fields[0] != 1)  {Err("Error 1"); print_r($rs->fields);};\r
+               if (trim($rs->fields[1]) != 'Caroline')  {Err("Error 2");print_r($rs->fields);};\r
+               $rs->MoveNext();\r
+               if (!$rs->EOF) Err("Error EOF");\r
+\r
+       }\r
+       $ADODB_FETCH_MODE = $savefetch;\r
+       \r
+       $db->debug = false;\r
+       print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               $arr = &$rs->GetRowAssoc();\r
+               if ($arr['ID'] != 1) {Err("Error 1");print_r($arr);};\r
+               if (trim($arr['FIRSTNAME']) != 'Caroline') {Err("Error 2"); print_r($arr);};\r
+               $rs->MoveNext();\r
+               if (!$rs->EOF) Err("Error EOF");\r
+\r
+       }\r
+       print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";\r
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
+       if ($rs && !$rs->EOF) {\r
+               $arr = &$rs->GetRowAssoc(false);\r
+               if ($arr['id'] != 1) {Err("Error 1"); print_r($arr);};\r
+               if (trim($arr['firstname']) != 'Caroline') {Err("Error 2"); print_r($arr);};\r
+\r
+       }\r
+       \r
+       print "<p>GetCol Test</p>";\r
+       $col = $db->GetCol('select distinct firstname from adoxyz order by 1');\r
+       if (!is_array($col)) Err("Col size is wrong");\r
+       if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong");\r
+\r
+       $db->debug = true;\r
+       print "<p>SelectLimit Distinct Test 1: Should see Caroline, John and Mary</p>";\r
+       $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3);\r
+       $db->debug=false;\r
+\r
+       if ($rs && !$rs->EOF) {\r
+               if (trim($rs->fields[1]) != 'Caroline') Err("Error 1");\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'John') Err("Error 2");\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Mary') Err("Error 3");\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) Err("Error EOF");\r
+               //rs2html($rs);\r
+       } else Err("Failed SelectLimit Test 1");\r
+       \r
+       print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";\r
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2);\r
+       if ($rs && !$rs->EOF) {\r
+               if (trim($rs->fields[1]) != 'Mary') Err("Error 1");\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'George')Err("Error 2");\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3");\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) Err("Error EOF");\r
+       //      rs2html($rs);\r
+       }\r
+        else Err("Failed SelectLimit Test 2");\r
+       \r
+       print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";\r
+       $db->debug=1;\r
+       global $A; $A=1;\r
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',-1,48);\r
+       $A=0;\r
+       if ($rs && !$rs->EOF) {\r
+               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
+               if (trim($rs->fields[1]) != 'Wai Hun') Err("Error 1 ".$rs->fields[1]);\r
+               $rs->MoveNext();\r
+               if (trim($rs->fields[1]) != 'Steven') Err("Error 2 ".$rs->fields[1]);\r
+               $rs->MoveNext();\r
+               if (! $rs->EOF) {\r
+                       Err("Error EOF");\r
+               }\r
+               //rs2html($rs);\r
+       }\r
+        else Err("Failed SelectLimit Test 3");\r
+               $db->debug = false;\r
+       \r
+       \r
+       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
+       print "<p>Testing Move()</p>";  \r
+       if (!$rs)Err( "Failed Move SELECT");\r
+       else {\r
+               if (!$rs->Move(2)) {\r
+                       if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";\r
+                       else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';\r
+               } else {\r
+                       $rs->MoveFirst();\r
+                       if (trim($rs->Fields("firstname")) != 'Caroline') {\r
+                               print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";\r
+                       }\r
+                       else print "MoveFirst() OK<BR>";\r
+                                               \r
+                                               // Move(3) tests error handling -- MoveFirst should not move cursor\r
+                       $rs->Move(3);\r
+                       if (trim($rs->Fields("firstname")) != 'George') {\r
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";\r
+                       } else print "Move(3) OK<BR>";\r
+                                               \r
+                       $rs->Move(7);\r
+                       if (trim($rs->Fields("firstname")) != 'Yat Sun') {\r
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";\r
+                               print_r($rs);\r
+                       } else print "Move(7) OK<BR>";\r
+                       if ($rs->EOF) Err("Move(7) is EOF already");\r
+                       $rs->MoveLast();\r
+                       if (trim($rs->Fields("firstname")) != 'Steven'){\r
+                                print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";\r
+                                print_r($rs);\r
+                       }else print "MoveLast() OK<BR>";\r
+                       $rs->MoveNext();\r
+                       if (!$rs->EOF) err("Bad MoveNext");\r
+                       if ($rs->canSeek) {\r
+                               $rs->Move(3);\r
+                               if (trim($rs->Fields("firstname")) != 'George') {\r
+                                       print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) after MoveLast failed</b></p>";\r
+                                       \r
+                               } else print "Move(3) after MoveLast() OK<BR>";\r
+                       }\r
+                       \r
+                       print "<p>Empty Move Test";\r
+                       $rs = $db->Execute("select * from ADOXYZ where id > 0 and id < 0");\r
+                       $rs->MoveFirst();\r
+                       if (!$rs->EOF || $rs->fields) Err("Error in empty move first");\r
+               }\r
+       }\r
+       \r
+       $rs = $db->Execute('select * from ADOXYZ where id = 2');\r
+       if ($rs->EOF || !is_array($rs->fields)) Err("Error in select");\r
+       $rs->MoveNext();\r
+       if (!$rs->EOF) Err("Error in EOF (xx) ");\r
+ //    $db->debug=true;\r
+       print "<p>Testing ADODB_FETCH_ASSOC and concat: concat firstname and lastname</p>";\r
+\r
+       $save = $ADODB_FETCH_MODE;\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       if ($db->dataProvider == 'postgres') {\r
+               $sql = "select ".$db->Concat('cast(firstname as varchar)',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";\r
+               $rs = &$db->Execute($sql);\r
+       } else {\r
+               $sql = "select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";\r
+               $rs = &$db->Execute($sql);\r
+       }\r
+       if ($rs) {\r
+               if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);\r
+       } else {\r
+               Err( "Failed Concat:".$sql);\r
+       }\r
+       $ADODB_FETCH_MODE = $save;\r
+       print "<hr>Testing GetArray() ";\r
+       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       \r
+       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
+       if ($rs) {\r
+               $arr = &$rs->GetArray(10);\r
+               if (sizeof($arr) != 10 || trim($arr[1][1]) != 'John' || trim($arr[1][2]) != 'Lim') print $arr[1][1].' '.$arr[1][2]."<b> &nbsp; ERROR</b><br>";\r
+               else print " OK<BR>";\r
+       }\r
+       \r
+       $arr = $db->GetArray("select x from ADOXYZ");\r
+       $e = $db->ErrorMsg(); $e2 = $db->ErrorNo();\r
+       echo "Testing error handling, should see illegal column 'x' error=<i>$e ($e2) </i><br>";\r
+       if (!$e || !$e2) Err("Error handling did not work");\r
+       print "Testing FetchNextObject for 1 object ";\r
+       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");\r
+       $fcnt = 0;\r
+       if ($rs)\r
+       while ($o = $rs->FetchNextObject()) {\r
+               $fcnt += 1;     \r
+       }\r
+       if ($fcnt == 1) print " OK<BR>";\r
+       else print "<b>FAILED</b><BR>";\r
+       \r
+       $stmt = $db->Prepare("select * from ADOXYZ where id < 3");\r
+       $rs = $db->Execute($stmt);\r
+       if (!$rs) Err("Prepare failed");\r
+       else {\r
+               $arr = $rs->GetArray();\r
+               if (!$arr) Err("Prepare failed 2");\r
+               if (sizeof($arr) != 2) Err("Prepare failed 3");\r
+       }\r
+       print "Testing GetAssoc() ";\r
+       $savecrecs = $ADODB_COUNTRECS;\r
+       $ADODB_COUNTRECS = false;\r
+       //$arr = $db->GetArray("select  lastname,firstname from ADOXYZ");\r
+       //print_r($arr);\r
+       print "<hr>";\r
+       $rs =& $db->Execute("select distinct lastname,firstname from ADOXYZ");\r
+       \r
+       if ($rs) {\r
+               $arr = $rs->GetAssoc();\r
+               //print_r($arr);\r
+               if (empty($arr['See']) || trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";\r
+               else print " OK 1";\r
+       }\r
+       \r
+       $arr = &$db->GetAssoc("select distinct lastname,firstname from ADOXYZ");\r
+       if ($arr) {\r
+               //print_r($arr);\r
+               if (empty($arr['See']) || trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";\r
+               else print " OK 2<BR>";\r
+       }\r
+       // Comment this out to test countrecs = false\r
+       $ADODB_COUNTRECS = $savecrecs;\r
+       \r
+       for ($loop=0; $loop < 1; $loop++) {\r
+       print "Testing GetMenu() and CacheExecute<BR>";\r
+       $db->debug = true;\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       \r
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; \r
+       else print " Fail<BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       \r
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';\r
+       else print " Fail<BR>";\r
+       \r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';\r
+       else print " Fail<BR>";\r
+       print '</p><hr>';\r
+       \r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) {\r
+               print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);\r
+               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
+       } else print " Fail<BR>";\r
+       print '</p><hr>';\r
+       \r
+       print "Testing GetMenu2() <BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; \r
+       else print " Fail<BR>";\r
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';\r
+       else print " Fail<BR>";\r
+       }\r
+       \r
+       $db->debug = false;\r
+       \r
+       // phplens\r
+       \r
+       $sql = 'select * from ADOXYZ where 0=1';\r
+       echo "<p>**Testing '$sql' (phplens compat 1)</p>";\r
+       $rs = &$db->Execute($sql);\r
+       if (!$rs) err( "<b>No recordset returned for '$sql'</b>");\r
+       if (!$rs->FieldCount()) err( "<b>No fields returned for $sql</b>");\r
+       if (!$rs->FetchField(1)) err( "<b>FetchField failed for $sql</b>");\r
+       \r
+       $sql = 'select * from ADOXYZ order by 1';\r
+       echo "<p>**Testing '$sql' (phplens compat 2)</p>";\r
+       $rs = &$db->Execute($sql);\r
+       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");\r
+       \r
+       \r
+       $sql = 'select * from ADOXYZ order by 1,1';\r
+       echo "<p>**Testing '$sql' (phplens compat 3)</p>";\r
+       $rs = &$db->Execute($sql);\r
+       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");\r
+       \r
+       \r
+       // Move\r
+       $rs1 = &$db->Execute("select id from ADOXYZ where id <= 2 order by 1");\r
+       $rs2 = &$db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");\r
+\r
+       if ($rs1) $rs1->MoveLast();\r
+       if ($rs2) $rs2->MoveLast();\r
+       \r
+       if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {\r
+               $a = $rs1->fields[0];\r
+               $b = $rs2->fields[0];\r
+               print "<p><b>Error in multiple recordset test rs1=$a rs2=$b (should be rs1=2 rs2=4)</b></p>";\r
+       } else\r
+               print "<p>Testing multiple recordsets OK</p>";\r
+               \r
+       \r
+       echo "<p> GenID test: ";\r
+       for ($i=1; $i <= 10; $i++) \r
+               echo  "($i: ",$val = $db->GenID($db->databaseType.'abcseq6' ,5), ") ";\r
+       if ($val == 0) Err("GenID not supported");\r
+       \r
+       if ($val) {\r
+               $db->DropSequence('abc_seq2');\r
+               $db->CreateSequence('abc_seq2');\r
+               $val = $db->GenID('abc_seq2');\r
+               $db->DropSequence('abc_seq2');\r
+               $db->CreateSequence('abc_seq2');\r
+               $val = $db->GenID('abc_seq2');\r
+               if ($val != 1) Err("Drop and Create Sequence not supported ($val)");\r
+       }\r
+       echo "<p>";\r
+       \r
+       if (substr($db->dataProvider,0,3) != 'notused') { // used to crash ado\r
+               $sql = "select firstnames from adoxyz";\r
+               print "<p>Testing execution of illegal statement: <i>$sql</i></p>";\r
+               if ($db->Execute($sql) === false) {\r
+                       print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';\r
+               } else \r
+                       print "<p><b>Error in error handling -- Execute() should return false</b></p>";\r
+       } else \r
+               print "<p><b>ADO skipped error handling of bad select statement</b></p>";\r
+       \r
+       print "<p>ASSOC TEST 2<br>";\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       $rs = $db->query('select * from adoxyz order by id');\r
+       if ($ee = $db->ErrorMsg()) {\r
+               Err("Error message=$ee");\r
+       }\r
+       if ($ee = $db->ErrorNo()) {\r
+               Err("Error No = $ee");\r
+       }\r
+       print_r($rs->fields);\r
+       for($i=0;$i<$rs->FieldCount();$i++) \r
+       { \r
+               $fld=$rs->FetchField($i); \r
+               print "<br> Field name is ".$fld->name; \r
+               print " ".$rs->Fields($fld->name); \r
+       } \r
+\r
+               \r
+       print "<p>BOTH TEST 2<br>";\r
+       if ($db->dataProvider == 'ado') {\r
+               print "<b>ADODB_FETCH_BOTH not supported</b> for dataProvider=".$db->dataProvider."<br>";\r
+       } else {\r
+               $ADODB_FETCH_MODE = ADODB_FETCH_BOTH;\r
+               $rs = $db->query('select * from adoxyz order by id');\r
+               for($i=0;$i<$rs->FieldCount();$i++) \r
+               { \r
+                       $fld=$rs->FetchField($i); \r
+                       print "<br> Field name is ".$fld->name; \r
+                       print " ".$rs->Fields($fld->name); \r
+               } \r
+       }\r
+       \r
+       print "<p>NUM TEST 2<br>";\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       $rs = $db->query('select * from adoxyz order by id');\r
+       for($i=0;$i<$rs->FieldCount();$i++) \r
+       { \r
+               $fld=$rs->FetchField($i); \r
+               print "<br> Field name is ".$fld->name; \r
+               print " ".$rs->Fields($fld->name); \r
+       } \r
+       \r
+       print "<p>ASSOC Test of SelectLimit<br>";\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       $rs = $db->selectlimit('select * from adoxyz order by id',3,4);\r
+       $cnt = 0;\r
+       while ($rs && !$rs->EOF) {\r
+               $cnt += 1;\r
+               if (!isset($rs->fields['firstname'])) {\r
+                       print "<br><b>ASSOC returned numeric field</b></p>";\r
+                       break;\r
+               }\r
+               $rs->MoveNext();\r
+       }\r
+       if ($cnt != 3) print "<br><b>Count should be 3, instead it was $cnt</b></p>";\r
+       \r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       if ($db->sysDate) {\r
+               $saved = $db->debug;\r
+               $db->debug = 1;\r
+               $rs = $db->Execute("select {$db->sysDate} from adoxyz where id=1");\r
+               if (ADORecordSet::UnixDate(date('Y-m-d')) != $rs->UnixDate($rs->fields[0])) {\r
+                       print "<p><b>Invalid date {$rs->fields[0]}</b></p>";\r
+               } else\r
+                       print "<p>Passed \$sysDate test ({$rs->fields[0]})</p>";\r
+               \r
+               print_r($rs->FetchField(0));\r
+               print time();\r
+               $db->debug=$saved;\r
+       } else {\r
+               print "<p><b>\$db->sysDate not defined</b></p>";\r
+       }\r
+\r
+       print "<p>Test CSV</p>";\r
+       include_once('../toexport.inc.php');\r
+       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'He, he\' he,\'"\' q  from adoxyz',10);   \r
+       \r
+       print "<pre>";\r
+       print rs2csv($rs);\r
+       print "</pre>";\r
+       \r
+       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'The      "young man", he said\' from adoxyz',10);        \r
+       \r
+       if (PHP_VERSION < 5) {\r
+               print "<pre>";\r
+               rs2tabout($rs);\r
+               print "</pre>";\r
+       }\r
+       //print " CacheFlush ";\r
+       //$db->CacheFlush();\r
+       \r
+       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A');\r
+       $sql = "SELECT $date from ADOXYZ";\r
+       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";\r
+       $rs = $db->SelectLimit($sql,1);\r
+       $d = date('d-m-M-Y-').'Q'.(ceil(date('m')/3.0)).date(' h:i:s A');\r
+       if (!$rs) Err("SQLDate query returned no recordset");\r
+       else if ($d != $rs->fields[0]) Err("SQLDate 1 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);\r
+       \r
+       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A',$db->DBDate("1974-02-25"));\r
+       $sql = "SELECT $date from ADOXYZ";\r
+       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";\r
+       $rs = $db->SelectLimit($sql,1);\r
+       $ts = ADOConnection::UnixDate('1974-02-25');\r
+       $d = date('d-m-M-Y-',$ts).'Q'.(ceil(date('m',$ts)/3.0)).date(' h:i:s A',$ts);\r
+       if (!$rs) Err("SQLDate query returned no recordset");\r
+       else if ($d != $rs->fields[0]) Err("SQLDate 2 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);\r
+       \r
+       \r
+       print "<p>Test Filter</p>";\r
+       $db->debug = 1;\r
+       \r
+       $rs = $db->SelectLimit('select * from ADOXYZ where id < 3 order by id');\r
+       \r
+       $rs = RSFilter($rs,'do_strtolower');\r
+       if (trim($rs->fields[1]) != 'caroline'  && trim($rs->fields[2]) != 'miranda') {\r
+               err('**** RSFilter failed');\r
+               print_r($rs->fields);\r
+       }\r
+       \r
+       rs2html($rs);\r
+               \r
+       $db->debug=1;\r
+       \r
+       \r
+       print "<p>Test Replace</p>";\r
+       \r
+       $ret = $db->Replace('adoxyz', \r
+               array('id'=>1,'firstname'=>'Caroline','lastname'=>'Miranda'),\r
+               array('id'),\r
+               $autoq = true);\r
+       if (!$ret) echo "<p>Error in replacing existing record</p>";\r
+       else {\r
+               $saved = $db->debug;\r
+               $db->debug = 0;\r
+               $savec = $ADODB_COUNTRECS;\r
+               $ADODB_COUNTRECS = true;\r
+               $rs = $db->Execute('select * FROM ADOXYZ where id=1');\r
+               $db->debug = $saved;\r
+               if ($rs->RecordCount() != 1) {\r
+                       $cnt = $rs->RecordCount();\r
+                       rs2html($rs);\r
+                       print "<b>Error - Replace failed, count=$cnt</b><p>";\r
+               }\r
+               $ADODB_COUNTRECS = $savec;\r
+       }\r
+       $ret = $db->Replace('adoxyz', \r
+               array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),\r
+               array('id','firstname'),\r
+               $autoq = true);\r
+       if ($ret != 2) print "<b>Replace failed: </b>";\r
+       print "test A return value=$ret (2 expected) <p>";\r
+       \r
+       $ret = $db->Replace('adoxyz', \r
+               array('id'=>1000,'firstname'=>'Sherazade','lastname'=>'Al-Rashid'),\r
+               'id',\r
+               $autoq = true);\r
+       if ($ret != 1) \r
+               if ($db->dataProvider == 'ibase' && $ret == 2);\r
+               else print "<b>Replace failed: </b>";\r
+       print "test B return value=$ret (1 or if ibase then 2 expected) <p>";\r
+       \r
+       print "<h3>rs2rs Test</h3>";\r
+       \r
+       $rs = $db->Execute('select * from adoxyz order by id');\r
+       $rs = $db->_rs2rs($rs);\r
+       $rs->valueX = 'X';\r
+       $rs->MoveNext();\r
+       $rs = $db->_rs2rs($rs);\r
+       if (!isset($rs->valueX)) err("rs2rs does not preserve array recordsets");\r
+       if (reset($rs->fields) != 1) err("rs2rs does not move to first row");\r
+\r
+       /////////////////////////////////////////////////////////////\r
+       include_once('../pivottable.inc.php');\r
+       print "<h3>Pivot Test</h3>";\r
+       $db->debug=true;\r
+       $sql = PivotTableSQL(\r
+               $db,                    # adodb connection\r
+               'adoxyz',               # tables\r
+               'firstname',    # row fields\r
+               'lastname',             # column fields \r
+               false,                  # join\r
+               'ID',                   # sum\r
+               'Sum ',                 # label for sum\r
+               'sum',                  # aggregate function\r
+               true\r
+       );\r
+       $rs = $db->Execute($sql);\r
+       if ($rs) rs2html($rs);\r
+       else Err("Pivot sql error");\r
+       \r
+       $db->debug=false;\r
+       include_once "PEAR.php";\r
+       \r
+       // PEAR TESTS BELOW\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
+       $pear = true;\r
+       $rs = $db->query('select * from adoxyz where id>0 and id<10 order by id');\r
+       \r
+       $i = 0;\r
+       if ($rs && !$rs->EOF) {\r
+               while ($arr = $rs->fetchRow()) {\r
+                       $i++;\r
+                       //print "$i ";\r
+                       if ($arr[0] != $i) {\r
+                               print_r($arr);\r
+                               print "<p><b>PEAR DB emulation error 1.</b></p>";\r
+                               $pear = false;\r
+                               break;\r
+                       }\r
+               }\r
+               $rs->Close();\r
+       }\r
+       \r
+       \r
+       if ($i != $db->GetOne('select count(*) from adoxyz where id>0 and id<10')) {\r
+               print "<p><b>PEAR DB emulation error 1.1 EOF ($i)</b></p>";\r
+               $pear = false;\r
+       }\r
+       \r
+       $rs = $db->limitQuery('select * from adoxyz where id>0 order by id',$i=3,$top=3);\r
+       $i2 = $i;\r
+       if ($rs && !$rs->EOF) {\r
+\r
+               while (!is_object($rs->fetchInto($arr))) {\r
+                       $i2++;\r
+                       \r
+       //                      print_r($arr);\r
+       //              print "$i ";print_r($arr);\r
+                       if ($arr[0] != $i2) {\r
+                               print "<p><b>PEAR DB emulation error 2.</b></p>";\r
+                               $pear = false;\r
+                               break;\r
+                       }\r
+               }\r
+               $rs->Close();\r
+       }\r
+       if ($i2 != $i+$top) {\r
+               print "<p><b>PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)</b></p>";\r
+               $pear = false;\r
+       }\r
+       \r
+       if ($pear) print "<p>PEAR DB emulation passed.</p>";\r
+       \r
+       $rs = $db->SelectLimit("select ".$db->sysDate." from adoxyz",1);\r
+       $date = $rs->fields[0];\r
+       if (!$date) Err("Bad sysDate");\r
+       else {\r
+               $ds = $db->UserDate($date,"d m Y");\r
+               if ($ds != date("d m Y")) Err("Bad UserDate: ".$ds.' expected='.date("d m Y"));\r
+               else echo "Passed UserDate: $ds<p>";\r
+       }\r
+       $db->debug=1;\r
+       if ($db->dataProvider == 'oci8') \r
+               $rs = $db->SelectLimit("select to_char(".$db->sysTimeStamp.",'YYYY-MM-DD HH24:MI:SS') from adoxyz",1);\r
+       else \r
+               $rs = $db->SelectLimit("select ".$db->sysTimeStamp." from adoxyz",1);\r
+       $date = $rs->fields[0];\r
+       if (!$date) Err("Bad sysTimeStamp");\r
+       else {\r
+               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");\r
+               if ($ds != date("H \\h\\r\\s-d m Y")) Err("Bad UserTimeStamp: ".$ds.", correct is ".date("H \\h\\r\\s-d m Y"));\r
+               else echo "Passed UserTimeStamp: $ds<p>";\r
+               \r
+               $date = 100;\r
+               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");\r
+               $ds2 = date("H \\h\\r\\s-d m Y",$date);\r
+               if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2");\r
+               else echo "Passed UserTimeStamp 2: $ds<p>";\r
+       }\r
+       if ($db->hasTransactions) {\r
+               //$db->debug=1;\r
+               echo "<p>Testing StartTrans CompleteTrans</p>";\r
+               $db->raiseErrorFn = false;\r
+               $db->StartTrans();\r
+               $rs = $db->Execute('select * from notable');\r
+                       $db->StartTrans();\r
+                               $db->BeginTrans();\r
+                       $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");\r
+                               $db->CommitTrans();\r
+                       $db->CompleteTrans();\r
+               $rez = $db->CompleteTrans();\r
+               if ($rez !== false) {\r
+                       if (is_null($rez)) Err("Error: _transOK not modified");\r
+                       else Err("Error: CompleteTrans (1) should have failed");\r
+               } else {\r
+                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");\r
+                       if ($name == "Carolx") Err("Error: CompleteTrans (2) should have failed");\r
+                       else echo "<p> -- Passed StartTrans test1 - rolling back</p>";\r
+               }\r
+               \r
+               $db->StartTrans();\r
+                       $db->BeginTrans();\r
+               $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");\r
+                       $db->RollbackTrans();\r
+               $rez = $db->CompleteTrans();\r
+               if ($rez !== true) Err("Error: CompleteTrans (1) should have succeeded");\r
+               else {\r
+                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");\r
+                       if (trim($name) != "Carolx") Err("Error: CompleteTrans (2) should have succeeded, returned name=$name");\r
+                       else echo "<p> -- Passed StartTrans test2 - commiting</p>";\r
+               }\r
+       }\r
+       \r
+       $saved = $db->debug;\r
+       $db->debug=1;\r
+       $cnt = _adodb_getcount($db, 'select * from ADOXYZ where firstname in (select firstname from ADOXYZ)');\r
+       echo "<b>Count=</b> $cnt";\r
+       $db->debug=$saved;\r
+       \r
+       global $TESTERRS;\r
+       $debugerr = true;\r
+       \r
+       global $ADODB_LANG;$ADODB_LANG = 'fr';\r
+       $db->debug = false;\r
+       $TESTERRS = 0;\r
+       $db->raiseErrorFn = 'adodb_test_err';\r
+       global $ERRNO; // from adodb_test_err\r
+       $db->Execute('select * from nowhere');\r
+       $metae = $db->MetaError($ERRNO);\r
+       if ($metae !== DB_ERROR_NOSUCHTABLE) print "<p><b>MetaError=".$metae." wrong</b>, should be ".DB_ERROR_NOSUCHTABLE."</p>";\r
+       else print "<p>MetaError ok (".DB_ERROR_NOSUCHTABLE."): ".$db->MetaErrorMsg($metae)."</p>";\r
+       if ($TESTERRS != 1) print "<b>raiseErrorFn select nowhere failed</b><br>";\r
+       $rs = $db->Execute('select * from adoxyz');\r
+       if ($debugerr) print " Move";\r
+       $rs->Move(100);\r
+       $rs->_queryID = false;\r
+       if ($debugerr) print " MoveNext";\r
+       $rs->MoveNext();\r
+       if ($debugerr) print " $rs=false";\r
+       $rs = false;\r
+\r
+       print "<p>SetFetchMode() tests</p>";\r
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
+       //      var_dump($rs->fields);\r
+       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;    \r
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
+       //var_dump($rs->fields);\r
+       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");\r
+       \r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;  \r
+       $db->SetFetchMode(ADODB_FETCH_NUM);\r
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
+       if (!isset($rs->fields[0])) Err("BAD FETCH NUM");\r
+       \r
+       print "<p>Test MetaTables again with SetFetchMode()</p>";\r
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
+       print_r($db->MetaTables());\r
+       print "<p>";\r
+       ////////////////////////////////////////////////////////////////////\r
+       \r
+       $conn = NewADOConnection($db->databaseType);\r
+       $conn->raiseErrorFn = 'adodb_test_err';\r
+       @$conn->PConnect('abc');\r
+       if ($TESTERRS == 2) print "raiseErrorFn tests passed<br>";\r
+       else print "<b>raiseErrorFn tests failed ($TESTERRS)</b><br>";\r
+       \r
+       \r
+       ////////////////////////////////////////////////////////////////////\r
+       \r
+       global $nocountrecs;\r
+       \r
+       if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set");\r
+       if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set");\r
+\r
+       \r
+?>\r
+       </p>\r
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
+       </p></form>\r
+<?php\r
+\r
+       if ($rs1) $rs1->Close();\r
+       if ($rs2) $rs2->Close();\r
+       if ($rs) $rs->Close();\r
+       $db->Close();\r
+       \r
+       if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)");\r
+       \r
+       \r
+       printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);\r
+}\r
+\r
+function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
+{\r
+global $TESTERRS,$ERRNO;\r
+\r
+       $ERRNO = $errno;\r
+       $TESTERRS += 1;\r
+       print "<i>** $dbms ($fn): errno=$errno &nbsp; errmsg=$errmsg ($p1,$p2)</i><br>";\r
+}\r
+\r
+//--------------------------------------------------------------------------------------\r
+\r
+\r
+@set_time_limit(240); // increase timeout\r
+\r
+include("../tohtml.inc.php");\r
+include("../adodb.inc.php");\r
+include("../rsfilter.inc.php");\r
+\r
+/* White Space Check */\r
+\r
+if (isset($_SERVER['argv'][1])) {\r
+       //print_r($_SERVER['argv']);\r
+       $HTTP_GET_VARS[$_SERVER['argv'][1]] = 1;\r
+}\r
+\r
+if ( @$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') {\r
+       CheckWS('mysqlt');\r
+       CheckWS('postgres');\r
+       CheckWS('oci8po');\r
+       \r
+       CheckWS('firebird');\r
+       CheckWS('sybase');\r
+       if (!ini_get('safe_mode')) CheckWS('informix');\r
+\r
+       CheckWS('ado_mssql');\r
+       CheckWS('ado_access');\r
+       CheckWS('mssql');\r
+       \r
+       CheckWS('vfp');\r
+       CheckWS('sqlanywhere');\r
+       CheckWS('db2');\r
+       CheckWS('access');\r
+       CheckWS('odbc_mssql');\r
+       CheckWS('firebird15');\r
+       //\r
+       CheckWS('oracle');\r
+       CheckWS('proxy');\r
+       CheckWS('fbsql');\r
+       print "White Space Check complete<p>";\r
+}\r
+if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true;\r
+\r
+\r
+foreach($HTTP_GET_VARS as $k=>$v)  {\r
+       //global $$k;\r
+       $$k = $v;\r
+}      \r
+if (strpos(PHP_VERSION,'5') === 0) {\r
+       //$testaccess=1;\r
+       //$testmssql = 1;\r
+       //$testsqlite=1;\r
+}\r
+?>\r
+<html>\r
+<title>ADODB Testing</title>\r
+<body bgcolor=white>\r
+<H1>ADODB Test</H1>\r
+\r
+This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). \r
+There is also support for Sybase, PostgreSQL.</p>\r
+For the latest version of ADODB, visit <a href=http://php.weblogs.com/ADODB>php.weblogs.com</a>.</p>\r
+\r
+Test <a href=test4.php>GetInsertSQL/GetUpdateSQL</a> &nbsp; \r
+       <a href=testsessions.php>Sessions</a> &nbsp;\r
+       <a href=testpaging.php>Paging</a> &nbsp;\r
+       <a href=test-perf.php>Perf Monitor</a><p>\r
+<?php\r
+include('./testdatabases.inc.php');\r
+\r
+echo "<br>vers=",ADOConnection::Version();\r
+\r
+include_once('../adodb-time.inc.php');\r
+adodb_date_test();\r
+?>\r
+<p><i>ADODB Database Library  (c) 2000-2004 John Lim. All rights reserved. Released under BSD and LGPL.</i></p>\r
+</body>\r
+</html>\r
index 14474666499c7a3488fe72dafcac4e790e13e85e..6da52e1f8e7e2d7c575660b330158063eb0728be 100644 (file)
@@ -1,41 +1,41 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-<html>
-<head>
-       <title>Untitled</title>
-</head>
-
-<body>
-<?php
-/*
-  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
- */
-#
-# test connecting to 2 MySQL databases simultaneously and ensure that each connection
-# is independant.
-#
-include("../tohtml.inc.php");
-include("../adodb.inc.php");   
-
-ADOLoadCode('mysql');
-
-$c1 = ADONewConnection('oci8');
-
-if (!$c1->PConnect('','scott','tiger')) 
-       die("Cannot connect to server");
-$c1->debug=1;
-$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');
-print "Records=".$rs->RecordCount()."<br><pre>";
-//$rs->_array = false;
-//$rs->connection = false;
-//print_r($rs);
-rs2html($rs);
-?>
-
-
-</body>
-</html>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
+\r
+<html>\r
+<head>\r
+       <title>Untitled</title>\r
+</head>\r
+\r
+<body>\r
+<?php\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+ */\r
+#\r
+# test connecting to 2 MySQL databases simultaneously and ensure that each connection\r
+# is independant.\r
+#\r
+include("../tohtml.inc.php");\r
+include("../adodb.inc.php");   \r
+\r
+ADOLoadCode('mysql');\r
+\r
+$c1 = ADONewConnection('oci8');\r
+\r
+if (!$c1->PConnect('','scott','tiger')) \r
+       die("Cannot connect to server");\r
+$c1->debug=1;\r
+$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');\r
+print "Records=".$rs->RecordCount()."<br><pre>";\r
+//$rs->_array = false;\r
+//$rs->connection = false;\r
+//print_r($rs);\r
+rs2html($rs);\r
+?>\r
+\r
+\r
+</body>\r
+</html>\r
index 207dda27732d97e1a10f5f85cb54ebdc7a4d728c..d3a636938e3934b7653703fbb72c810a53aa508e 100644 (file)
@@ -1,44 +1,44 @@
-<?php
-/*
-  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence.
-  Set tabs to 8.
- */
-
-
-error_reporting(E_ALL);
-
-$path = dirname(__FILE__);
-
-include("$path/../adodb-exceptions.inc.php");
-include("$path/../adodb.inc.php");     
-
-try {
-$db = NewADOConnection("oci8");
-$db->Connect('','scott','natsoft');
-$db->debug=1;
-
-$cnt = $db->GetOne("select count(*) from adoxyz");
-$rs = $db->Execute("select * from adoxyz order by id");
-
-$i = 0;
-foreach($rs as $k => $v) {
-       $i += 1;
-       echo $k; adodb_pr($v);
-       flush();
-}
-
-if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
-
-
-
-$rs = $db->Execute("select bad from badder");
-
-} catch (exception $e) {
-       adodb_pr($e);
-       $e = adodb_backtrace($e->trace);
-}
-
+<?php\r
+/*\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+  Set tabs to 8.\r
+ */\r
+\r
+\r
+error_reporting(E_ALL);\r
+\r
+$path = dirname(__FILE__);\r
+\r
+include("$path/../adodb-exceptions.inc.php");\r
+include("$path/../adodb.inc.php");     \r
+\r
+try {\r
+$db = NewADOConnection("oci8");\r
+$db->Connect('','scott','natsoft');\r
+$db->debug=1;\r
+\r
+$cnt = $db->GetOne("select count(*) from adoxyz");\r
+$rs = $db->Execute("select * from adoxyz order by id");\r
+\r
+$i = 0;\r
+foreach($rs as $k => $v) {\r
+       $i += 1;\r
+       echo $k; adodb_pr($v);\r
+       flush();\r
+}\r
+\r
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");\r
+\r
+\r
+\r
+$rs = $db->Execute("select bad from badder");\r
+\r
+} catch (exception $e) {\r
+       adodb_pr($e);\r
+       $e = adodb_backtrace($e->trace);\r
+}\r
+\r
 ?>
\ No newline at end of file
index 64fb8b01a07867ca4dcf1ff7f500fedab79fc2d1..56956721ffe5a3b0a51c02973119af446f55d69e 100644 (file)
@@ -1,7 +1,7 @@
 <?php\r
 \r
 /** \r
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
  * Released under both BSD license and Lesser GPL library license. \r
  * Whenever there is any discrepancy between the two licenses, \r
  * the BSD license will take precedence. \r
@@ -31,10 +31,13 @@ FROM ADOXYZ WHERE id = -1";
 // Select an empty record from the database \r
 \r
 $conn = &ADONewConnection("mysql");  // create a connection\r
+$conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb\r
+\r
+//$conn =& ADONewConnection('oci8');\r
+//$conn->Connect('','scott','natsoft');\r
 //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
 \r
 $conn->debug=1;\r
-$conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb\r
 $conn->Execute("delete from adoxyz where lastname like 'Smith%'");\r
 \r
 $rs = $conn->Execute($sql); // Execute the query and get the empty recordset\r
@@ -53,6 +56,8 @@ $insertSQL = $conn->GetInsertSQL($rs, $record);
 \r
 $conn->Execute($insertSQL); // Insert the record into the database\r
 \r
+$insertSQL2 = $conn->GetInsertSQL($table='ADOXYZ', $record);\r
+if ($insertSQL != $insertSQL2) echo "<p><b>Walt's new stuff failed</b>: $insertSQL2</p>";\r
 //==========================\r
 // This code tests an update\r
 \r
@@ -62,7 +67,7 @@ FROM ADOXYZ WHERE lastname=".$conn->qstr($record['lastname']);
 // Select a record to update \r
 \r
 $rs = $conn->Execute($sql); // Execute the query and get the existing record to update\r
-if (!$rs) print "<p>No record found!</p>";\r
+if (!$rs) print "<p><b>No record found!</b></p>";\r
 \r
 $record = array(); // Initialize an array to hold the record data to update\r
 \r
@@ -78,7 +83,7 @@ $record['num'] = 3921;
 $updateSQL = $conn->GetUpdateSQL($rs, $record);\r
 \r
 $conn->Execute($updateSQL); // Update the record in the database\r
-print "<p>Rows Affected=".$conn->Affected_Rows()."</p>";\r
+if ($conn->Affected_Rows() != 1)print "<p><b>Error</b>: Rows Affected=".$conn->Affected_Rows().", should be 1</p>";\r
 \r
 $rs = $conn->Execute("select * from adoxyz where lastname like 'Smith%'");\r
 adodb_pr($rs);\r
index ba02aeed085a35700bb55f7cbd12f17951b6efa7..64fe38e2397af4f7f6bba32f287b7990fa2a6139 100644 (file)
@@ -1,47 +1,47 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-
-// Select an empty record from the database 
-
-include('../adodb.inc.php');
-include('../tohtml.inc.php');
-
-include('../adodb-errorpear.inc.php');
-
-if (0) {
-       $conn = &ADONewConnection('mysql');
-       $conn->debug=1;
-       $conn->PConnect("localhost","root","","xphplens");
-       print $conn->databaseType.':'.$conn->GenID().'<br>';
-}
-
-if (0) {
-       $conn = &ADONewConnection("oci8");  // create a connection
-       $conn->debug=1;
-       $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb
-       print $conn->databaseType.':'.$conn->GenID();
-}
-
-if (0) {
-       $conn = &ADONewConnection("ibase");  // create a connection
-       $conn->debug=1;
-       $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb
-       print $conn->databaseType.':'.$conn->GenID().'<br>';
-}
-
-if (0) {
-       $conn = &ADONewConnection('postgres');
-       $conn->debug=1;
-       @$conn->PConnect("susetikus","tester","test","test");
-       print $conn->databaseType.':'.$conn->GenID().'<br>';
-}
-?>
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+\r
+// Select an empty record from the database \r
+\r
+include('../adodb.inc.php');\r
+include('../tohtml.inc.php');\r
+\r
+include('../adodb-errorpear.inc.php');\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection('mysql');\r
+       $conn->debug=1;\r
+       $conn->PConnect("localhost","root","","xphplens");\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection("oci8");  // create a connection\r
+       $conn->debug=1;\r
+       $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb\r
+       print $conn->databaseType.':'.$conn->GenID();\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection("ibase");  // create a connection\r
+       $conn->debug=1;\r
+       $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+\r
+if (0) {\r
+       $conn = &ADONewConnection('postgres');\r
+       $conn->debug=1;\r
+       @$conn->PConnect("susetikus","tester","test","test");\r
+       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
+}\r
+?>\r
index b4516d5e854350260186d00fb874b0f2d42390f0..2f032b7d40bdc6f4856b16b5d3f4d4c47cce6389 100644 (file)
@@ -1,29 +1,29 @@
-<html>
-<body>
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));
-include("../adodb.inc.php");
-
-if (isset($access)) {
-       $db=ADONewConnection('access');
-       $db->PConnect('nwind');
-} else {
-       $db = ADONewConnection('mysql');
-       $db->PConnect('mangrove','root','','xphplens');
-}
-if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');
-else $rs = $db->Execute('select * from products');
-
-$arr = $rs->GetArray();
-print sizeof($arr);
+<html>\r
+<body>\r
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));\r
+include("../adodb.inc.php");\r
+\r
+if (isset($access)) {\r
+       $db=ADONewConnection('access');\r
+       $db->PConnect('nwind');\r
+} else {\r
+       $db = ADONewConnection('mysql');\r
+       $db->PConnect('mangrove','root','','xphplens');\r
+}\r
+if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');\r
+else $rs = $db->Execute('select * from products');\r
+\r
+$arr = $rs->GetArray();\r
+print sizeof($arr);\r
 ?>
\ No newline at end of file
index 871ec8d2729df2714b49439ccfbb57991c3dd6fb..eaa1de03748d5b5668a912a7f0066170ddf80a6d 100644 (file)
-<?php
-  
-/*
-V4.20 22 Feb 2004  (c) 2000-2004 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.
-*/ 
- /* this file is used by the ADODB test program: test.php */
- ?>
-
-<table><tr valign=top><td>
-<form method=get>
-<input type=checkbox name="testaccess" value=1 <?php echo !empty($testaccess) ? 'checked' : '' ?>> <b>Access</b><br>
-<input type=checkbox name="testibase" value=1 <?php echo !empty($testibase) ? 'checked' : '' ?>> <b>Interbase</b><br>
-<input type=checkbox name="testmssql" value=1 <?php echo !empty($testmssql) ? 'checked' : '' ?>> <b>MSSQL</b><br>
- <input type=checkbox name="testmysql" value=1 <?php echo !empty($testmysql) ? 'checked' : '' ?>> <b>MySQL</b><br>
-<input type=checkbox name="testmysqlodbc" value=1 <?php echo !empty($testmysqlodbc) ? 'checked' : '' ?>> <b>MySQL ODBC</b><br>
-<td><input type=checkbox name="testsqlite" value=1 <?php echo !empty($testsqlite) ? 'checked' : '' ?>> <b>SQLite</b><br>
-<input type=checkbox name="testproxy" value=1 <?php echo !empty($testproxy) ? 'checked' : '' ?>> <b>MySQL Proxy</b><br>
-<input type=checkbox name="testoracle" value=1 <?php echo !empty($testoracle) ? 'checked' : '' ?>> <b>Oracle (oci8)</b> <br>
-<input type=checkbox name="testpostgres" value=1 <?php echo !empty($testpostgres) ? 'checked' : '' ?>> <b>PostgreSQL</b><br>
-<input type=checkbox name="testpgodbc" value=1 <?php echo !empty($testpgodbc) ? 'checked' : '' ?>> <b>PostgreSQL ODBC</b><br>
-<td><input type=checkbox name="testdb2" value=1 <?php echo !empty($testdb2) ? 'checked' : '' ?>> DB2<br>
-<input type=checkbox name="testvfp" value=1 <?php echo !empty($testvfp) ? 'checked' : '' ?>> VFP<br>
-<input type=checkbox name="testado" value=1 <?php echo !empty($testado) ? 'checked' : '' ?>> ADO (for mssql and access)<br>
-<input type=checkbox name="nocountrecs" value=1 <?php echo !empty($nocountrecs) ? 'checked' : '' ?>> $ADODB_COUNTRECS=false<br>
-<input type=checkbox name="nolog" value=1 <?php echo !empty($nolog) ? 'checked' : '' ?>> No SQL Logging<br>
-<td><input type=submit>
-</form>
-</table>
-<?php
-
-if ($ADODB_FETCH_MODE != ADODB_FETCH_DEFAULT) print "<h3>FETCH MODE IS NOT ADODB_FETCH_DEFAULT</h3>";
-
-if (isset($nocountrecs)) $ADODB_COUNTRECS = false;
-
-// cannot test databases below, but we include them anyway to check
-// if they parse ok...
-
-if (!strpos(PHP_VERSION,'5') === 0) {
-       ADOLoadCode("sybase");
-       ADOLoadCode("postgres");
-       ADOLoadCode("postgres7");
-       ADOLoadCode("firebird");
-       ADOLoadCode("borland_ibase");
-       ADOLoadCode("informix");
-       ADOLoadCode("sqlanywhere");
-}
-
-
-flush();
-if (!empty($testpostgres)) {
-       //ADOLoadCode("postgres");
-
-       $db = &ADONewConnection('postgres');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if (@$db->Connect("localhost","tester","test","test")) {
-               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");
-       }else
-               print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
-}
-
-if (!empty($testpgodbc)) { 
-       
-       $db = &ADONewConnection('odbc');
-       $db->hasTransactions = false;
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       if ($db->PConnect('Postgresql')) {
-               $db->hasTransactions = true;
-               testdb($db,
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
-       } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
-}
-
-if (!empty($testibase)) {
-       
-       $db = &ADONewConnection('firebird');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if (@$db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", ""))
-               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");
-        else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();
-       
-}
-
-
-if (!empty($testsqlite)) {
-       $db = &ADONewConnection('sqlite');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       if (@$db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", ""))
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
-       else print "ERROR: SQLite";
-       
-}
-
-// REQUIRES ODBC DSN CALLED nwind
-if (!empty($testaccess)) {
-       $db = &ADONewConnection('access');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       $dsn = "nwind";
-       $driver = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\inetpub\adodb\northwind.mdb;Uid=Admin;Pwd=;";
-       if (@$db->PConnect($dsn, "", "", ""))
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
-       else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";
-       
-}
-
-if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS
-
-       $db = &ADONewConnection("ado_access");
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       $access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
-       $myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
-               . 'DATA SOURCE=' . $access . ';';
-               //. 'USER ID=;PASSWORD=;';
-       
-       if (@$db->PConnect($myDSN, "", "", "")) {
-               print "ADO version=".$db->_connectionID->version."<br>";
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
-       } else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();
-       
-}
-
-if (!empty($testvfp)) { // ODBC
-       $db = &ADONewConnection('vfp');
-       print "<h1>Connecting $db->databaseType...</h1>";flush();
-
-       if ( $db->PConnect("vfp-adoxyz")) {
-               testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
-        } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";
-       
-}
-
-
-// REQUIRES MySQL server at localhost with database 'test'
-if (!empty($testmysql)) { // MYSQL
-
-       $db = &ADONewConnection('mysql');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
-       else $server = "mangrove";
-       if ($db->PConnect($server, "root", "", "northwind")) {
-               //$db->debug=1;$db->Execute('drop table ADOXYZ');
-               testdb($db,
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
-       } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
-}
-
-// REQUIRES MySQL server at localhost with database 'test'
-if (!empty($testmysqlodbc)) { // MYSQL
-       
-       $db = &ADONewConnection('odbc');
-       $db->hasTransactions = false;
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
-       else $server = "mangrove";
-       if ($db->PConnect('mysql', "root", ""))
-               testdb($db,
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
-       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
-}
-
-if (!empty($testproxy)){
-       $db = &ADONewConnection('proxy');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
-
-       if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))
-               testdb($db,
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
-       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
-
-}
-
-ADOLoadCode('oci805');
-ADOLoadCode("oci8po");
-if (!empty($testoracle)) { 
-       
-       $db = ADONewConnection('oci8po');
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if ($db->Connect('', "scott", "natsoft",''))
-       //if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my"))
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
-       else print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'<BR>'.$db->ErrorMsg();
-
-}
-ADOLoadCode("oracle"); // no longer supported
-if (false && !empty($testoracle)) { 
-       
-       $db = ADONewConnection();
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
-       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
-
-}
-
-ADOLoadCode("db2"); // no longer supported
-if (!empty($testdb2)) { 
-       
-       $db = ADONewConnection();
-       print "<h1>Connecting $db->databaseType...</h1>";
-       if ($db->Connect("db2_sample", "root", "natsoft", ""))
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
-       else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();
-
-}
-
-
-ADOLoadCode('odbc_mssql');
-if (!empty($testmssql)) { // MS SQL Server via ODBC
-       $db = ADONewConnection();
-       
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       $dsn = "mssql-northwind";
-       $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";
-       
-       if (@$db->PConnect($dsn, "adodb", "natsoft", ""))  {
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
-       }
-       else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
-
-}
-
-ADOLoadCode("ado_mssql");
-
-if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less
-       
-       $db = &ADONewConnection("ado_mssql");
-       //$db->debug=1;
-       print "<h1>Connecting DSN-less $db->databaseType...</h1>";
-       
-       $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
-               . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No"  ;
-
-               
-       if (@$db->PConnect($myDSN, "", "", ""))
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
-       else print "ERROR: MSSQL test 2 requires MS SQL 7";
-       
-}
-
-
-ADOLoadCode("mssqlpo");
-if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC
-       $db = ADONewConnection("mssqlpo");
-       //$db->debug=1;
-       print "<h1>Connecting $db->databaseType...</h1>";
-       
-       $ok = $db->PConnect('tigress','adodb','natsoft','northwind');
-       //$rs = $db->Execute("exec sp_ddate");
-       //print_r($rs->fields);
-       //die();
-
-       if ($ok or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {
-               AutoDetect_MSSQL_Date_Order($db);
-       //      $db->Execute('drop table adoxyz');
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
-       } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();
-       
-}
-
-if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider
-
-       $db = &ADONewConnection("ado_mssql");
-       print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";
-       //$db->debug=1;
-       $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes";
-       //$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;';
-       if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB'))
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
-       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";
-
-}
-
-
-print "<h3>Tests Completed</h3>";
-
-?>
+<?php\r
+  \r
+/*\r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence.\r
+*/ \r
\r
+ /* this file is used by the ADODB test program: test.php */\r
+ ?>\r
+\r
+<table><tr valign=top><td>\r
+<form method=get>\r
+<input type=checkbox name="testaccess" value=1 <?php echo !empty($testaccess) ? 'checked' : '' ?>> <b>Access</b><br>\r
+<input type=checkbox name="testibase" value=1 <?php echo !empty($testibase) ? 'checked' : '' ?>> <b>Interbase</b><br>\r
+<input type=checkbox name="testmssql" value=1 <?php echo !empty($testmssql) ? 'checked' : '' ?>> <b>MSSQL</b><br>\r
+ <input type=checkbox name="testmysql" value=1 <?php echo !empty($testmysql) ? 'checked' : '' ?>> <b>MySQL</b><br>\r
+<input type=checkbox name="testmysqlodbc" value=1 <?php echo !empty($testmysqlodbc) ? 'checked' : '' ?>> <b>MySQL ODBC</b><br>\r
+<td><input type=checkbox name="testsqlite" value=1 <?php echo !empty($testsqlite) ? 'checked' : '' ?>> <b>SQLite</b><br>\r
+<input type=checkbox name="testproxy" value=1 <?php echo !empty($testproxy) ? 'checked' : '' ?>> <b>MySQL Proxy</b><br>\r
+<input type=checkbox name="testoracle" value=1 <?php echo !empty($testoracle) ? 'checked' : '' ?>> <b>Oracle (oci8)</b> <br>\r
+<input type=checkbox name="testpostgres" value=1 <?php echo !empty($testpostgres) ? 'checked' : '' ?>> <b>PostgreSQL</b><br>\r
+<input type=checkbox name="testpgodbc" value=1 <?php echo !empty($testpgodbc) ? 'checked' : '' ?>> <b>PostgreSQL ODBC</b><br>\r
+<td><input type=checkbox name="testdb2" value=1 <?php echo !empty($testdb2) ? 'checked' : '' ?>> DB2<br>\r
+<input type=checkbox name="testvfp" value=1 <?php echo !empty($testvfp) ? 'checked' : '' ?>> VFP<br>\r
+<input type=checkbox name="testado" value=1 <?php echo !empty($testado) ? 'checked' : '' ?>> ADO (for mssql and access)<br>\r
+<input type=checkbox name="nocountrecs" value=1 <?php echo !empty($nocountrecs) ? 'checked' : '' ?>> $ADODB_COUNTRECS=false<br>\r
+<input type=checkbox name="nolog" value=1 <?php echo !empty($nolog) ? 'checked' : '' ?>> No SQL Logging<br>\r
+<td><input type=submit>\r
+</form>\r
+</table>\r
+<?php\r
+\r
+if ($ADODB_FETCH_MODE != ADODB_FETCH_DEFAULT) print "<h3>FETCH MODE IS NOT ADODB_FETCH_DEFAULT</h3>";\r
+\r
+if (isset($nocountrecs)) $ADODB_COUNTRECS = false;\r
+\r
+// cannot test databases below, but we include them anyway to check\r
+// if they parse ok...\r
+\r
+if (!strpos(PHP_VERSION,'5') === 0) {\r
+       ADOLoadCode("sybase");\r
+       ADOLoadCode("postgres");\r
+       ADOLoadCode("postgres7");\r
+       ADOLoadCode("firebird");\r
+       ADOLoadCode("borland_ibase");\r
+       ADOLoadCode("informix");\r
+       ADOLoadCode("sqlanywhere");\r
+//     ADOLoadCode('mysqli');\r
+}\r
+\r
+\r
+flush();\r
+if (!empty($testpostgres)) {\r
+       //ADOLoadCode("postgres");\r
+\r
+       $db = &ADONewConnection('postgres');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->Connect("localhost","tester","test","test")) {\r
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");\r
+       }else\r
+               print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();\r
+}\r
+\r
+if (!empty($testpgodbc)) { \r
+       \r
+       $db = &ADONewConnection('odbc');\r
+       $db->hasTransactions = false;\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       if ($db->PConnect('Postgresql')) {\r
+               $db->hasTransactions = true;\r
+               testdb($db,\r
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
+       } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();\r
+}\r
+\r
+if (!empty($testibase)) {\r
+       //$_GET['nolog'] = true;\r
+       $db = &ADONewConnection('firebird');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (@$db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", ""))\r
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");\r
+        else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+\r
+if (!empty($testsqlite)) {\r
+       $db = &ADONewConnection('sqlite');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       if (@$db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: SQLite";\r
+       \r
+}\r
+\r
+// REQUIRES ODBC DSN CALLED nwind\r
+if (!empty($testaccess)) {\r
+       $db = &ADONewConnection('access');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       $dsn = "nwind";\r
+       $driver = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\inetpub\adodb\northwind.mdb;Uid=Admin;Pwd=;";\r
+       if (@$db->PConnect($dsn, "", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";\r
+       \r
+}\r
+\r
+if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS\r
+\r
+       $db = &ADONewConnection("ado_access");\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       $access = 'd:\inetpub\wwwroot\php\NWIND.MDB';\r
+       $myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'\r
+               . 'DATA SOURCE=' . $access . ';';\r
+               //. 'USER ID=;PASSWORD=;';\r
+       \r
+       if (@$db->PConnect($myDSN, "", "", "")) {\r
+               print "ADO version=".$db->_connectionID->version."<br>";\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       } else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+if (!empty($testvfp)) { // ODBC\r
+       $db = &ADONewConnection('vfp');\r
+       print "<h1>Connecting $db->databaseType...</h1>";flush();\r
+\r
+       if ( $db->PConnect("vfp-adoxyz")) {\r
+               testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");\r
+        } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";\r
+       \r
+}\r
+\r
+\r
+// REQUIRES MySQL server at localhost with database 'test'\r
+if (!empty($testmysql)) { // MYSQL\r
+\r
+       $db = &ADONewConnection('mysql');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
+       else $server = "mangrove";\r
+       if ($db->PConnect($server, "root", "", "northwind")) {\r
+               //$db->debug=1;$db->Execute('drop table ADOXYZ');\r
+               testdb($db,\r
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");\r
+       } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
+}\r
+\r
+// REQUIRES MySQL server at localhost with database 'test'\r
+if (!empty($testmysqli)) { // MYSQL\r
+\r
+       $db = &ADONewConnection('mysqli');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
+       else $server = "mangrove";\r
+       if ($db->PConnect($server, "root", "", "northwind")) {\r
+               //$db->debug=1;$db->Execute('drop table ADOXYZ');\r
+               testdb($db,\r
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");\r
+       } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
+}\r
+\r
+\r
+// REQUIRES MySQL server at localhost with database 'test'\r
+if (!empty($testmysqlodbc)) { // MYSQL\r
+       \r
+       $db = &ADONewConnection('odbc');\r
+       $db->hasTransactions = false;\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
+       else $server = "mangrove";\r
+       if ($db->PConnect('mysql', "root", ""))\r
+               testdb($db,\r
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
+       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
+}\r
+\r
+if (!empty($testproxy)){\r
+       $db = &ADONewConnection('proxy');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
+\r
+       if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))\r
+               testdb($db,\r
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
+       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+\r
+ADOLoadCode('oci805');\r
+ADOLoadCode("oci8po");\r
+if (!empty($testoracle)) { \r
+       \r
+       $db = ADONewConnection('oci8po');\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($db->Connect('', "scott", "natsoft",''))\r
+       //if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my"))\r
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+ADOLoadCode("oracle"); // no longer supported\r
+if (false && !empty($testoracle)) { \r
+       \r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))\r
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+\r
+ADOLoadCode("db2"); // no longer supported\r
+if (!empty($testdb2)) { \r
+       \r
+       $db = ADONewConnection();\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       if ($db->Connect("db2_sample", "root", "natsoft", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
+       else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();\r
+\r
+}\r
+\r
+\r
+ADOLoadCode('odbc_mssql');\r
+if (!empty($testmssql)) { // MS SQL Server via ODBC\r
+       $db = ADONewConnection();\r
+       \r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       $dsn = "mssql-northwind";\r
+       $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";\r
+       \r
+       if (@$db->PConnect($dsn, "adodb", "natsoft", ""))  {\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
+       }\r
+       else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";\r
+\r
+}\r
+\r
+ADOLoadCode("ado_mssql");\r
+\r
+if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less\r
+       \r
+       $db = &ADONewConnection("ado_mssql");\r
+       //$db->debug=1;\r
+       print "<h1>Connecting DSN-less $db->databaseType...</h1>";\r
+       \r
+       $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"\r
+               . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No"  ;\r
+\r
+               \r
+       if (@$db->PConnect($myDSN, "", "", ""))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
+       else print "ERROR: MSSQL test 2 requires MS SQL 7";\r
+       \r
+}\r
+\r
+\r
+ADOLoadCode("mssqlpo");\r
+if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC\r
+       $db = ADONewConnection("mssqlpo");\r
+       //$db->debug=1;\r
+       print "<h1>Connecting $db->databaseType...</h1>";\r
+       \r
+       $ok = $db->PConnect('tigress','adodb','natsoft','northwind');\r
+       //$rs = $db->Execute("exec sp_ddate");\r
+       //print_r($rs->fields);\r
+       //die();\r
+\r
+       if ($ok or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {\r
+               AutoDetect_MSSQL_Date_Order($db);\r
+       //      $db->Execute('drop table adoxyz');\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
+       } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();\r
+       \r
+}\r
+\r
+if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider\r
+\r
+       $db = &ADONewConnection("ado_mssql");\r
+       print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";\r
+       //$db->debug=1;\r
+       $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes";\r
+       //$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;';\r
+       if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB'))\r
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
+       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";\r
+\r
+}\r
+\r
+\r
+print "<h3>Tests Completed</h3>";\r
+\r
+?>\r
index 479f7124b53e15d2b4ec4770b019e1b42db5ed32..14b48ce3c2ce5b62c1467b446ea023719758993f 100644 (file)
@@ -1,36 +1,36 @@
-<?php
-/*
-       V4.20 22 Feb 2004 
-       
-       Run multiple copies of this php script at the same time
-       to test unique generation of id's in multiuser mode
-*/
-include_once('../adodb.inc.php');
-$testaccess = true;
-include_once('testdatabases.inc.php');
-
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
-{
-       $table = 'adodbseq';
-       
-       $db->Execute("drop table $table");
-       //$db->debug=true;
-       
-       $ctr = 5000;
-       $lastnum = 0;
-       
-       while (--$ctr >= 0) {
-               $num = $db->GenID($table);
-               if ($num === false) {   
-                       print "GenID returned false";
-                       break;
-               }
-               if ($lastnum + 1 == $num) print " $num ";
-               else {
-                       print " <font color=red>$num</font> ";
-                       flush();
-               }
-               $lastnum = $num;
-       }
-}
+<?php\r
+/*\r
+       V4.50 6 July 2004 \r
+       \r
+       Run multiple copies of this php script at the same time\r
+       to test unique generation of id's in multiuser mode\r
+*/\r
+include_once('../adodb.inc.php');\r
+$testaccess = true;\r
+include_once('testdatabases.inc.php');\r
+\r
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
+{\r
+       $table = 'adodbseq';\r
+       \r
+       $db->Execute("drop table $table");\r
+       //$db->debug=true;\r
+       \r
+       $ctr = 5000;\r
+       $lastnum = 0;\r
+       \r
+       while (--$ctr >= 0) {\r
+               $num = $db->GenID($table);\r
+               if ($num === false) {   \r
+                       print "GenID returned false";\r
+                       break;\r
+               }\r
+               if ($lastnum + 1 == $num) print " $num ";\r
+               else {\r
+                       print " <font color=red>$num</font> ";\r
+                       flush();\r
+               }\r
+               $lastnum = $num;\r
+       }\r
+}\r
 ?>
\ No newline at end of file
index 6db4123c19443138269263f36c1eb64b0de74324..9ff90ced5b885e9159f7a166a95be93728f467cb 100644 (file)
@@ -1,76 +1,76 @@
-<?php
-
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
- * Released under both BSD license and Lesser GPL library license. 
- * Whenever there is any discrepancy between the two licenses, 
- * the BSD license will take precedence. 
- *
- * Set tabs to 4 for best viewing.
- * 
- * Latest version is available at http://php.weblogs.com
- *
- * Test GetUpdateSQL and GetInsertSQL.
- */
-error_reporting(E_ALL);
-
-
-include('../adodb.inc.php');
-include('../tohtml.inc.php');
-
-//==========================
-// This code tests an insert
-
-
-
-$conn = &ADONewConnection("mssql");  // create a connection
-$conn->Connect('localhost','sa','natsoft','northwind') or die('Fail');
-
-$conn->debug =1;
-$query = 'select * from products';
-$conn->SetFetchMode(ADODB_FETCH_ASSOC);
-$rs = $conn->Execute($query);
-echo "<pre>";
-while( !$rs->EOF ) {
-       $output[] = $rs->fields;
-       var_dump($rs->fields);
-       $rs->MoveNext();
-       print "<p>";
-}
-die();
-
-
-$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)');
-echo "<pre>";
-print_r($p);
-
-$conn->debug=1;
-$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time())));
-
-$p = $conn->Prepare('select * from products where productname like ?');
-$arr = $conn->getarray($p,array('V%'));
-print_r($arr);
-die();
-
-//$conn = &ADONewConnection("mssql");
-//$conn->Connect('mangrove','sa','natsoft','ai');
-
-//$conn->Connect('mangrove','sa','natsoft','ai');
-$conn->debug=1;
-$conn->Execute('delete from blobtest');
-
-$conn->Execute('insert into blobtest (id) values(1)');
-$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');
-$rs = $conn->Execute('select b1 from blobtest where id=1');
-
-$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; 
-print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";
-$fd = fopen($output, "wb"); 
-fwrite($fd, $rs->fields[0]); 
-fclose($fd); 
-
-print " <a href=file://$output>View Image</a>";
-//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');
-//rs2html($rs);
+<?php\r
+\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Set tabs to 4 for best viewing.\r
+ * \r
+ * Latest version is available at http://php.weblogs.com\r
+ *\r
+ * Test GetUpdateSQL and GetInsertSQL.\r
+ */\r
\r
+error_reporting(E_ALL);\r
+\r
+\r
+include('../adodb.inc.php');\r
+include('../tohtml.inc.php');\r
+\r
+//==========================\r
+// This code tests an insert\r
+\r
+\r
+\r
+$conn = &ADONewConnection("mssql");  // create a connection\r
+$conn->Connect('localhost','sa','natsoft','northwind') or die('Fail');\r
+\r
+$conn->debug =1;\r
+$query = 'select * from products';\r
+$conn->SetFetchMode(ADODB_FETCH_ASSOC);\r
+$rs = $conn->Execute($query);\r
+echo "<pre>";\r
+while( !$rs->EOF ) {\r
+       $output[] = $rs->fields;\r
+       var_dump($rs->fields);\r
+       $rs->MoveNext();\r
+       print "<p>";\r
+}\r
+die();\r
+\r
+\r
+$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)');\r
+echo "<pre>";\r
+print_r($p);\r
+\r
+$conn->debug=1;\r
+$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time())));\r
+\r
+$p = $conn->Prepare('select * from products where productname like ?');\r
+$arr = $conn->getarray($p,array('V%'));\r
+print_r($arr);\r
+die();\r
+\r
+//$conn = &ADONewConnection("mssql");\r
+//$conn->Connect('mangrove','sa','natsoft','ai');\r
+\r
+//$conn->Connect('mangrove','sa','natsoft','ai');\r
+$conn->debug=1;\r
+$conn->Execute('delete from blobtest');\r
+\r
+$conn->Execute('insert into blobtest (id) values(1)');\r
+$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');\r
+$rs = $conn->Execute('select b1 from blobtest where id=1');\r
+\r
+$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; \r
+print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";\r
+$fd = fopen($output, "wb"); \r
+fwrite($fd, $rs->fields[0]); \r
+fclose($fd); \r
+\r
+print " <a href=file://$output>View Image</a>";\r
+//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');\r
+//rs2html($rs);\r
 ?>
\ No newline at end of file
index d748efca463af2d0b52fd462f3f9f93319c80d02..df9a38277a1a354ea7c4113592184fa2dca22de9 100644 (file)
@@ -1,70 +1,69 @@
-<html>
-<body>
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-error_reporting(63);
-include("../adodb.inc.php");
-include("../tohtml.inc.php");
-
-if (1) {
-       $db = ADONewConnection('oci8po');
-       
-       $db->PConnect('','scott','tiger');
-
-       if (!empty($testblob)) {
-               $varHoldingBlob = 'ABC DEF GEF John TEST';
-               $num = time()%10240;
-               // create table atable (id integer, ablob blob);
-               $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');
-               $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');
-               
-               $rs = &$db->Execute('select * from atable');
-               
-               if (!$rs) die("Empty RS");
-               if ($rs->EOF) die("EOF RS");
-               rs2html($rs);
-       }
-       $stmt = $db->Prepare('select * from adoxyz where id=?');
-       for ($i = 1; $i <= 10; $i++) {
-       $rs = &$db->Execute(
-               $stmt,
-               array($i));
-                       
-               if (!$rs) die("Empty RS");
-               if ($rs->EOF) die("EOF RS");
-               rs2html($rs);
-       }
-}
-if (1) {
-       $db = ADONewConnection('oci8');
-       $db->PConnect('','scott','tiger');
-       $db->debug = true;
-       $db->Execute("delete from emp where ename='John'");
-       print $db->Affected_Rows().'<BR>';
-       $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
-       $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));
-       // prepare not quite ready for prime time
-       //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));
-       if (!$rs) die("Empty RS");
-}
-
-if (0) {
-       $db = ADONewConnection('odbc_oracle');
-       if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');
-       $db->debug = true;
-       $rs = &$db->Execute(
-               'select * from adoxyz where firstname=? and trim(lastname)=?',
-               array('first'=>'Caroline','last'=>'Miranda'));
-       if (!$rs) die("Empty RS");
-       if ($rs->EOF) die("EOF RS");
-       rs2html($rs);
-}
+<html>\r
+<body>\r
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+error_reporting(63);\r
+include("../adodb.inc.php");\r
+include("../tohtml.inc.php");\r
+\r
+if (1) {\r
+       $db = ADONewConnection('oci8po');\r
+       \r
+       $db->PConnect('','scott','natsoft');\r
+       if (!empty($testblob)) {\r
+               $varHoldingBlob = 'ABC DEF GEF John TEST';\r
+               $num = time()%10240;\r
+               // create table atable (id integer, ablob blob);\r
+               $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');\r
+               $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');\r
+               \r
+               $rs = &$db->Execute('select * from atable');\r
+               \r
+               if (!$rs) die("Empty RS");\r
+               if ($rs->EOF) die("EOF RS");\r
+               rs2html($rs);\r
+       }\r
+       $stmt = $db->Prepare('select * from adoxyz where id=?');\r
+       for ($i = 1; $i <= 10; $i++) {\r
+       $rs = &$db->Execute(\r
+               $stmt,\r
+               array($i));\r
+                       \r
+               if (!$rs) die("Empty RS");\r
+               if ($rs->EOF) die("EOF RS");\r
+               rs2html($rs);\r
+       }\r
+}\r
+if (1) {\r
+       $db = ADONewConnection('oci8');\r
+       $db->PConnect('','scott','tiger');\r
+       $db->debug = true;\r
+       $db->Execute("delete from emp where ename='John'");\r
+       print $db->Affected_Rows().'<BR>';\r
+       $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
+       $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));\r
+       // prepare not quite ready for prime time\r
+       //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));\r
+       if (!$rs) die("Empty RS");\r
+}\r
+\r
+if (0) {\r
+       $db = ADONewConnection('odbc_oracle');\r
+       if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');\r
+       $db->debug = true;\r
+       $rs = &$db->Execute(\r
+               'select * from adoxyz where firstname=? and trim(lastname)=?',\r
+               array('first'=>'Caroline','last'=>'Miranda'));\r
+       if (!$rs) die("Empty RS");\r
+       if ($rs->EOF) die("EOF RS");\r
+       rs2html($rs);\r
+}\r
 ?>
\ No newline at end of file
index a80fc9b9392d9382d2210f37856bb4145459905b..c87204886281cf9cbaa689d5d982091e6cca3fe2 100644 (file)
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-/*
-       Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.
-       
-       We have 2 examples. The first shows us using the Parameter statement. 
-       The second shows us using the new ExecuteCursor($sql, $cursorName)
-       function.
-       
-------------------------------------------------------------------
--- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus
-------------------------------------------------------------------
-
-
--- TEST PACKAGE
-CREATE OR REPLACE PACKAGE adodb AS
-TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
-PROCEDURE data_out(input IN varchar, output OUT varchar); 
-
-procedure myproc (p1 in number, p2 out number);
-END adodb;
-/
-
-CREATE OR REPLACE PACKAGE BODY adodb AS
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
-       BEGIN
-               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
-       END open_tab;
-       
-PROCEDURE data_out(input IN varchar, output OUT varchar) IS
-       BEGIN
-               output := 'Cinta Hati '||input;
-       END;
-       
-procedure myproc (p1 in number, p2 out number) as
-begin
-p2 := p1;
-end;
-END adodb;
-/
-
-------------------------------------------------------------------
--- END PACKAGE
-------------------------------------------------------------------
-
-*/
-
-include('../adodb.inc.php');
-include('../tohtml.inc.php');
-
-       error_reporting(E_ALL);
-       $db = ADONewConnection('oci8');
-       $db->PConnect('','scott','natsoft');
-       $db->debug = 99;
-
-
-/*
-*/
-
-       define('MYNUM',5);
-       
-
-       
-       $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'A%'); END;");
-       $db->InParameter($stmt, $cur, 'RS', -1, OCI_B_CURSOR);
-       $rs = $db->Execute($stmt);
-
-       if ($rs && !$rs->EOF) {
-               print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
-       } else {
-               print "<b>Error in using Cursor Variables 1</b><p>";
-       }
-       
-       
-       print "<h4>Testing Stored Procedures for oci8</h4>";
-       
-       $stid = $db->PrepareSP('BEGIN adodb.myproc('.MYNUM.', :myov); END;');
-       $db->OutParameter($stid, $myov, 'myov');
-       $db->Execute($stid);
-       if ($myov != MYNUM) print "<p><b>Error with myproc</b></p>";
-       
-       
-       $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;",true);
-       $a1 = 'Malaysia';
-       //$a2 = ''; # a2 doesn't even need to be defined!
-       $db->InParameter($stmt,$a1,'a1');
-       $db->OutParameter($stmt,$a2,'a2');
-       $rs = $db->Execute($stmt);
-       if ($rs) {
-               if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
-               else echo  "OK: a2=$a2<p>";
-       } else {
-               print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
-       }
-       
-       
-       $tname = 'A%';
-       
-       $stmt = $db->PrepareSP('select * from tab where tname like :tablename');
-       $db->Parameter($stmt,$tname,'tablename');
-       $rs = $db->Execute($stmt);
-       rs2html($rs);
-               
-               
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+/*\r
+       Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.\r
+       \r
+       We have 2 examples. The first shows us using the Parameter statement. \r
+       The second shows us using the new ExecuteCursor($sql, $cursorName)\r
+       function.\r
+       \r
+------------------------------------------------------------------\r
+-- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus\r
+------------------------------------------------------------------\r
+\r
+\r
+-- TEST PACKAGE\r
+CREATE OR REPLACE PACKAGE adodb AS\r
+TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;\r
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);\r
+PROCEDURE data_out(input IN varchar, output OUT varchar); \r
+\r
+procedure myproc (p1 in number, p2 out number);\r
+END adodb;\r
+/\r
+\r
+CREATE OR REPLACE PACKAGE BODY adodb AS\r
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS\r
+       BEGIN\r
+               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;\r
+       END open_tab;\r
+       \r
+PROCEDURE data_out(input IN varchar, output OUT varchar) IS\r
+       BEGIN\r
+               output := 'Cinta Hati '||input;\r
+       END;\r
+       \r
+procedure myproc (p1 in number, p2 out number) as\r
+begin\r
+p2 := p1;\r
+end;\r
+END adodb;\r
+/\r
+\r
+------------------------------------------------------------------\r
+-- END PACKAGE\r
+------------------------------------------------------------------\r
+\r
+*/\r
+\r
+include('../adodb.inc.php');\r
+include('../tohtml.inc.php');\r
+\r
+       error_reporting(E_ALL);\r
+       $db = ADONewConnection('oci8');\r
+       $db->PConnect('','scott','natsoft');\r
+       $db->debug = 99;\r
+\r
+\r
+/*\r
+*/\r
+\r
+       define('MYNUM',5);\r
+       \r
+\r
+       $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS,'A%'); END;");\r
+       \r
+       if ($rs && !$rs->EOF) {\r
+               print "Test 1 RowCount: ".$rs->RecordCount()."<p>";\r
+       } else {\r
+               print "<b>Error in using Cursor Variables 1</b><p>";\r
+       }\r
+       \r
+       print "<h4>Testing Stored Procedures for oci8</h4>";\r
+       \r
+       $stid = $db->PrepareSP('BEGIN adodb.myproc('.MYNUM.', :myov); END;');\r
+       $db->OutParameter($stid, $myov, 'myov');\r
+       $db->Execute($stid);\r
+       if ($myov != MYNUM) print "<p><b>Error with myproc</b></p>";\r
+       \r
+       \r
+       $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;",true);\r
+       $a1 = 'Malaysia';\r
+       //$a2 = ''; # a2 doesn't even need to be defined!\r
+       $db->InParameter($stmt,$a1,'a1');\r
+       $db->OutParameter($stmt,$a2,'a2');\r
+       $rs = $db->Execute($stmt);\r
+       if ($rs) {\r
+               if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";\r
+               else echo  "OK: a2=$a2<p>";\r
+       } else {\r
+               print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";\r
+       }\r
+       \r
+       \r
+       $tname = 'A%';\r
+       \r
+       $stmt = $db->PrepareSP('select * from tab where tname like :tablename');\r
+       $db->Parameter($stmt,$tname,'tablename');\r
+       $rs = $db->Execute($stmt);\r
+       rs2html($rs);\r
+               \r
+               \r
 ?>
\ No newline at end of file
index 89c9594649df5eaad99127596681db71dd9662ff..b95fd005e614cf78eb2f12727a529ebddd9d8e29 100644 (file)
@@ -1,83 +1,83 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-error_reporting(E_ALL);
-
-
-include_once('../adodb.inc.php');
-include_once('../adodb-pager.inc.php');
-
-$driver = 'oci8';
-$sql = 'select  ID, firstname as "First Name", lastname as "Last Name" from adoxyz  order  by  id';
-//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';
-$sql = 'select distinct firstname, lastname from adoxyz  order  by  firstname';
-
-if ($driver == 'postgres') {
-       $db = NewADOConnection('postgres');
-       $db->PConnect('localhost','tester','test','test');
-}
-
-if ($driver == 'access') {
-       $db = NewADOConnection('access');
-       $db->PConnect("nwind", "", "", "");
-}
-
-if ($driver == 'ibase') {
-       $db = NewADOConnection('ibase');
-       $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");
-       $sql = 'select distinct firstname, lastname  from adoxyz  order  by  firstname';
-
-}
-if ($driver == 'mssql') {
-       $db = NewADOConnection('mssql');
-       $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
-}
-if ($driver == 'oci8') {
-       $db = NewADOConnection('oci8');
-       $db->Connect('','scott','natsoft');
-}
-
-if ($driver == 'access') {
-       $db = NewADOConnection('access');
-       $db->Connect('nwind');
-}
-
-if (empty($driver) or $driver == 'mysql') {
-       $db = NewADOConnection('mysql');
-       $db->Connect('localhost','root','','xphplens');
-}
-
-//$db->pageExecuteCountRows = false;
-
-$db->debug = true;
-
-if (0) {
-$rs = &$db->Execute($sql);
-include_once('../toexport.inc.php');
-print "<pre>";
-print rs2csv($rs); # return a string
-
-print '<hr>';
-$rs->MoveFirst(); # note, some databases do not support MoveFirst
-print rs2tab($rs); # return a string
-
-print '<hr>';
-$rs->MoveFirst();
-rs2tabout($rs); # send to stdout directly
-print "</pre>";
-}
-
-$pager = new ADODB_Pager($db,$sql);
-$pager->showPageLinks = true;
-$pager->linksPerPage = 3;
-$pager->cache = 60;
-$pager->Render($rows=7);
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+error_reporting(E_ALL);\r
+\r
+\r
+include_once('../adodb.inc.php');\r
+include_once('../adodb-pager.inc.php');\r
+\r
+$driver = 'oci8';\r
+$sql = 'select  ID, firstname as "First Name", lastname as "Last Name" from adoxyz  order  by  id';\r
+//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';\r
+$sql = 'select distinct firstname, lastname from adoxyz  order  by  firstname';\r
+\r
+if ($driver == 'postgres') {\r
+       $db = NewADOConnection('postgres');\r
+       $db->PConnect('localhost','tester','test','test');\r
+}\r
+\r
+if ($driver == 'access') {\r
+       $db = NewADOConnection('access');\r
+       $db->PConnect("nwind", "", "", "");\r
+}\r
+\r
+if ($driver == 'ibase') {\r
+       $db = NewADOConnection('ibase');\r
+       $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");\r
+       $sql = 'select distinct firstname, lastname  from adoxyz  order  by  firstname';\r
+\r
+}\r
+if ($driver == 'mssql') {\r
+       $db = NewADOConnection('mssql');\r
+       $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');\r
+}\r
+if ($driver == 'oci8') {\r
+       $db = NewADOConnection('oci8');\r
+       $db->Connect('','scott','natsoft');\r
+}\r
+\r
+if ($driver == 'access') {\r
+       $db = NewADOConnection('access');\r
+       $db->Connect('nwind');\r
+}\r
+\r
+if (empty($driver) or $driver == 'mysql') {\r
+       $db = NewADOConnection('mysql');\r
+       $db->Connect('localhost','root','','xphplens');\r
+}\r
+\r
+//$db->pageExecuteCountRows = false;\r
+\r
+$db->debug = true;\r
+\r
+if (0) {\r
+$rs = &$db->Execute($sql);\r
+include_once('../toexport.inc.php');\r
+print "<pre>";\r
+print rs2csv($rs); # return a string\r
+\r
+print '<hr>';\r
+$rs->MoveFirst(); # note, some databases do not support MoveFirst\r
+print rs2tab($rs); # return a string\r
+\r
+print '<hr>';\r
+$rs->MoveFirst();\r
+rs2tabout($rs); # send to stdout directly\r
+print "</pre>";\r
+}\r
+\r
+$pager = new ADODB_Pager($db,$sql);\r
+$pager->showPageLinks = true;\r
+$pager->linksPerPage = 3;\r
+$pager->cache = 60;\r
+$pager->Render($rows=7);\r
 ?>
\ No newline at end of file
index 05ef8ca87199c8f324a2c7f0d9c81e4f9a042649..2ad82c999fa40d234b7944075d79ece14b441921 100644 (file)
@@ -1,34 +1,34 @@
-<?php
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-error_reporting(E_ALL);
-
-include_once('../adodb-pear.inc.php');
-$username = 'root';
-$password = '';
-$hostname = 'localhost';
-$databasename = 'xphplens';
-$driver = 'mysql';
-
-$dsn = "$driver://$username:$password@$hostname/$databasename";
-
-$db = DB::Connect($dsn);
-$db->setFetchMode(ADODB_FETCH_ASSOC);
-$rs = $db->Query('select firstname,lastname from adoxyz');
-$cnt = 0;
-while ($arr = $rs->FetchRow()) {
-       print_r($arr);
-       print "<br>";
-       $cnt += 1;
-}
-
-if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";
+<?php\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+error_reporting(E_ALL);\r
+\r
+include_once('../adodb-pear.inc.php');\r
+$username = 'root';\r
+$password = '';\r
+$hostname = 'localhost';\r
+$databasename = 'xphplens';\r
+$driver = 'mysql';\r
+\r
+$dsn = "$driver://$username:$password@$hostname/$databasename";\r
+\r
+$db = DB::Connect($dsn);\r
+$db->setFetchMode(ADODB_FETCH_ASSOC);\r
+$rs = $db->Query('select firstname,lastname from adoxyz');\r
+$cnt = 0;\r
+while ($arr = $rs->FetchRow()) {\r
+       print_r($arr);\r
+       print "<br>";\r
+       $cnt += 1;\r
+}\r
+\r
+if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";\r
 ?>
\ No newline at end of file
index 691aa5f988abab5c87ee90416a98dbe14cdc3d9c..8854d634a057ccab086d04b173c887ae28697440 100644 (file)
@@ -1,66 +1,66 @@
-<?php
-
-/* 
-V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license. 
-  Whenever there is any discrepancy between the two licenses, 
-  the BSD license will take precedence. 
-  Set tabs to 4 for best viewing.
-       
-  Latest version is available at http://php.weblogs.com/
-*/
-
-function NotifyExpire($ref,$key)
-{
-       print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";
-}
-
-//-------------------------------------------------------------------
-       
-       
-#### CONNECTION
-       $ADODB_SESSION_DRIVER='oci8';
-       $ADODB_SESSION_CONNECT='';
-       $ADODB_SESSION_USER ='scott';
-       $ADODB_SESSION_PWD ='natsoft';
-       $ADODB_SESSION_DB ='';
-       
-       
-### TURN DEBUGGING ON
-       $ADODB_SESS_DEBUG = true;
-
-       
-#### SETUP NOTIFICATION
-       $USER = 'JLIM'.rand();
-       $ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');
-
-       
-#### INIT
-       ob_start();
-       error_reporting(E_ALL);
-       include('../session/adodb-cryptsession.php');
-       session_start();
-
-
-### SETUP SESSION VARIABLES 
-       $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);
-       if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;
-
-       
-### START DISPLAY
-       print "<h3>PHP ".PHP_VERSION."</h3>";
-       print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";
-       
-       print "<hr> <b>Cookies</b>: ";
-       print_r($HTTP_COOKIE_VARS);
-       
-### RANDOMLY PERFORM Garbage Collection
-       if (rand() % 10 == 0) {
-       
-               print "<hr><p><b>Garbage Collection</b></p>";
-               adodb_sess_gc(10);
-               
-               print "<p>Random session destroy</p>";
-               session_destroy();
-       }
+<?php\r
+\r
+/* \r
+V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  Released under both BSD license and Lesser GPL library license. \r
+  Whenever there is any discrepancy between the two licenses, \r
+  the BSD license will take precedence. \r
+  Set tabs to 4 for best viewing.\r
+       \r
+  Latest version is available at http://adodb.sourceforge.net\r
+*/\r
+\r
+function NotifyExpire($ref,$key)\r
+{\r
+       print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";\r
+}\r
+\r
+//-------------------------------------------------------------------\r
+       \r
+       \r
+#### CONNECTION\r
+       $ADODB_SESSION_DRIVER='oci8';\r
+       $ADODB_SESSION_CONNECT='';\r
+       $ADODB_SESSION_USER ='scott';\r
+       $ADODB_SESSION_PWD ='natsoft';\r
+       $ADODB_SESSION_DB ='';\r
+       \r
+       \r
+### TURN DEBUGGING ON\r
+       $ADODB_SESS_DEBUG = true;\r
+\r
+       \r
+#### SETUP NOTIFICATION\r
+       $USER = 'JLIM'.rand();\r
+       $ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');\r
+\r
+       \r
+#### INIT\r
+       ob_start();\r
+       error_reporting(E_ALL);\r
+       include('../session/adodb-cryptsession.php');\r
+       session_start();\r
+\r
+\r
+### SETUP SESSION VARIABLES \r
+       $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);\r
+       if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;\r
+\r
+       \r
+### START DISPLAY\r
+       print "<h3>PHP ".PHP_VERSION."</h3>";\r
+       print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";\r
+       \r
+       print "<hr> <b>Cookies</b>: ";\r
+       print_r($HTTP_COOKIE_VARS);\r
+       \r
+### RANDOMLY PERFORM Garbage Collection\r
+       if (rand() % 10 == 0) {\r
+       \r
+               print "<hr><p><b>Garbage Collection</b></p>";\r
+               adodb_sess_gc(10);\r
+               \r
+               print "<p>Random session destroy</p>";\r
+               session_destroy();\r
+       }\r
 ?>
\ No newline at end of file
index 80c9e2af3a08ea2a362bfd00c70a7e175cd2983a..db84eae26c1431cb018287ebf528dc29af763c82 100644 (file)
-<?php
-
-/** 
- * @version V4.20 22 Feb 2004 (c) 2000-2004 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. 
- *
- * Code to export recordsets in several formats:
- *
- * AS VARIABLE
- * $s = rs2csv($rs); # comma-separated values
- * $s = rs2tab($rs); # tab delimited
- * 
- * TO A FILE
- * $f = fopen($path,'w');
- * rs2csvfile($rs,$f);
- * fclose($f);
- *
- * TO STDOUT
- * rs2csvout($rs);
- */
-// returns a recordset as a csv string
-function rs2csv(&$rs,$addtitles=true)
-{
-       return _adodb_export($rs,',',',',false,$addtitles);
-}
-
-// writes recordset to csv file 
-function rs2csvfile(&$rs,$fp,$addtitles=true)
-{
-       _adodb_export($rs,',',',',$fp,$addtitles);
-}
-
-// write recordset as csv string to stdout
-function rs2csvout(&$rs,$addtitles=true)
-{
-       $fp = fopen('php://stdout','wb');
-       _adodb_export($rs,',',',',true,$addtitles);
-       fclose($fp);
-}
-
-function rs2tab(&$rs,$addtitles=true)
-{
-       return _adodb_export($rs,"\t",',',false,$addtitles);
-}
-
-// to file pointer
-function rs2tabfile(&$rs,$fp,$addtitles=true)
-{
-       _adodb_export($rs,"\t",',',$fp,$addtitles);
-}
-
-// to stdout
-function rs2tabout(&$rs,$addtitles=true)
-{
-       $fp = fopen('php://stdout','wb');
-       _adodb_export($rs,"\t",' ',true,$addtitles);
-       fclose($fp);
-}
-
-function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
-{
-       if (!$rs) return '';
-       //----------
-       // CONSTANTS
-       $NEWLINE = "\r\n";
-       $BUFLINES = 100;
-       $escquotequote = $escquote.$quote;
-       $s = '';
-       
-       if ($addtitles) {
-               $fieldTypes = $rs->FieldTypesArray();
-               reset($fieldTypes);
-               while(list(,$o) = each($fieldTypes)) {
-                       
-                       $v = $o->name;
-                       if ($escquote) $v = str_replace($quote,$escquotequote,$v);
-                       $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
-                       $elements[] = $v;
-                       
-               }
-               $s .= implode($sep, $elements).$NEWLINE;
-       }
-       $hasNumIndex = isset($rs->fields[0]);
-       
-       $line = 0;
-       $max = $rs->FieldCount();
-       
-       while (!$rs->EOF) {
-               $elements = array();
-               $i = 0;
-               
-               if ($hasNumIndex) {
-                       for ($j=0; $j < $max; $j++) {
-                               $v = trim($rs->fields[$j]);
-                               if ($escquote) $v = str_replace($quote,$escquotequote,$v);
-                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
-                               
-                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
-                               else $elements[] = $v;
-                       }
-               } else { // ASSOCIATIVE ARRAY
-                       foreach($rs->fields as $v) {
-                               if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
-                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
-                               
-                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
-                               else $elements[] = $v;
-                       }
-               }
-               $s .= implode($sep, $elements).$NEWLINE;
-               $rs->MoveNext();
-               $line += 1;
-               if ($fp && ($line % $BUFLINES) == 0) {
-                       if ($fp === true) echo $s;
-                       else fwrite($fp,$s);
-                       $s = '';
-               }
-       }
-       
-       if ($fp) {
-               if ($fp === true) echo $s;
-               else fwrite($fp,$s);
-               $s = '';
-       }
-       
-       return $s;
-}
+<?php\r
+\r
+/** \r
+ * @version V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * Released under both BSD license and Lesser GPL library license. \r
+ * Whenever there is any discrepancy between the two licenses, \r
+ * the BSD license will take precedence. \r
+ *\r
+ * Code to export recordsets in several formats:\r
+ *\r
+ * AS VARIABLE\r
+ * $s = rs2csv($rs); # comma-separated values\r
+ * $s = rs2tab($rs); # tab delimited\r
+ * \r
+ * TO A FILE\r
+ * $f = fopen($path,'w');\r
+ * rs2csvfile($rs,$f);\r
+ * fclose($f);\r
+ *\r
+ * TO STDOUT\r
+ * rs2csvout($rs);\r
+ */\r
\r
+// returns a recordset as a csv string\r
+function rs2csv(&$rs,$addtitles=true)\r
+{\r
+       return _adodb_export($rs,',',',',false,$addtitles);\r
+}\r
+\r
+// writes recordset to csv file \r
+function rs2csvfile(&$rs,$fp,$addtitles=true)\r
+{\r
+       _adodb_export($rs,',',',',$fp,$addtitles);\r
+}\r
+\r
+// write recordset as csv string to stdout\r
+function rs2csvout(&$rs,$addtitles=true)\r
+{\r
+       $fp = fopen('php://stdout','wb');\r
+       _adodb_export($rs,',',',',true,$addtitles);\r
+       fclose($fp);\r
+}\r
+\r
+function rs2tab(&$rs,$addtitles=true)\r
+{\r
+       return _adodb_export($rs,"\t",',',false,$addtitles);\r
+}\r
+\r
+// to file pointer\r
+function rs2tabfile(&$rs,$fp,$addtitles=true)\r
+{\r
+       _adodb_export($rs,"\t",',',$fp,$addtitles);\r
+}\r
+\r
+// to stdout\r
+function rs2tabout(&$rs,$addtitles=true)\r
+{\r
+       $fp = fopen('php://stdout','wb');\r
+       _adodb_export($rs,"\t",' ',true,$addtitles);\r
+       if ($fp) fclose($fp);\r
+}\r
+\r
+function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')\r
+{\r
+       if (!$rs) return '';\r
+       //----------\r
+       // CONSTANTS\r
+       $NEWLINE = "\r\n";\r
+       $BUFLINES = 100;\r
+       $escquotequote = $escquote.$quote;\r
+       $s = '';\r
+       \r
+       if ($addtitles) {\r
+               $fieldTypes = $rs->FieldTypesArray();\r
+               reset($fieldTypes);\r
+               while(list(,$o) = each($fieldTypes)) {\r
+                       \r
+                       $v = $o->name;\r
+                       if ($escquote) $v = str_replace($quote,$escquotequote,$v);\r
+                       $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
+                       $elements[] = $v;\r
+                       \r
+               }\r
+               $s .= implode($sep, $elements).$NEWLINE;\r
+       }\r
+       $hasNumIndex = isset($rs->fields[0]);\r
+       \r
+       $line = 0;\r
+       $max = $rs->FieldCount();\r
+       \r
+       while (!$rs->EOF) {\r
+               $elements = array();\r
+               $i = 0;\r
+               \r
+               if ($hasNumIndex) {\r
+                       for ($j=0; $j < $max; $j++) {\r
+                               $v = trim($rs->fields[$j]);\r
+                               if ($escquote) $v = str_replace($quote,$escquotequote,$v);\r
+                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
+                               \r
+                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";\r
+                               else $elements[] = $v;\r
+                       }\r
+               } else { // ASSOCIATIVE ARRAY\r
+                       foreach($rs->fields as $v) {\r
+                               if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));\r
+                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
+                               \r
+                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";\r
+                               else $elements[] = $v;\r
+                       }\r
+               }\r
+               $s .= implode($sep, $elements).$NEWLINE;\r
+               $rs->MoveNext();\r
+               $line += 1;\r
+               if ($fp && ($line % $BUFLINES) == 0) {\r
+                       if ($fp === true) echo $s;\r
+                       else fwrite($fp,$s);\r
+                       $s = '';\r
+               }\r
+       }\r
+       \r
+       if ($fp) {\r
+               if ($fp === true) echo $s;\r
+               else fwrite($fp,$s);\r
+               $s = '';\r
+       }\r
+       \r
+       return $s;\r
+}\r
 ?>
\ No newline at end of file
index dac81ddb756b874cf8777bd4673c959ea2e60c01..f70018ae28ab60809cd7fe15f5f993432a926997 100644 (file)
@@ -1,6 +1,6 @@
 <?php \r
 /*\r
-  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  V4.50 6 July 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
   Released under both BSD license and Lesser GPL library license. \r
   Whenever there is any discrepancy between the two licenses, \r
   the BSD license will take precedence.\r
@@ -76,17 +76,39 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows;
                        \r
                        $type = $typearr[$i];\r
                        switch($type) {\r
+                       case 'D':\r
+                               if (!strpos($v,':')) {\r
+                                       $s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";\r
+                                       break;\r
+                               }\r
                        case 'T':\r
                                $s .= " <TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";\r
                        break;\r
-                       case 'D':\r
-                               $s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";\r
-                       break;\r
                        case 'I':\r
                        case 'N':\r
                                $s .= " <TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";\r
                                \r
                        break;\r
+                       /*\r
+                       case 'B':\r
+                               if (substr($v,8,2)=="BM" ) $v = substr($v,8);\r
+                               $mtime = substr(str_replace(' ','_',microtime()),2);\r
+                               $tmpname = "tmp/".uniqid($mtime).getmypid();\r
+                               $fd = @fopen($tmpname,'a');\r
+                               @ftruncate($fd,0);\r
+                               @fwrite($fd,$v);\r
+                               @fclose($fd);\r
+                               if (!function_exists ("mime_content_type")) {\r
+                                 function mime_content_type ($file) {\r
+                                   return exec("file -bi ".escapeshellarg($file));\r
+                                 }\r
+                               }\r
+                               $t = mime_content_type($tmpname);\r
+                               $s .= (substr($t,0,5)=="image") ? " <td><img src='$tmpname' alt='$t'></td>\\n" : " <td><a\r
+                               href='$tmpname'>$t</a></td>\\n";\r
+                               break;\r
+                       */\r
+\r
                        default:\r
                                if ($htmlspecialchars) $v = htmlspecialchars(trim($v));\r
                                $v = trim($v);\r
@@ -156,4 +178,4 @@ function arr2html(&$arr,$ztabhtml='',$zheaderarray='')
        print $s;\r
 }\r
 \r
-\r
+?>\r