From 4e5cb1786ee59b26e36cd84365040201e8209d27 Mon Sep 17 00:00:00 2001 From: Ralf Becker Date: Mon, 26 Sep 2005 10:12:10 +0000 Subject: [PATCH] imported adodb 4.65 --- phpgwapi/inc/adodb/adodb-csvlib.inc.php | 56 +- phpgwapi/inc/adodb/adodb-datadict.inc.php | 88 +- phpgwapi/inc/adodb/adodb-error.inc.php | 5 +- phpgwapi/inc/adodb/adodb-errorhandler.inc.php | 4 +- phpgwapi/inc/adodb/adodb-errorpear.inc.php | 4 +- phpgwapi/inc/adodb/adodb-exceptions.inc.php | 5 +- phpgwapi/inc/adodb/adodb-iterator.inc.php | 3 +- phpgwapi/inc/adodb/adodb-lib.inc.php | 285 +- phpgwapi/inc/adodb/adodb-pager.inc.php | 16 +- phpgwapi/inc/adodb/adodb-pear.inc.php | 19 +- phpgwapi/inc/adodb/adodb-perf.inc.php | 250 +- phpgwapi/inc/adodb/adodb-php4.inc.php | 2 +- phpgwapi/inc/adodb/adodb-time.inc.php | 468 +- phpgwapi/inc/adodb/adodb-time.zip | Bin 8953 -> 12576 bytes phpgwapi/inc/adodb/adodb-xmlschema.inc.php | 11 +- phpgwapi/inc/adodb/adodb.inc.php | 524 ++- .../adodb/datadict/datadict-access.inc.php | 2 +- .../inc/adodb/datadict/datadict-db2.inc.php | 81 +- .../adodb/datadict/datadict-firebird.inc.php | 8 +- .../adodb/datadict/datadict-generic.inc.php | 2 +- .../inc/adodb/datadict/datadict-ibase.inc.php | 2 +- .../adodb/datadict/datadict-informix.inc.php | 2 +- .../inc/adodb/datadict/datadict-mssql.inc.php | 34 +- .../inc/adodb/datadict/datadict-mysql.inc.php | 8 +- .../inc/adodb/datadict/datadict-oci8.inc.php | 17 +- .../adodb/datadict/datadict-postgres.inc.php | 25 +- .../inc/adodb/datadict/datadict-sapdb.inc.php | 8 +- .../adodb/datadict/datadict-sybase.inc.php | 10 +- phpgwapi/inc/adodb/docs/docs-adodb.htm | 3991 ++++++++--------- phpgwapi/inc/adodb/docs/docs-datadict.htm | 32 +- phpgwapi/inc/adodb/docs/docs-oracle.htm | 542 +++ phpgwapi/inc/adodb/docs/docs-perf.htm | 12 +- phpgwapi/inc/adodb/docs/docs-session.htm | 114 +- phpgwapi/inc/adodb/docs/old-changelog.htm | 124 +- .../inc/adodb/drivers/adodb-access.inc.php | 2 +- phpgwapi/inc/adodb/drivers/adodb-ado.inc.php | 32 +- phpgwapi/inc/adodb/drivers/adodb-ado5.inc.php | 636 +++ .../adodb/drivers/adodb-ado_access.inc.php | 9 +- .../inc/adodb/drivers/adodb-ado_mssql.inc.php | 62 +- .../adodb/drivers/adodb-borland_ibase.inc.php | 2 +- phpgwapi/inc/adodb/drivers/adodb-csv.inc.php | 2 +- phpgwapi/inc/adodb/drivers/adodb-db2.inc.php | 57 +- .../inc/adodb/drivers/adodb-fbsql.inc.php | 7 +- .../inc/adodb/drivers/adodb-firebird.inc.php | 2 +- .../inc/adodb/drivers/adodb-ibase.inc.php | 121 +- .../inc/adodb/drivers/adodb-informix.inc.php | 3 +- .../adodb/drivers/adodb-informix72.inc.php | 93 +- phpgwapi/inc/adodb/drivers/adodb-ldap.inc.php | 157 +- .../inc/adodb/drivers/adodb-mssql.inc.php | 125 +- .../inc/adodb/drivers/adodb-mssqlpo.inc.php | 2 +- .../inc/adodb/drivers/adodb-mysql.inc.php | 206 +- .../inc/adodb/drivers/adodb-mysqli.inc.php | 570 ++- .../inc/adodb/drivers/adodb-mysqlt.inc.php | 27 +- .../inc/adodb/drivers/adodb-netezza.inc.php | 8 +- phpgwapi/inc/adodb/drivers/adodb-oci8.inc.php | 283 +- .../inc/adodb/drivers/adodb-oci805.inc.php | 2 +- .../inc/adodb/drivers/adodb-oci8po.inc.php | 18 +- phpgwapi/inc/adodb/drivers/adodb-odbc.inc.php | 134 +- .../adodb/drivers/adodb-odbc_mssql.inc.php | 10 +- .../adodb/drivers/adodb-odbc_oracle.inc.php | 61 +- .../inc/adodb/drivers/adodb-odbtp.inc.php | 206 +- .../adodb/drivers/adodb-odbtp_unicode.inc.php | 29 +- .../inc/adodb/drivers/adodb-oracle.inc.php | 4 +- phpgwapi/inc/adodb/drivers/adodb-pdo.inc.php | 314 +- .../inc/adodb/drivers/adodb-pdo_mysql.inc.php | 145 + .../inc/adodb/drivers/adodb-pdo_oci.inc.php | 92 + .../inc/adodb/drivers/adodb-pdo_pgsql.inc.php | 228 + .../inc/adodb/drivers/adodb-postgres.inc.php | 2 +- .../adodb/drivers/adodb-postgres64.inc.php | 130 +- .../inc/adodb/drivers/adodb-postgres7.inc.php | 37 +- .../inc/adodb/drivers/adodb-postgres8.inc.php | 12 + .../inc/adodb/drivers/adodb-proxy.inc.php | 2 +- .../inc/adodb/drivers/adodb-sapdb.inc.php | 6 +- .../adodb/drivers/adodb-sqlanywhere.inc.php | 2 +- .../inc/adodb/drivers/adodb-sqlite.inc.php | 57 +- .../inc/adodb/drivers/adodb-sqlitepo.inc.php | 2 +- .../inc/adodb/drivers/adodb-sybase.inc.php | 25 +- .../adodb/drivers/adodb-sybase_ase.inc.php | 115 + phpgwapi/inc/adodb/drivers/adodb-vfp.inc.php | 7 +- phpgwapi/inc/adodb/lang/adodb-ar.inc.php | 34 + phpgwapi/inc/adodb/lang/adodb-da.inc.php | 33 + phpgwapi/inc/adodb/lang/adodb-es.inc.php | 3 +- .../inc/adodb/lang/adodb-esperanto.inc.php | 35 + phpgwapi/inc/adodb/lang/adodb-hu.inc.php | 34 + phpgwapi/inc/adodb/lang/adodb-uk1251.inc.php | 35 + .../inc/adodb/pear/Auth/Container/ADOdb.php | 29 +- phpgwapi/inc/adodb/perf/perf-db2.inc.php | 2 +- phpgwapi/inc/adodb/perf/perf-informix.inc.php | 2 +- phpgwapi/inc/adodb/perf/perf-mssql.inc.php | 2 +- phpgwapi/inc/adodb/perf/perf-mysql.inc.php | 70 +- phpgwapi/inc/adodb/perf/perf-oci8.inc.php | 64 +- phpgwapi/inc/adodb/perf/perf-postgres.inc.php | 11 +- phpgwapi/inc/adodb/pivottable.inc.php | 35 +- phpgwapi/inc/adodb/rsfilter.inc.php | 11 +- phpgwapi/inc/adodb/server.php | 18 +- .../adodb/session/adodb-compress-bzip2.php | 2 +- .../inc/adodb/session/adodb-compress-gzip.php | 2 +- .../inc/adodb/session/adodb-cryptsession.php | 2 +- .../adodb/session/adodb-encrypt-mcrypt.php | 2 +- .../inc/adodb/session/adodb-encrypt-md5.php | 2 +- .../adodb/session/adodb-encrypt-secret.php | 2 +- .../inc/adodb/session/adodb-session-clob.php | 2 +- phpgwapi/inc/adodb/session/adodb-session.php | 140 +- .../session/adodb-sessions.oracle.clob.sql | 15 + .../adodb/session/adodb-sessions.oracle.sql | 16 + .../adodb/session/old/adodb-cryptsession.php | 23 +- .../adodb/session/old/adodb-session-clob.php | 40 +- .../inc/adodb/session/old/adodb-session.php | 72 +- phpgwapi/inc/adodb/session/session_schema.xml | 26 + phpgwapi/inc/adodb/tests/benchmark.php | 2 +- phpgwapi/inc/adodb/tests/pdo.php | 108 +- phpgwapi/inc/adodb/tests/test-datadict.php | 35 +- phpgwapi/inc/adodb/tests/test-php5.php | 24 +- phpgwapi/inc/adodb/tests/test-xmlschema.php | 17 +- phpgwapi/inc/adodb/tests/test.php | 296 +- phpgwapi/inc/adodb/tests/test2.php | 59 +- phpgwapi/inc/adodb/tests/test3.php | 2 +- phpgwapi/inc/adodb/tests/test4.php | 51 +- phpgwapi/inc/adodb/tests/test5.php | 2 +- phpgwapi/inc/adodb/tests/testcache.php | 2 +- .../inc/adodb/tests/testdatabases.inc.php | 170 +- phpgwapi/inc/adodb/tests/testmssql.php | 4 +- phpgwapi/inc/adodb/tests/testoci8.php | 2 +- phpgwapi/inc/adodb/tests/testoci8cursor.php | 2 +- phpgwapi/inc/adodb/tests/testpaging.php | 11 +- phpgwapi/inc/adodb/tests/testpear.php | 2 +- phpgwapi/inc/adodb/tests/testsessions.php | 34 +- phpgwapi/inc/adodb/tests/xmlschema-mssql.xml | 34 + phpgwapi/inc/adodb/tests/xmlschema.xml | 3 + phpgwapi/inc/adodb/toexport.inc.php | 12 +- phpgwapi/inc/adodb/tohtml.inc.php | 42 +- 131 files changed, 8364 insertions(+), 4114 deletions(-) create mode 100644 phpgwapi/inc/adodb/docs/docs-oracle.htm create mode 100644 phpgwapi/inc/adodb/drivers/adodb-ado5.inc.php create mode 100644 phpgwapi/inc/adodb/drivers/adodb-pdo_mysql.inc.php create mode 100644 phpgwapi/inc/adodb/drivers/adodb-pdo_oci.inc.php create mode 100644 phpgwapi/inc/adodb/drivers/adodb-pdo_pgsql.inc.php create mode 100644 phpgwapi/inc/adodb/drivers/adodb-postgres8.inc.php create mode 100644 phpgwapi/inc/adodb/drivers/adodb-sybase_ase.inc.php create mode 100644 phpgwapi/inc/adodb/lang/adodb-ar.inc.php create mode 100644 phpgwapi/inc/adodb/lang/adodb-da.inc.php create mode 100644 phpgwapi/inc/adodb/lang/adodb-esperanto.inc.php create mode 100644 phpgwapi/inc/adodb/lang/adodb-hu.inc.php create mode 100644 phpgwapi/inc/adodb/lang/adodb-uk1251.inc.php create mode 100644 phpgwapi/inc/adodb/session/adodb-sessions.oracle.clob.sql create mode 100644 phpgwapi/inc/adodb/session/adodb-sessions.oracle.sql create mode 100644 phpgwapi/inc/adodb/session/session_schema.xml create mode 100644 phpgwapi/inc/adodb/tests/xmlschema-mssql.xml diff --git a/phpgwapi/inc/adodb/adodb-csvlib.inc.php b/phpgwapi/inc/adodb/adodb-csvlib.inc.php index 92a6f737af..801e057107 100644 --- a/phpgwapi/inc/adodb/adodb-csvlib.inc.php +++ b/phpgwapi/inc/adodb/adodb-csvlib.inc.php @@ -7,7 +7,8 @@ global $ADODB_INCLUDED_CSV; $ADODB_INCLUDED_CSV = 1; /* - V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved. + + V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. See License.txt. @@ -66,10 +67,15 @@ $ADODB_INCLUDED_CSV = 1; $o =& $rs->FetchField($i); $flds[] = $o; } - - $rs =& new ADORecordSet_array(); - $rs->InitArrayFields($rows,$flds); - return $line.serialize($rs); + + $savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; + $class = $rs->connection->arrayClass; + $rs2 = new $class(); + $rs2->sql = $rs->sql; + $rs2->oldProvider = $rs->dataProvider; + $rs2->InitArrayFields($rows,$flds); + $rs2->fetchMode = $savefetch; + return $line.serialize($rs2); } @@ -84,15 +90,16 @@ $ADODB_INCLUDED_CSV = 1; * error occurred in sql INSERT/UPDATE/DELETE, * empty recordset is returned */ - function &csv2rs($url,&$err,$timeout=0) + function &csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array') { + $false = false; $err = false; $fp = @fopen($url,'rb'); if (!$fp) { $err = $url.' file/URL not found'; - return false; + return $false; } - flock($fp, LOCK_SH); + @flock($fp, LOCK_SH); $arr = array(); $ttl = 0; @@ -101,7 +108,7 @@ $ADODB_INCLUDED_CSV = 1; if (strncmp($meta[0],'****',4) === 0) { $err = trim(substr($meta[0],4,1024)); fclose($fp); - return false; + return $false; } // check for meta data // $meta[0] is -1 means return an empty recordset @@ -113,19 +120,20 @@ $ADODB_INCLUDED_CSV = 1; if (sizeof($meta) < 5) { $err = "Corrupt first line for format -1"; fclose($fp); - return false; + return $false; } fclose($fp); if ($timeout > 0) { $err = " Illegal Timeout $timeout "; - return false; + return $false; } + + $rs = new $rsclass($val=true); $rs->fields = array(); $rs->timeCreated = $meta[1]; - $rs =& new ADORecordSet($val=true); $rs->EOF = true; - $rs->_numOfFields=0; + $rs->_numOfFields = 0; $rs->sql = urldecode($meta[2]); $rs->affectedrows = (integer)$meta[3]; $rs->insertid = $meta[4]; @@ -149,27 +157,27 @@ $ADODB_INCLUDED_CSV = 1; if ((rand() & 31) == 0) { fclose($fp); $err = "Timeout 3"; - return false; + return $false; } break; case 2: if ((rand() & 15) == 0) { fclose($fp); $err = "Timeout 2"; - return false; + return $false; } break; case 1: if ((rand() & 3) == 0) { fclose($fp); $err = "Timeout 1"; - return false; + return $false; } break; default: fclose($fp); $err = "Timeout 0"; - return false; + return $false; } // switch } // if check flush cache @@ -203,7 +211,7 @@ $ADODB_INCLUDED_CSV = 1; if (!$meta) { fclose($fp); $err = "Unexpected EOF 1"; - return false; + return $false; } } @@ -216,7 +224,7 @@ $ADODB_INCLUDED_CSV = 1; $flds = false; break; } - $fld =& new ADOFieldObject(); + $fld = new ADOFieldObject(); $fld->name = urldecode($o2[0]); $fld->type = $o2[1]; $fld->max_length = $o2[2]; @@ -225,7 +233,7 @@ $ADODB_INCLUDED_CSV = 1; } else { fclose($fp); $err = "Recordset had unexpected EOF 2"; - return false; + return $false; } // slurp in the data @@ -242,9 +250,9 @@ $ADODB_INCLUDED_CSV = 1; if (!is_array($arr)) { $err = "Recordset had unexpected EOF (in serialized recordset)"; if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!"; - return false; + return $false; } - $rs =& new ADORecordSet_array(); + $rs = new $rsclass(); $rs->timeCreated = $ttl; $rs->InitArrayFields($arr,$flds); return $rs; @@ -272,7 +280,7 @@ $ADODB_INCLUDED_CSV = 1; $mtime = substr(str_replace(' ','_',microtime()),2); // getmypid() actually returns 0 on Win98 - never mind! $tmpname = $filename.uniqid($mtime).getmypid(); - if (!($fd = fopen($tmpname,'a'))) return false; + if (!($fd = @fopen($tmpname,'a'))) return false; $ok = ftruncate($fd,0); if (!fwrite($fd,$contents)) $ok = false; fclose($fd); @@ -288,7 +296,7 @@ $ADODB_INCLUDED_CSV = 1; } return $ok; } - if (!($fd = fopen($filename, 'a'))) return false; + if (!($fd = @fopen($filename, 'a'))) return false; if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { $ok = fwrite( $fd, $contents ); fclose($fd); diff --git a/phpgwapi/inc/adodb/adodb-datadict.inc.php b/phpgwapi/inc/adodb/adodb-datadict.inc.php index 8d7edc921b..ec309f197b 100644 --- a/phpgwapi/inc/adodb/adodb-datadict.inc.php +++ b/phpgwapi/inc/adodb/adodb-datadict.inc.php @@ -1,7 +1,7 @@ $str

"; $a= Lens_ParseArgs($str); print "
";
@@ -30,6 +30,7 @@ print_r($a);
 print "
"; } + if (!function_exists('ctype_alnum')) { function ctype_alnum($text) { return preg_match('/^[a-z0-9]*$/i', $text); @@ -153,6 +154,7 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-') } $pos += 1; } + if ($intoken) $tokens[$stmtno][] = implode('',$tokarr); return $tokens; } @@ -169,10 +171,12 @@ class ADODB_DataDict { var $dropCol = ' DROP COLUMN'; var $renameColumn = 'ALTER TABLE %s RENAME COLUMN %s TO %s'; // table, old-column, new-column, column-definitions (not used by default) var $nameRegex = '\w'; + var $nameRegexBrackets = 'a-zA-Z0-9_\(\)'; var $schema = false; var $serverInfo = array(); var $autoIncrement = false; var $dataProvider; + var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob /// in other words, we use a text area for editting. @@ -186,23 +190,27 @@ class ADODB_DataDict { return false; } - function &MetaTables() + function MetaTables() { + if (!$this->connection->IsConnected()) return array(); return $this->connection->MetaTables(); } - function &MetaColumns($tab, $upper=true, $schema=false) + function MetaColumns($tab, $upper=true, $schema=false) { + if (!$this->connection->IsConnected()) return array(); return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema); } - function &MetaPrimaryKeys($tab,$owner=false,$intkey=false) + function MetaPrimaryKeys($tab,$owner=false,$intkey=false) { + if (!$this->connection->IsConnected()) return array(); return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey); } - function &MetaIndexes($table, $primary = false, $owner = false) + function MetaIndexes($table, $primary = false, $owner = false) { + if (!$this->connection->IsConnected()) return array(); return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner); } @@ -211,7 +219,7 @@ class ADODB_DataDict { return ADORecordSet::MetaType($t,$len,$fieldobj); } - function NameQuote($name = NULL) + function NameQuote($name = NULL,$allowBrackets=false) { if (!is_string($name)) { return FALSE; @@ -231,7 +239,9 @@ class ADODB_DataDict { } // if name contains special characters, quote it - if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) { + $regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex; + + if ( !preg_match('/^[' . $regex . ']+$/', $name) ) { return $quote . $name . $quote; } @@ -312,7 +322,8 @@ class ADODB_DataDict { } foreach($flds as $key => $fld) { - $flds[$key] = $this->NameQuote($fld); + # some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32) + $flds[$key] = $this->NameQuote($fld,$allowBrackets=true); } return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions)); @@ -424,7 +435,7 @@ class ADODB_DataDict { { if (!$tableoptions) $tableoptions = array(); - list($lines,$pkey) = $this->_GenFields($flds); + list($lines,$pkey) = $this->_GenFields($flds, true); $taboptions = $this->_Options($tableoptions); $tabname = $this->TableName ($tabname); @@ -436,7 +447,7 @@ class ADODB_DataDict { return $sql; } - function _GenFields($flds) + function _GenFields($flds,$widespacing=false) { if (is_string($flds)) { $padding = ' '; @@ -558,7 +569,7 @@ class ADODB_DataDict { } else { $fdefault = $this->connection->sysDate; } - } else if (strlen($fdefault) && !$fnoquote) + } else if ($fdefault !== false && !$fnoquote) if ($ty == 'C' or $ty == 'X' or ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') @@ -567,7 +578,7 @@ class ADODB_DataDict { $fdefault = $this->connection->qstr($fdefault); $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned); - $fname = str_pad($fname,16); + if ($widespacing) $fname = str_pad($fname,24); $lines[$fid] = $fname.' '.$ftype.$suffix; if ($fautoinc) $this->autoIncrement = true; @@ -692,26 +703,69 @@ class ADODB_DataDict { } /* - "Florian Buzin [ easywe ]" + "Florian Buzin [ easywe ]" This function changes/adds new fields to your table. You don't have to know if the col is new or not. It will check on its own. */ function ChangeTableSQL($tablename, $flds, $tableoptions = false) { + global $ADODB_FETCH_MODE; + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false); + // check table exists - $cols = &$this->MetaColumns($tablename); + $save_handler = $this->connection->raiseErrorFn; + $this->connection->raiseErrorFn = ''; + $cols = $this->MetaColumns($tablename); + $this->connection->raiseErrorFn = $save_handler; + + if (isset($savem)) $this->connection->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ( empty($cols)) { return $this->CreateTableSQL($tablename, $flds, $tableoptions); } + if (is_array($flds)) { + // Cycle through the update fields, comparing + // existing fields to fields to update. + // if the Metatype and size is exactly the + // same, ignore - by Mark Newham + $holdflds = array(); + foreach($flds as $k=>$v) { + if ( isset($cols[$k]) && is_object($cols[$k]) ) { + $c = $cols[$k]; + $ml = $c->max_length; + $mt = &$this->MetaType($c->type,$ml); + if ($ml == -1) $ml = ''; + if ($mt == 'X') $ml = $v['SIZE']; + if (($mt != $v['TYPE']) || $ml != $v['SIZE']) { + $holdflds[$k] = $v; + } + } else { + $holdflds[$k] = $v; + } + } + $flds = $holdflds; + } + + // already exists, alter table instead list($lines,$pkey) = $this->_GenFields($flds); $alter = 'ALTER TABLE ' . $this->TableName($tablename); $sql = array(); - + foreach ( $lines as $id => $v ) { if ( isset($cols[$id]) && is_object($cols[$id]) ) { + + $flds = Lens_ParseArgs($v,','); + + // We are trying to change the size of the field, if not allowed, simply ignore the request. + if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)) continue; + $sql[] = $alter . $this->alterCol . ' ' . $v; } else { $sql[] = $alter . $this->addCol . ' ' . $v; @@ -721,4 +775,4 @@ class ADODB_DataDict { return $sql; } } // class -?> +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/adodb-error.inc.php b/phpgwapi/inc/adodb/adodb-error.inc.php index 1a651b0595..b9bd8a55b6 100644 --- a/phpgwapi/inc/adodb/adodb-error.inc.php +++ b/phpgwapi/inc/adodb/adodb-error.inc.php @@ -1,6 +1,6 @@ DB_ERROR_VALUE_COUNT_ON_ROW, 1146 => DB_ERROR_NOSUCHTABLE, 1048 => DB_ERROR_CONSTRAINT, - 2002 => DB_ERROR_CONNECT_FAILED + 2002 => DB_ERROR_CONNECT_FAILED, + 2005 => DB_ERROR_CONNECT_FAILED ); return $MAP; diff --git a/phpgwapi/inc/adodb/adodb-errorhandler.inc.php b/phpgwapi/inc/adodb/adodb-errorhandler.inc.php index 1652bbcd47..d46c1f12d6 100644 --- a/phpgwapi/inc/adodb/adodb-errorhandler.inc.php +++ b/phpgwapi/inc/adodb/adodb-errorhandler.inc.php @@ -1,6 +1,6 @@ $value) $new_array[strtoupper($key)] = $value; @@ -80,7 +81,6 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_ $cnt = $zthis->GetOne("select count(*) from $table where $where"); if ($cnt > 0) return 1; // record already exists } else { - if (($zthis->Affected_Rows()>0)) return 1; } } else @@ -114,12 +114,12 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f if ($multiple or is_array($defstr)) { if ($size==0) $size=5; - $attr = " multiple size=$size"; + $attr = ' multiple size="'.$size.'"'; if (!strpos($name,'[]')) $name .= '[]'; - } else if ($size) $attr = " size=$size"; + } else if ($size) $attr = ' size="'.$size.'"'; else $attr =''; - - $s = "'; if ($blank1stItem) if (is_string($blank1stItem)) { $barr = explode(':',$blank1stItem); @@ -131,9 +131,18 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f else $compareFields0 = true; $value = ''; + $optgroup = null; + $firstgroup = true; + $fieldsize = $zthis->FieldCount(); while(!$zthis->EOF) { $zval = rtrim(reset($zthis->fields)); - if (sizeof($zthis->fields) > 1) { + + if ($blank1stItem && $zval=="") { + $zthis->MoveNext(); + continue; + } + + if ($fieldsize > 1) { if (isset($zthis->fields[1])) $zval2 = rtrim($zthis->fields[1]); else @@ -141,67 +150,176 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f } $selected = ($compareFields0) ? $zval : $zval2; - if ($blank1stItem && $zval=="") { - $zthis->MoveNext(); - continue; + $group = ''; + if ($fieldsize > 2) { + $group = rtrim($zthis->fields[2]); + } + + if ($optgroup != $group) { + $optgroup = $group; + if ($firstgroup) { + $firstgroup = false; + $s .="\n"; + } else { + $s .="\n"; + $s .="\n"; + } } + if ($hasvalue) $value = " value='".htmlspecialchars($zval2)."'"; if (is_array($defstr)) { if (in_array($selected,$defstr)) - $s .= "'; + $s .= "\n'; else $s .= "\n'.htmlspecialchars($zval).''; } else { if (strcasecmp($selected,$defstr)==0) - $s .= "'; + $s .= "\n'; else $s .= "\n'.htmlspecialchars($zval).''; } $zthis->MoveNext(); } // while + // closing last optgroup + if($optgroup != null) { + $s .= "\n"; + } return $s ."\n\n"; } +// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM +function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) +{ + $hasvalue = false; + + if ($multiple or is_array($defstr)) { + if ($size==0) $size=5; + $attr = ' multiple size="'.$size.'"'; + if (!strpos($name,'[]')) $name .= '[]'; + } else if ($size) $attr = ' size="'.$size.'"'; + else $attr =''; + + $s = '\n"; +} + + /* Count the number of records this sql statement will return by using query rewriting techniques... - Does not work with UNIONs. + Does not work with UNIONs, except with postgresql and oracle. */ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) { $qryRecs = 0; - if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) { + if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || + preg_match('/\s+GROUP\s+BY\s+/is',$sql) || + preg_match('/\s+UNION\s+/is',$sql)) { // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias // but this is only supported by oracle and postgresql... if ($zthis->dataProvider == 'oci8') { $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); - $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; - } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') { + // Allow Oracle hints to be used for query optimization, Chris Wrye + if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) { + $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; + } else + $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; + + } else if (strncmp($zthis->databaseType,'postgres',8) == 0) { $info = $zthis->ServerInfo(); if (substr($info['version'],0,3) >= 7.1) { // good till version 999 - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql); $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_"; } } - } else { + } else { // now replace SELECT ... FROM with SELECT COUNT(*) FROM - $rewritesql = preg_replace( '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql); - + // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails // with mssql, access and postgresql. Also a good speedup optimization - skips sorting! - $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql); } if (isset($rewritesql) && $rewritesql != $sql) { @@ -218,11 +336,14 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) //-------------------------------------------- // query rewrite failed - so try slower way... + // strip off unneeded ORDER BY if no UNION if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql; else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); $rstest = &$zthis->Execute($rewritesql,$inputarr); + if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr); + if ($rstest) { $qryRecs = $rstest->RecordCount(); if ($qryRecs == -1) { @@ -249,7 +370,7 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) /* Code originally from "Cornel G" - This code will not work with SQL that has UNION in it + This code might not work with SQL that has UNION in it Also if you are using CachePageExecute(), there is a strong possibility that data will get out of synch. use CachePageExecute() only with tables that @@ -416,9 +537,9 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq // is_null requires php 4.0.4 //********************************************************// if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) || $arrFields[$upperfname] === 'null' - || $arrFields[$upperfname] === '' - || empty($arrFields[$upperfname])) + ) { switch ($force) { @@ -462,8 +583,11 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq // If there were any modified fields then build the rest of the update query. if ($fieldUpdatedCount > 0 || $forceUpdate) { // Get the table name from the existing query. - preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); - + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else { + preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); + $tableName = $tableName[1]; + } // Get the full where clause excluding the word "WHERE" from // the existing query. preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); @@ -472,18 +596,19 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq // not a good hack, improvements? if ($whereClause) { if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard)); - else preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard); + else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard)); + else preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard); } else $whereClause = array(false,false); if ($discard) $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); - $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2); - if (strlen($whereClause[1]) > 0) - $sql .= ' WHERE '.$whereClause[1]; + $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2); + if (strlen($whereClause[1]) > 0) + $sql .= ' WHERE '.$whereClause[1]; - return $sql; + return $sql; } else { return false; @@ -512,6 +637,10 @@ function adodb_key_exists($key, &$arr,$force=2) */ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) { +static $cacheRS = false; +static $cacheSig = 0; +static $cacheCols; + $tableName = ''; $values = ''; $fields = ''; @@ -528,13 +657,26 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) //because we have to call MetaType. //php can't do a $rsclass::MetaType() $rsclass = $zthis->rsPrefix.$zthis->databaseType; - $recordSet =& new $rsclass(-1,$zthis->fetchMode); + $recordSet = new $rsclass(-1,$zthis->fetchMode); $recordSet->connection = &$zthis; - - $columns = $zthis->MetaColumns( $tableName ); + + if (is_string($cacheRS) && $cacheRS == $rs) { + $columns =& $cacheCols; + } else { + $columns = $zthis->MetaColumns( $tableName ); + $cacheRS = $tableName; + $cacheCols = $columns; + } } else if (is_subclass_of($rs, 'adorecordset')) { - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) - $columns[] = $rs->FetchField($i); + if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) { + $columns =& $cacheCols; + } else { + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) + $columns[] = $rs->FetchField($i); + $cacheRS = $cacheSig; + $cacheCols = $columns; + $rs->insertSig = $cacheSig++; + } $recordSet =& $rs; } else { @@ -556,9 +698,9 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) /********************************************************/ if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) || $arrFields[$upperfname] === 'null' - || $arrFields[$upperfname] === '' - || empty($arrFields[$upperfname])) + ) { switch ($force) { @@ -613,7 +755,8 @@ function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) // Get the table name from the existing query. if (!$tableName) { - if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName)) + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName)) $tableName = $tableName[1]; else return false; @@ -724,58 +867,39 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, } } - - $sql = ''; switch($type) { case "C": case "X": case 'B': - if ($action == 'I') { - $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", "; - } else { - $sql .= $fnameq . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", "; - } - break; + $val = $zthis->qstr($arrFields[$fname],$magicq); + break; case "D": - if ($action == 'I') { - $sql = $zthis->DBDate($arrFields[$fname]) . ", "; - } else { - $sql .= $fnameq . "=" . $zthis->DBDate($arrFields[$fname]) . ", "; - } + $val = $zthis->DBDate($arrFields[$fname]); break; case "T": - if ($action == 'I') { - $sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", "; - } else { - $sql .= $fnameq . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", "; - } + $val = $zthis->DBTimeStamp($arrFields[$fname]); break; default: $val = $arrFields[$fname]; if (empty($val)) $val = '0'; - - - if ($action == 'I') { - $sql .= $val . ", "; - } else { - $sql .= $fnameq . "=" . $val . ", "; - } break; } - return $sql; + if ($action == 'I') return $val . ", "; + + + return $fnameq . "=" . $val . ", "; + } function _adodb_debug_execute(&$zthis, $sql, $inputarr) { -global $HTTP_SERVER_VARS; - $ss = ''; if ($inputarr) { foreach($inputarr as $kk=>$vv) { @@ -784,21 +908,26 @@ global $HTTP_SERVER_VARS; } $ss = "[ $ss ]"; } - $sqlTxt = str_replace(',',', ',is_array($sql) ? $sql[0] : $sql); - + $sqlTxt = is_array($sql) ? $sql[0] : $sql; + /*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql); + $sqlTxt = str_replace(',',', ',$sqlTxt); + $sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt); + */ // check if running from browser or command-line - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); + $dbt = $zthis->databaseType; + if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType; if ($inBrowser) { $ss = htmlspecialchars($ss); if ($zthis->debug === -1) - ADOConnection::outp( "
\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); + ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); else - ADOConnection::outp( "
\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); + ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); } else { - ADOConnection::outp("-----\n($zthis->databaseType): ".$sqlTxt."\n-----\n",false); + ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false); } - + $qID = $zthis->_query($sql,$inputarr); /* @@ -814,18 +943,19 @@ global $HTTP_SERVER_VARS; ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg()); } + if ($zthis->debug === 99) _adodb_backtrace(true,9999,2); return $qID; } -function _adodb_backtrace($printOrArr=true,$levels=9999) +function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0) { - if (PHPVERSION() < 4.3) return ''; + if ((float) PHPVERSION() < 4.3) return ''; $html = (isset($_SERVER['HTTP_USER_AGENT'])); $fmt = ($html) ? " %% line %4d, file: %s" : "%% line %4d, file: %s"; - $MAXSTRLEN = 64; + $MAXSTRLEN = 128; $s = ($html) ? '
' : '';
 	
@@ -836,6 +966,7 @@ function _adodb_backtrace($printOrArr=true,$levels=9999)
 	$tabs = sizeof($traceArr)-2;
 	
 	foreach ($traceArr as $arr) {
+		if ($skippy) {$skippy -= 1; continue;}
 		$levels -= 1;
 		if ($levels < 0) break;
 		
diff --git a/phpgwapi/inc/adodb/adodb-pager.inc.php b/phpgwapi/inc/adodb/adodb-pager.inc.php
index 0cca2344e2..705a4e7433 100644
--- a/phpgwapi/inc/adodb/adodb-pager.inc.php
+++ b/phpgwapi/inc/adodb/adodb-pager.inc.php
@@ -1,7 +1,7 @@
 sql = $sql;
 		$this->id = $id;
@@ -69,12 +69,12 @@ class ADODB_Pager {
 		
 		$next_page = $id.'_next_page';	
 		
-		if (isset($HTTP_GET_VARS[$next_page])) {
-			$HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
+		if (isset($_GET[$next_page])) {
+			$_SESSION[$curr_page] = $_GET[$next_page];
 		}
-		if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
+		if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page
 		
-		$this->curr_page = $HTTP_SESSION_VARS[$curr_page];
+		$this->curr_page = $_SESSION[$curr_page];
 		
 	}
 	
@@ -242,6 +242,8 @@ class ADODB_Pager {
 	
 		$this->rows = $rows;
 		
+		if ($this->db->dataProvider == 'informix') $this->db->cursorType = IFX_SCROLL;
+		
 		$savec = $ADODB_COUNTRECS;
 		if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
 		if ($this->cache)
diff --git a/phpgwapi/inc/adodb/adodb-pear.inc.php b/phpgwapi/inc/adodb/adodb-pear.inc.php
index 2db774c6c7..9a938b5c29 100644
--- a/phpgwapi/inc/adodb/adodb-pear.inc.php
+++ b/phpgwapi/inc/adodb/adodb-pear.inc.php
@@ -1,6 +1,6 @@
  $v) {
 				switch(strtolower($k)) {
+				case 'persist':
 				case 'persistent': 	$persist = $v; break;
 				#ibase
 				case 'dialect': 	$obj->dialect = $v; break;
@@ -204,9 +210,10 @@ class DB
 	 */
 	function isError($value)
 	{
-		return (is_object($value) &&
-				(get_class($value) == 'db_error' ||
-				 is_subclass_of($value, 'db_error')));
+		if (!is_object($value)) return false;
+		$class = get_class($value);
+		return $class == 'pear_error' || is_subclass_of($value, 'pear_error') || 
+				$class == 'db_error' || is_subclass_of($value, 'db_error');
 	}
 
 
@@ -221,9 +228,11 @@ class DB
 	 */
 	function isWarning($value)
 	{
+		return false;
+		/*
 		return is_object($value) &&
 			(get_class( $value ) == "db_warning" ||
-			 is_subclass_of($value, "db_warning"));
+			 is_subclass_of($value, "db_warning"));*/
 	}
 
 	/**
diff --git a/phpgwapi/inc/adodb/adodb-perf.inc.php b/phpgwapi/inc/adodb/adodb-perf.inc.php
index 5cf597d7e0..4895809c33 100644
--- a/phpgwapi/inc/adodb/adodb-perf.inc.php
+++ b/phpgwapi/inc/adodb/adodb-perf.inc.php
@@ -1,6 +1,6 @@
 =2) return (integer) $memarr[1];
+	
+	return 0;
+}
 
 // avoids localization problems where , is used instead of .
 function adodb_round($n,$prec)
@@ -37,7 +64,6 @@ function adodb_microtime()
 /* sql code timing */
 function& adodb_log_sql(&$conn,$sql,$inputarr)
 {
-global $HTTP_SERVER_VARS;
 	
     $perf_table = adodb_perf::table();
 	$conn->fnExecute = false;
@@ -73,20 +99,26 @@ global $HTTP_SERVER_VARS;
 			$conn->lastInsID = @$conn->Insert_ID();
 			$conn->debug = $dbg;
 		}
-		if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {
-			$tracer .= '
'.$HTTP_SERVER_VARS['HTTP_HOST']; - if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF']; + if (isset($_SERVER['HTTP_HOST'])) { + $tracer .= '
'.$_SERVER['HTTP_HOST']; + if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF']; } else - if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '
'.$HTTP_SERVER_VARS['PHP_SELF']; + if (isset($_SERVER['PHP_SELF'])) $tracer .= '
'.$_SERVER['PHP_SELF']; //$tracer .= (string) adodb_backtrace(false); - $tracer = substr($tracer,0,500); + $tracer = (string) substr($tracer,0,500); if (is_array($inputarr)) { if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr); else { - $params = ''; - $params = implode(', ',$inputarr); + // Quote string parameters so we can see them in the + // performance stats. This helps spot disabled indexes. + $xar_params = $inputarr; + foreach ($xar_params as $xar_param_key => $xar_param) { + if (gettype($xar_param) == 'string') + $xar_params[$xar_param_key] = '"' . $xar_param . '"'; + } + $params = implode(', ', $xar_params); if (strlen($params) >= 3000) $params = substr($params, 0, 3000); } } else { @@ -94,14 +126,16 @@ global $HTTP_SERVER_VARS; } if (is_array($sql)) $sql = $sql[0]; - $arr = array('b'=>trim(substr($sql,0,230)), + $arr = array('b'=>strlen($sql).'.'.crc32($sql), 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6)); //var_dump($arr); $saved = $conn->debug; $conn->debug = 0; + $d = $conn->sysTimeStamp; + if (empty($d)) $d = date("'Y-m-d H:i:s'"); if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') { - $isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)"; + $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)"; } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') { $timer = $arr['f']; if ($dbT == 'informix') $sql2 = substr($sql2,0,230); @@ -111,12 +145,13 @@ global $HTTP_SERVER_VARS; $params = $conn->qstr($arr['d']); $tracer = $conn->qstr($arr['e']); - $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)"; + $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)"; if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql); $arr = false; } else { - $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)"; + $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)"; } + $ok = $conn->Execute($isql,$arr); $conn->debug = $saved; @@ -138,7 +173,7 @@ global $HTTP_SERVER_VARS; timer decimal(16,6))"); } if (!$ok) { - ADOConnection::outp( "LOGSQL Insert Failed: $isql
$err2
"); + ADOConnection::outp( "

LOGSQL Insert Failed: $isql
$err2

"); $conn->_logsql = false; } } @@ -208,6 +243,12 @@ processes 69293 // Algorithm is taken from // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp if (strncmp(PHP_OS,'WIN',3)==0) { + if (PHP_VERSION == '5.0.0') return false; + if (PHP_VERSION == '5.0.1') return false; + if (PHP_VERSION == '5.0.2') return false; + if (PHP_VERSION == '5.0.3') return false; + if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737 + @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'"); if (!$c) return false; @@ -310,7 +351,12 @@ Committed_AS: 348732 kB $perf_table = adodb_perf::table(); $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; - + + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + $sqlq = $this->conn->qstr($sql); $arr = $this->conn->GetArray( "select count(*),tracer @@ -324,6 +370,9 @@ Committed_AS: 348732 kB $s .= sprintf("%4d",$k[0]).'   '.strip_tags($k[1]).'
'; } } + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_CACHE_MODE = $save; $this->conn->fnExecute = $saveE; return $s; } @@ -340,9 +389,8 @@ Committed_AS: 348732 kB function InvalidSQL($numsql = 10) { - global $HTTP_GET_VARS; - if (isset($HTTP_GET_VARS['sql'])) return; + if (isset($_GET['sql'])) return; $s = '

Invalid SQL

'; $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; @@ -363,22 +411,23 @@ Committed_AS: 348732 kB */ function _SuspiciousSQL($numsql = 10) { - global $ADODB_FETCH_MODE,$HTTP_GET_VARS; + global $ADODB_FETCH_MODE; $perf_table = adodb_perf::table(); $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; - if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) { - $partial = !empty($HTTP_GET_VARS['part']); - echo "".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n"; + if (isset($_GET['exps']) && isset($_GET['sql'])) { + $partial = !empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; } - if (isset($HTTP_GET_VARS['sql'])) return; + if (isset($_GET['sql'])) return; $sql1 = $this->sql1; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); //$this->conn->debug=1; $rs =& $this->conn->SelectLimit( "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer @@ -387,6 +436,7 @@ Committed_AS: 348732 kB and (tracer is null or tracer not like 'ERROR:%') group by sql1 order by 1 desc",$numsql); + if (isset($savem)) $this->conn->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; $this->conn->fnExecute = $saveE; @@ -440,35 +490,38 @@ Committed_AS: 348732 kB */ function _ExpensiveSQL($numsql = 10) { - global $HTTP_GET_VARS,$ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $perf_table = adodb_perf::table(); $saveE = $this->conn->fnExecute; $this->conn->fnExecute = false; - if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) { - $partial = !empty($HTTP_GET_VARS['part']); - echo "".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n"; + if (isset($_GET['expe']) && isset($_GET['sql'])) { + $partial = !empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; } - if (isset($HTTP_GET_VARS['sql'])) return; + if (isset($_GET['sql'])) return; $sql1 = $this->sql1; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + $rs =& $this->conn->SelectLimit( "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer from $perf_table where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT') and (tracer is null or tracer not like 'ERROR:%') group by sql1 + having count(*)>1 order by 1 desc",$numsql); - + if (isset($savem)) $this->conn->SetFetchMode($savem); $this->conn->fnExecute = $saveE; $ADODB_FETCH_MODE = $save; if (!$rs) return "

$this->helpurl. ".$this->conn->ErrorMsg()."

"; $s = "

Expensive SQL

-Tuning the following SQL will reduce the server load substantially
+Tuning the following SQL could reduce the server load substantially
\n"; $max = $this->maxLength; while (!$rs->EOF) { @@ -531,7 +584,11 @@ Committed_AS: 348732 kB $ret = false; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + $rs = $this->conn->Execute($sql1); + + if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; if ($rs) { while (!$rs->EOF) { @@ -577,7 +634,6 @@ Committed_AS: 348732 kB function UI($pollsecs=5) { - global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS; $perf_table = adodb_perf::table(); $conn = $this->conn; @@ -589,15 +645,15 @@ Committed_AS: 348732 kB if ($app) $app .= ', '; $savelog = $this->conn->LogSQL(false); $info = $conn->ServerInfo(); - if (isset($HTTP_GET_VARS['clearsql'])) { + if (isset($_GET['clearsql'])) { $this->conn->Execute("delete from $perf_table"); } $this->conn->LogSQL($savelog); // magic quotes - if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) { - $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']); + if (isset($_GET['sql']) && get_magic_quotes_gpc()) { + $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']); } if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10; @@ -606,13 +662,13 @@ Committed_AS: 348732 kB $app .= $info['description']; - if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do']; - else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do']; - else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql'; + if (isset($_GET['do'])) $do = $_GET['do']; + else if (isset($_POST['do'])) $do = $_POST['do']; + else if (isset($_GET['sql'])) $do = 'viewsql'; else $do = 'stats'; - if (isset($HTTP_GET_VARS['nsql'])) { - if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql']; + if (isset($_GET['nsql'])) { + if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql']; } echo "ADOdb Performance Monitor on $app"; if ($do == 'viewsql') $form = ""; @@ -620,7 +676,7 @@ Committed_AS: 348732 kB $allowsql = !defined('ADODB_PERF_NO_RUN_SQL'); - if (empty($HTTP_GET_VARS['hidem'])) + if (empty($_GET['hidem'])) echo "
LoadCountSQLMaxMin
# SQL:
ADOdb Performance Monitor for $app
Performance Stats   View SQL @@ -639,7 +695,7 @@ Committed_AS: 348732 kB break; case 'poll': echo ""; + src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\">"; break; case 'poll2': echo "
";
@@ -652,7 +708,7 @@ Committed_AS:   348732 kB
 			$this->DoSQLForm();
 			break;
 		case 'viewsql':
-			if (empty($HTTP_GET_VARS['hidem']))
+			if (empty($_GET['hidem']))
 				echo "  Clear SQL Log
"; echo($this->SuspiciousSQL($nsql)); echo($this->ExpensiveSQL($nsql)); @@ -679,6 +735,7 @@ Committed_AS: 348732 kB set_time_limit(0); sleep($secs); while (1) { + $arr =& $this->PollParameters(); $hits = sprintf('%2.2f',$arr[0]); @@ -699,6 +756,8 @@ Committed_AS: 348732 kB echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n"; flush(); + if (connection_aborted()) return; + sleep($secs); $arro = $arr; } @@ -809,24 +868,22 @@ Committed_AS: 348732 kB function DoSQLForm() { - global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS; - $HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS); - $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; - $sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : ''; + $PHP_SELF = $_SERVER['PHP_SELF']; + $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : ''; - if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows']; + if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows']; else $rows = 3; - if (isset($HTTP_VARS['SMALLER'])) { + if (isset($_REQUEST['SMALLER'])) { $rows /= 2; if ($rows < 3) $rows = 3; - $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows; + $_SESSION['phplens_sqlrows'] = $rows; } - if (isset($HTTP_VARS['BIGGER'])) { + if (isset($_REQUEST['BIGGER'])) { $rows *= 2; - $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows; + $_SESSION['phplens_sqlrows'] = $rows; } ?> @@ -846,7 +903,7 @@ Committed_AS: 348732 kB undomq(trim($sql)); if (substr($sql,strlen($sql)-1) === ';') { @@ -902,8 +959,95 @@ Committed_AS: 348732 kB } return $m; } + + + /************************************************************************/ + + /** + * Reorganise multiple table-indices/statistics/.. + * OptimizeMode could be given by last Parameter + * + * @example + *
+     *          optimizeTables( 'tableA');
+     *      
+ *
+     *          optimizeTables( 'tableA', 'tableB', 'tableC');
+     *      
+ *
+     *          optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
+     *      
+ * + * @param string table name of the table to optimize + * @param int mode optimization-mode + * ADODB_OPT_HIGH for full optimization + * ADODB_OPT_LOW for CPU-less optimization + * Default is LOW ADODB_OPT_LOW + * @author Markus Staab + * @return Returns true on success and false on error + */ + function OptimizeTables() + { + $args = func_get_args(); + $numArgs = func_num_args(); + + if ( $numArgs == 0) return false; + + $mode = ADODB_OPT_LOW; + $lastArg = $args[ $numArgs - 1]; + if ( !is_string($lastArg)) { + $mode = $lastArg; + unset( $args[ $numArgs - 1]); + } + + foreach( $args as $table) { + $this->optimizeTable( $table, $mode); + } + } + + /** + * Reorganise the table-indices/statistics/.. depending on the given mode. + * Default Implementation throws an error. + * + * @param string table name of the table to optimize + * @param int mode optimization-mode + * ADODB_OPT_HIGH for full optimization + * ADODB_OPT_LOW for CPU-less optimization + * Default is LOW ADODB_OPT_LOW + * @author Markus Staab + * @return Returns true on success and false on error + */ + function OptimizeTable( $table, $mode = ADODB_OPT_LOW) + { + ADOConnection::outp( sprintf( "

%s: '%s' not implemented for driver '%s'

", __CLASS__, __FUNCTION__, $this->conn->databaseType)); + return false; + } + + /** + * Reorganise current database. + * Default implementation loops over all MetaTables() and + * optimize each using optmizeTable() + * + * @author Markus Staab + * @return Returns true on success and false on error + */ + function optimizeDatabase() + { + $conn = $this->conn; + if ( !$conn) return false; + + $tables = $conn->MetaTables( 'TABLES'); + if ( !$tables ) return false; + + foreach( $tables as $table) { + if ( !$this->optimizeTable( $table)) { + return false; + } + } + + return true; + } + // end hack } - - ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/adodb-php4.inc.php b/phpgwapi/inc/adodb/adodb-php4.inc.php index d65070eb50..bc68171cb2 100644 --- a/phpgwapi/inc/adodb/adodb-php4.inc.php +++ b/phpgwapi/inc/adodb/adodb-php4.inc.php @@ -1,7 +1,7 @@ The parameters are identical, except that adodb_date() accepts a subset @@ -55,8 +57,8 @@ adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) COPYRIGHT -(c) 2003 John Lim and released under BSD-style license except for code by jackbbs, -which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year +(c) 2003-2005 John Lim and released under BSD-style license except for code by +jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year and originally found at http://www.php.net/manual/en/function.mktime.php ============================================================================= @@ -72,13 +74,14 @@ These should be posted to the ADOdb forums at FUNCTION DESCRIPTIONS -FUNCTION adodb_getdate($date=false) +** FUNCTION adodb_getdate($date=false) Returns an array containing date information, as getdate(), but supports -dates greater than 1901 to 2038. - - -FUNCTION adodb_date($fmt, $timestamp = false) +dates greater than 1901 to 2038. The local date/time format is derived from a +heuristic the first time adodb_getdate is called. + + +** FUNCTION adodb_date($fmt, $timestamp = false) Convert a timestamp to a formatted local date. If $timestamp is not defined, the current timestamp is used. Unlike the function date(), it supports dates @@ -87,72 +90,139 @@ outside the 1901 to 2038 range. The format fields that adodb_date supports:
-a - "am" or "pm" 
-A - "AM" or "PM" 
-d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
-D - day of the week, textual, 3 letters; e.g. "Fri" 
-F - month, textual, long; e.g. "January" 
-g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
-G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
-h - hour, 12-hour format; i.e. "01" to "12" 
-H - hour, 24-hour format; i.e. "00" to "23" 
-i - minutes; i.e. "00" to "59" 
-j - day of the month without leading zeros; i.e. "1" to "31" 
-l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
-L - boolean for whether it is a leap year; i.e. "0" or "1" 
-m - month; i.e. "01" to "12" 
-M - month, textual, 3 letters; e.g. "Jan" 
-n - month without leading zeros; i.e. "1" to "12" 
-O - Difference to Greenwich time in hours; e.g. "+0200" 
-Q - Quarter, as in 1, 2, 3, 4 
-r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
-s - seconds; i.e. "00" to "59" 
-S - English ordinal suffix for the day of the month, 2 characters; 
-   			i.e. "st", "nd", "rd" or "th" 
-t - number of days in the given month; i.e. "28" to "31"
-T - Timezone setting of this machine; e.g. "EST" or "MDT" 
-U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
-w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
-Y - year, 4 digits; e.g. "1999" 
-y - year, 2 digits; e.g. "99" 
-z - day of the year; i.e. "0" to "365" 
-Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
-   			The offset for timezones west of UTC is always negative, 
-			and for those east of UTC is always positive. 
+	a - "am" or "pm" 
+	A - "AM" or "PM" 
+	d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
+	D - day of the week, textual, 3 letters; e.g. "Fri" 
+	F - month, textual, long; e.g. "January" 
+	g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
+	G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
+	h - hour, 12-hour format; i.e. "01" to "12" 
+	H - hour, 24-hour format; i.e. "00" to "23" 
+	i - minutes; i.e. "00" to "59" 
+	j - day of the month without leading zeros; i.e. "1" to "31" 
+	l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
+	L - boolean for whether it is a leap year; i.e. "0" or "1" 
+	m - month; i.e. "01" to "12" 
+	M - month, textual, 3 letters; e.g. "Jan" 
+	n - month without leading zeros; i.e. "1" to "12" 
+	O - Difference to Greenwich time in hours; e.g. "+0200" 
+	Q - Quarter, as in 1, 2, 3, 4 
+	r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
+	s - seconds; i.e. "00" to "59" 
+	S - English ordinal suffix for the day of the month, 2 characters; 
+	   			i.e. "st", "nd", "rd" or "th" 
+	t - number of days in the given month; i.e. "28" to "31"
+	T - Timezone setting of this machine; e.g. "EST" or "MDT" 
+	U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
+	w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
+	Y - year, 4 digits; e.g. "1999" 
+	y - year, 2 digits; e.g. "99" 
+	z - day of the year; i.e. "0" to "365" 
+	Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
+	   			The offset for timezones west of UTC is always negative, 
+				and for those east of UTC is always positive. 
 
Unsupported:
-B - Swatch Internet time 
-I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
-W - ISO-8601 week number of year, weeks starting on Monday 
+	B - Swatch Internet time 
+	I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
+	W - ISO-8601 week number of year, weeks starting on Monday 
 
 
-FUNCTION adodb_date2($fmt, $isoDateString = false) + +** FUNCTION adodb_date2($fmt, $isoDateString = false) Same as adodb_date, but 2nd parameter accepts iso date, eg. adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); -FUNCTION adodb_gmdate($fmt, $timestamp = false) + +** FUNCTION adodb_gmdate($fmt, $timestamp = false) Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the current timestamp is used. Unlike the function date(), it supports dates outside the 1901 to 2038 range. -FUNCTION adodb_mktime($hr, $min, $sec [, $month, $day, $year]) +** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year]) Converts a local date to a unix timestamp. Unlike the function mktime(), it supports -dates outside the 1901 to 2038 range. Differs from mktime() in that all parameters -are currently compulsory. +dates outside the 1901 to 2038 range. All parameters are optional. -FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year]) + +** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year]) Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters are currently compulsory. +** FUNCTION adodb_gmstrftime($fmt, $timestamp = false) +Convert a timestamp to a formatted GMT date. + +** FUNCTION adodb_strftime($fmt, $timestamp = false) + +Convert a timestamp to a formatted local date. Internally converts $fmt into +adodb_date format, then echo result. + +For best results, you can define the local date format yourself. Define a global +variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using +adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax. + + eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s'); + + Supported format codes: + +
+	%a - abbreviated weekday name according to the current locale 
+	%A - full weekday name according to the current locale 
+	%b - abbreviated month name according to the current locale 
+	%B - full month name according to the current locale 
+	%c - preferred date and time representation for the current locale 
+	%d - day of the month as a decimal number (range 01 to 31) 
+	%D - same as %m/%d/%y 
+	%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31') 
+	%h - same as %b
+	%H - hour as a decimal number using a 24-hour clock (range 00 to 23) 
+	%I - hour as a decimal number using a 12-hour clock (range 01 to 12) 
+	%m - month as a decimal number (range 01 to 12) 
+	%M - minute as a decimal number 
+	%n - newline character 
+	%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale 
+	%r - time in a.m. and p.m. notation 
+	%R - time in 24 hour notation 
+	%S - second as a decimal number 
+	%t - tab character 
+	%T - current time, equal to %H:%M:%S 
+	%x - preferred date representation for the current locale without the time 
+	%X - preferred time representation for the current locale without the date 
+	%y - year as a decimal number without a century (range 00 to 99) 
+	%Y - year as a decimal number including the century 
+	%Z - time zone or name or abbreviation 
+	%% - a literal `%' character 
+
+ + Unsupported codes: +
+	%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99) 
+	%g - like %G, but without the century. 
+	%G - The 4-digit year corresponding to the ISO week number (see %V). 
+	     This has the same format and value as %Y, except that if the ISO week number belongs 
+		 to the previous or next year, that year is used instead. 
+	%j - day of the year as a decimal number (range 001 to 366) 
+	%u - weekday as a decimal number [1,7], with 1 representing Monday 
+	%U - week number of the current year as a decimal number, starting 
+	    with the first Sunday as the first day of the first week 
+	%V - The ISO 8601:1988 week number of the current year as a decimal number, 
+	     range 01 to 53, where week 1 is the first week that has at least 4 days in the 
+		 current year, and with Monday as the first day of the week. (Use %G or %g for 
+		 the year component that corresponds to the week number for the specified timestamp.) 
+	%w - day of the week as a decimal, Sunday being 0 
+	%W - week number of the current year as a decimal number, starting with the 
+	     first Monday as the first day of the first week 
+
+ ============================================================================= NOTES @@ -166,17 +236,31 @@ a. Using an algorithm similar to Plauger's in "The Standard C Library" (page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not work outside 32-bit signed range, so i decided not to implement it. -b. Iterate over a block of years (say 12) when searching for the -correct year. - -c. Implement daylight savings, which looks awfully complicated, see +b. Implement daylight savings, which looks awfully complicated, see http://webexhibits.org/daylightsaving/ CHANGELOG + +- 18 July 2005 0.21 +- In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat. +- Added support for negative months in adodb_mktime(). + +- 24 Feb 2005 0.20 +Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date(). + +- 21 Dec 2004 0.17 +In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false. +Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro. + +- 17 Nov 2004 0.16 +Removed intval typecast in adodb_mktime() for secs, allowing: + adodb_mktime(0,0,0 + 2236672153,1,1,1934); +Suggested by Ryan. + - 18 July 2004 0.15 -All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. This -brings it more in line with mktime (still not identical). +All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. +This brings it more in line with mktime (still not identical). - 23 June 2004 0.14 @@ -275,12 +359,11 @@ First implementation. /* Version Number */ -define('ADODB_DATE_VERSION',0.15); +define('ADODB_DATE_VERSION',0.21); /* - We check for Windows as only +ve ints are accepted as dates on Windows. - - Apparently this problem happens also with Linux, RH 7.3 and later! + This code was originally for windows. But apparently this problem happens + also with Linux, RH 7.3 and later! glibc-2.2.5-34 and greater has been changed to return -1 for dates < 1970. This used to work. The problem exists with RedHat 7.3 and 8.0 @@ -293,16 +376,28 @@ define('ADODB_DATE_VERSION',0.15); if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); -function adodb_date_test_date($y1,$m) +function adodb_date_test_date($y1,$m,$d=13) { - //print " $y1/$m "; - $t = adodb_mktime(0,0,0,$m,13,$y1); - if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s',$t)) { - print "$y1 error
"; + $t = adodb_mktime(0,0,0,$m,$d,$y1); + $rez = adodb_date('Y-n-j H:i:s',$t); + if ("$y1-$m-$d 00:00:00" != $rez) { + print "$y1 error, expected=$y1-$m-$d 00:00:00, adodb=$rez
"; return false; } return true; } + +function adodb_date_test_strftime($fmt) +{ + $s1 = strftime($fmt); + $s2 = adodb_strftime($fmt); + + if ($s1 == $s2) return true; + + echo "error for $fmt, strftime=$s1, $adodb=$s2
"; + return false; +} + /** Test Suite */ @@ -310,13 +405,17 @@ function adodb_date_test() { error_reporting(E_ALL); - print "

Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION. "

"; + print "

Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."

"; @set_time_limit(0); $fail = false; // This flag disables calling of PHP native functions, so we can properly test the code if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1); + adodb_date_test_strftime('%Y %m %x %X'); + adodb_date_test_strftime("%A %d %B %Y"); + adodb_date_test_strftime("%H %M S"); + $t = adodb_mktime(0,0,0); if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'
'; @@ -485,13 +584,13 @@ Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 1 $year--; } - $day = ( floor((13 * $month - 1) / 5) + + $day = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4) + floor(($year / 100) / 4) - 2 * - floor($year / 100) + 77); + floor($year / 100) + 77 + $greg_correction; - return (($day - 7 * floor($day / 7))) + $greg_correction; + return $day - 7 * floor($day / 7); } @@ -513,6 +612,7 @@ function _adodb_is_leap_year($year) return true; } + /** checks for leap year, returns true if it is. Has 2-digit year check */ @@ -575,6 +675,26 @@ function adodb_getdate($d=false,$fast=false) return _adodb_getdate($d); } +/* +// generate $YRS table for _adodb_getdate() +function adodb_date_gentable($out=true) +{ + + for ($i=1970; $i >= 1600; $i-=10) { + $s = adodb_gmmktime(0,0,0,1,1,$i); + echo "$i => $s,
"; + } +} +adodb_date_gentable(); + +for ($i=1970; $i > 1500; $i--) { + +echo "
$i "; + adodb_date_test_date($i,1,1); +} + +*/ + /** Low-level function that returns the getdate() array. We have a special $fast flag, which if set to true, will return fewer array values, @@ -582,6 +702,8 @@ function adodb_getdate($d=false,$fast=false) */ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) { +static $YRS; + $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff()); $_day_power = 86400; @@ -597,9 +719,57 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) $d365 = $_day_power * 365; if ($d < 0) { - $origd = $d; + + if (empty($YRS)) $YRS = array( + 1970 => 0, + 1960 => -315619200, + 1950 => -631152000, + 1940 => -946771200, + 1930 => -1262304000, + 1920 => -1577923200, + 1910 => -1893456000, + 1900 => -2208988800, + 1890 => -2524521600, + 1880 => -2840140800, + 1870 => -3155673600, + 1860 => -3471292800, + 1850 => -3786825600, + 1840 => -4102444800, + 1830 => -4417977600, + 1820 => -4733596800, + 1810 => -5049129600, + 1800 => -5364662400, + 1790 => -5680195200, + 1780 => -5995814400, + 1770 => -6311347200, + 1760 => -6626966400, + 1750 => -6942499200, + 1740 => -7258118400, + 1730 => -7573651200, + 1720 => -7889270400, + 1710 => -8204803200, + 1700 => -8520336000, + 1690 => -8835868800, + 1680 => -9151488000, + 1670 => -9467020800, + 1660 => -9782640000, + 1650 => -10098172800, + 1640 => -10413792000, + 1630 => -10729324800, + 1620 => -11044944000, + 1610 => -11360476800, + 1600 => -11676096000); + + if ($is_gmt) $origd = $d; // The valid range of a 32bit signed timestamp is typically from // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT + // + + # old algorithm iterates through all years. new algorithm does it in + # 10 year blocks + + /* + # old algo for ($a = 1970 ; --$a >= 0;) { $lastd = $d; @@ -611,6 +781,36 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) break; } } + */ + + $lastsecs = 0; + $lastyear = 1970; + foreach($YRS as $year => $secs) { + if ($d >= $secs) { + $a = $lastyear; + break; + } + $lastsecs = $secs; + $lastyear = $year; + } + + $d -= $lastsecs; + if (!isset($a)) $a = $lastyear; + + //echo ' yr=',$a,' ', $d,'.'; + + for (; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d += $d366; + else $d += $d365; + + if ($d >= 0) { + $year = $a; + break; + } + } + /**/ $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; @@ -738,6 +938,7 @@ static $daylight; $_day_power = 86400; $arr = _adodb_getdate($d,true,$is_gmt); + if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv'); if ($daylight) adodb_daylight_sv($arr, $is_gmt); @@ -762,8 +963,10 @@ static $daylight; case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 + // 4.3.11 uses '04 Jun 2004' + // 4.3.8 uses ' 4 Jun 2004' $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', ' - . ($day<10?' '.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; + . ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; @@ -877,33 +1080,46 @@ function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst= function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false) { if (!defined('ADODB_TEST_DATES')) { + + if ($mon === false) { + return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec); + } + // for windows, we don't check 1970 because with timezone differences, // 1 Jan 1970 could generate negative timestamp, which is illegal if (1971 < $year && $year < 2038 - || $mon === false || !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038) - ) - return $is_gmt? + ) { + return $is_gmt ? @gmmktime($hr,$min,$sec,$mon,$day,$year): @mktime($hr,$min,$sec,$mon,$day,$year); + } } $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff(); - + + /* + # disabled because some people place large values in $sec. + # however we need it for $mon because we use an array... $hr = intval($hr); $min = intval($min); $sec = intval($sec); + */ $mon = intval($mon); $day = intval($day); $year = intval($year); $year = adodb_year_digit_check($year); - + if ($mon > 12) { $y = floor($mon / 12); $year += $y; $mon -= $y*12; + } else if ($mon < 1) { + $y = ceil((1-$mon) / 12); + $year -= $y; + $mon += $y*12; } $_day_power = 86400; @@ -964,4 +1180,108 @@ function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=fa return $ret; } +function adodb_gmstrftime($fmt, $ts=false) +{ + return adodb_strftime($fmt,$ts,true); +} + +// hack - convert to adodb_date +function adodb_strftime($fmt, $ts=false,$is_gmt=false) +{ +global $ADODB_DATE_LOCALE; + + if (!defined('ADODB_TEST_DATES')) { + if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer + return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts); + + } + } + + if (empty($ADODB_DATE_LOCALE)) { + $tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am + $sep = substr($tstr,2,1); + $hasAM = strrpos($tstr,'M') !== false; + + $ADODB_DATE_LOCALE = array(); + $ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y'; + $ADODB_DATE_LOCALE[] = ($hasAM) ? 'h:i:s a' : 'H:i:s'; + + } + $inpct = false; + $fmtdate = ''; + for ($i=0,$max = strlen($fmt); $i < $max; $i++) { + $ch = $fmt[$i]; + if ($ch == '%') { + if ($inpct) { + $fmtdate .= '%'; + $inpct = false; + } else + $inpct = true; + } else if ($inpct) { + + $inpct = false; + switch($ch) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'E': + case 'O': + /* ignore format modifiers */ + $inpct = true; + break; + + case 'a': $fmtdate .= 'D'; break; + case 'A': $fmtdate .= 'l'; break; + case 'h': + case 'b': $fmtdate .= 'M'; break; + case 'B': $fmtdate .= 'F'; break; + case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break; + case 'C': $fmtdate .= '\C?'; break; // century + case 'd': $fmtdate .= 'd'; break; + case 'D': $fmtdate .= 'm/d/y'; break; + case 'e': $fmtdate .= 'j'; break; + case 'g': $fmtdate .= '\g?'; break; //? + case 'G': $fmtdate .= '\G?'; break; //? + case 'H': $fmtdate .= 'H'; break; + case 'I': $fmtdate .= 'h'; break; + case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd + case 'm': $fmtdate .= 'm'; break; + case 'M': $fmtdate .= 'i'; break; + case 'n': $fmtdate .= "\n"; break; + case 'p': $fmtdate .= 'a'; break; + case 'r': $fmtdate .= 'h:i:s a'; break; + case 'R': $fmtdate .= 'H:i:s'; break; + case 'S': $fmtdate .= 's'; break; + case 't': $fmtdate .= "\t"; break; + case 'T': $fmtdate .= 'H:i:s'; break; + case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-basde + case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break; + case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break; + case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-basde + case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'y': $fmtdate .= 'y'; break; + case 'Y': $fmtdate .= 'Y'; break; + case 'Z': $fmtdate .= 'T'; break; + } + } else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' )) + $fmtdate .= "\\".$ch; + else + $fmtdate .= $ch; + } + //echo "fmt=",$fmtdate,"
"; + if ($ts === false) $ts = time(); + $ret = adodb_date($fmtdate, $ts, $is_gmt); + return $ret; +} + + ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/adodb-time.zip b/phpgwapi/inc/adodb/adodb-time.zip index d3239dbc32b2687a01b5d322e20b63f24ad33fd4..ff50de3a1a78c79caa48fa3b7669ebd3121803a0 100644 GIT binary patch literal 12576 zcmV+*G2hNmO9KQH000080HL7vGMgv19GWly0IHe*01^NI0AXZrWMVCJX>DaLX>MaK zaA{bdJ8ZRlUWSdCdU{Da5CPU9MV#kq>lTc?QS8Io%!zj zyZ2U=x5Jue0f_TIoE0UacITUiw3I>g8I!3x=teE}LrR zrMXJRDxYd4@4aD`r`{+Jl30ZTR;`>Si#SX?|4>cye0JFB0Bd`phhZ|w+M^`ucz)s! zZ++mt&4Wnax|P++hqoV8?B&6oR`gzt=P_f?)I8HFh;u#BsiIX`?nSdqjgwRX=WL#P z4A-t!Ug?oX&`fENH5pT;yi}_c%hF(!YhUFF^Rd)knyKDFx7X@-2m1<)e2jy8Rjqij zkLNGC?)gta>?ey%`EyOHEiuWRPRC)gU{YkOpZ>L{=+CCRQA^Ol83&1{;QoOx5Egjl3{iszJXs4Dzg@7C}B$ zBvFuu^*~mw%o40n@jM!q7wzrHqBd#al(`tENu+w+t~zd?wu$3G*ZxAX2?3N=D^m}2 z4YiIH)eiO^L(D_rW($3);xiG^e#zt9*n$Dq)dd+f`ZwIt$1el zYGskkLzsw16efuZ6UdIG$?N86sv*Q6nuR*TCx=1|JNiuaSr<{3lrCC@XdkFEBa+5R z2rJ4CY1PYFs=wQ)RyHO&CzGl-lWi+c}zGW2U5ZjITV)S2N3o#<8Ux# z90eF0t??R|)#ImOCQ%XUWrx@YG>K1>+wmfulfBXz4t$85wAobpexzr)Xs*PyH=-A$ z{cJwWbY87MJMs=kXB=o~cTA?A<6K^>ID=t|>E&YmVM10zugU)3T--E`V=((XUI7>a zT`d%I^u1*mOs2WYygM93Hcg!BBv(_Q3vrN*RfWsPWI8+ay<25y=3gZX3QVXu3leWT^zqZIip`+!)Z-HnaXBb`%O7Fc4Hut zqq5#5FQz)xr01h;}D%IjQ0#$M8EUndcc4%C1ry&-K8y zsnm-nLi?Mmvp1Jl=g05W$>r76*~!iM<$LBSnQ8SV)sqB7XVWCjH6geh<;jpd^jI8F zZ+E{>&J}M-A?%XpX@-xaRtvq;6u|oT^DyvYDA^rOA}WfsAAkXH2~@AsfS23FyxCdf(N;v|br6rV>bARkO|{TQ@gne10_BgO{HDqh_5h_5*lp5(J^bBm67Gg-sr3Lm z<~ic9G zBY%k4GEyCC52mT+Fy>Ufx;|}X`7)%~H_|a;pgGPG(qR;kZ?*E9H~KsrB8o4j!DtGj z7=?46!g+!J=E^O?mE^a6Fdo}yL3WF6XSd|pr{g7+|)%3`r-Q??T8 zyc2ox+zUH8?pTX&%WiGXlKu^XeD(2-x;p!Cd3AFwK7bMfm@~y99BZ7jLgFF`7-Th% zAdH+AY^?IF5CY{~i$3rVhV10YEEr|P!CwRaXy@O;#_Nyo`DCiov+I+q^AGfy8LC#E zKUeN;Ig)MB&m;JROtY0MhC3<{q*NL}GSBK`ag&dTCPlbRkh3ZZ@CI z;0Lm5MZC=<)s(MLtcW??BRNuLCkcl5YXa@Cw-?;xd10z>eZF{i4+c5a^EAj1fmjXW zAcY&|H6?~$q-D;}D=XGuB~@|Zh^oeY6MRvq1)ojQHPYm` zn>`HI4(TfMfv`NdxJ@tG#A#KVGyIEZ$Mo#@LY{rN;AcLb!L!+*7{N-WP1ToVGLs|& z=iev0`CX?;_N@xq5YuM2w@K7)4tk8|w2Wt=^=C*+-{*5mGzP$tQwH*_((MUW!|(I5 z*H~uubikA?TDb4YiKI)0od6bxIYoTwx9EeF3lRxPuBX$G+3PcoHx5UC=gV<)1xJ6t zIHpg~@lY~m%ePN#>A=g_1CmG(&tV@AA$AWK;rF*i-eJ`+Nw8nc5eL}`R;Og;TsBb9;BufKM6x@fA+maZLTDFj?BbCT!8jN= zw!mLw371%Oia3W9jM559Pg7K33ks6#j!+hnw%l&tbo-_NMr zu!%AZ04V^jUZ1G_e!t*l=&)L3NSv^ur%v^V!hKiu_71zf!|n^U+9m^*Ov7*cPg%k> zAkN}R7-Un()~BEhZ!jLC{w9@3uK4(DkER|q9axg&SC!h>*pLmfe6y)GW1oJezGy6; z@@6?Ule$-NF|c%%;{*;qE~~S@?@SI$Z?Nl5X)$JbgU#cYJj{@Bl!0UQ z2IYEUM%08s>bYhOa;kvV(5|-ZtX4k8CMIeBa21kXfu-w(hr&jkqclm8B+5y{yK_|^ zd9xsg0SDxd=&%N3b!yALYg6{!aJI_6guKln$S6u~{DdXv*O#sRJ;YE_Z^2SUA@q<7 zx>SrWRu>5=TXE2Ils}bX^lgq2WC?Y5uJe@8tn!R&k2097utf5xK7{BBa939YixL<; z;V7?4d)55bMeCD#dl=N3HLeB_Y5KdWHy|f5*r_$Xl|^ea!suU;6Hy`l|1%?6$F!;A zwx&?^7Q!cf;;8&gzlhh{;xcoKjNzA}2sl)^^iPB^C*R^&X{)t7*v3tX3!5$f2^Z=Z zrTc@nOfn<1Uic)7u2=McN%e(XqOki~9#`$De~L>9uci@N=zww9pd7X&1r(R5UbS(g zy%=UmDjl750&z{RKQQ*MG4=KPe910fUuLied4@WFnasJ7B`1`XQ!sFo?k*{_(cu_M5-`|Dm<+wJTDkMmz#E2I zZJ|UyeRX?!d~q&`~Y>6WDUK(BG84C-E z&O+%380el%<?&9EwiPIlG-H|Cxm~UTeBM4CSRw*0D=eNU$<)|MMze@!JXMc zMdAFl^VTP%FGGMm2)4X}Be)C9@u$mEc4{dS9MANE5y{L&NmH#80(G4@GunP58GTXQ zW>>DcwyC#7CD%@?bQ4>&esfk(s+6jfdZvN@M_0Qkx$B;qi&pkXCRh>ue7@L4eJbDK z1>?2ohnku=bYZr!VM&;gCX#u^`qB5fDU(*0xF&&zaI#!`(uLiA(0Y2(IGj0&f8W~^ zS@l-rTRC87R87aFPX=y@B^>1&t zQc)U|; z%donOyG!21TpMvd#Vg@&tNO=`%$`gH$AG+#Sdi5`W#~BKv9Z3Dsb|*8isG=|E1QA+ zabSF$lpkUqYuYp=fipyuC3SNT_rcshE1Cb` zN;C?7H^VgM!cY;UhjLz06-4HcE@$&;gp4Z+LP!}p{}6g}c+wi%;3gf9YraBHeRX2z zps2l7pLwwKo&J7P-RF6dN9~ciy`c{%4{iAgceuj0+Ky)is0Be|Ch2Eag_bYB`7F_G zunJi76ar`wh;(x&sA;*D7@{0=&-@3I2KM4KOp?zaV?oKa6sKXpK?IvicOx z!$9pMopdZdLD!M${^afP`!{FrF5l2EE!Eps-_L-@V|4w_*?)A9- zQ?;~aBLSU!giEjq=lsqzyt^cLvQnzie4k#O2#mQFj%FS)-BQQ&)|T}A()Rx(zsy#( zS7{)pMakA{Jrr6&YPVVuTs#~^I8D9WSrzDZpSHU1bx8qfa%WT!tC>!jC2H-uAs}fH z*&SV@dQgg>=P9;=jIO*%UR=vloI9q< z^YMH@1G$745!)Sj0OcWq|EmNJWE|WR>gm0@@aAb^DDS;c?~^-6`5s-&M#-H_XWUUv zxr93;-~CA1tP|v~8I{6evVeN&WUnDieWUt)1lbq;9>PYC{yP}#P`!ISpG!d9qfe7e)TN3XWR`dIa3&ba==^4`3nA+MeGiA=4OYigK0Wj z6NuaF4!fKi|8ARLe22}=P7szvTB0(^D7MbAVVX0x^Wy?#`raf1UYUO`mv`9?r_6hPj z8cm>X%vPk16v6*ogU_k`@~s8M^CPvV{{D9*A73;K7~ja%eo@~XsUD#JLBv?@*$`!B zfQ$XoKwB&)*FASWO$iE@V8a8^RzL{5;>n4+;&#)|=I-SenzrnkXXd81^o(gNLqS0N zpvU=z`VX5(n6|B+a2xGmi^D8VVqV)-NpQOS|u&x7wEt zs;E(crTbcjb=#m!(o|Bon_K~;tVr1F?+aj@6mJAA>JeaX>9so4ngc7!GddL52CUqd@_w4 zl}@~a<_562)O_~r8N7>$^J~Vm>U>*?oQIt0LrjL&19d!~I8wV-D8sqQeWjc4jj8OG zksd@2RHT1C4i#k+Hw?9Ru-`S&#RV7IuzO$=gkrMsgQ}Y=bn@)-zIX-Juz8ogGNU?+ zt%KS<_EJsu8<5fgYB$_pw_)wNR(1)t`#XhCGuaT%H;sJeN}9^Y@7`Vhbo>77&GF6o zk7u_uRfgk0PJTf^l$$~JW)9J1Ppd>6bxOXV$!>c&(mU8Yu=ex9CQ(fC3kkpui5)Pv z)2-HT;jAry)>+!sTlJzn_{JGnyQDd2ICJxO_{FM<&d2^=v>)V0eIaM3M9rQ%l$4(& zP2>x^eP@Kk$nJjsnS`B4d$E~GLJibnNOPA*_c=tbo6fZCSQ#8BSh?GEm!7_}&Ia4* z(PxTtzPUz{u}7IIrL#=qys4^VSEi>y*J@c(t%NHSGzDqO84;pGN+uB{8C9(jyo2Il z7_RAK}yV}ZpS!Ff$BGww4} zuFqwKv|kbu=R0mP)>1+q&C1r44ZECEMC=aoX^Oo)=k>-o;D&4-Q4V6HqJeK6LCRB| zyRF_1`#2JATV2`dQ+63LJ&C%c>rOAy|6x*ICE{*MroGTkGP^6h?lcsc9MDs-K=zlM zDT;8NCpF(9k=#9->+Fd`%r`?no?Ts^U%qc!ti?!RLzm2!a96;N4Y0ai(ojiTttFIC zk1eonA5)|yna%2Wa`zmchI znp*d=^29K;pZSYGD4eJVJ%cCLeB;X*v1NQp@i*qCC7(nV#5<&0_f6yVR^Os|R^^+$ zNf-=At$w@T-fazb__ZBdrDB=CWK(crl835R&*bT3`!9h;^ex_vTcCiYijSXZN1(n( zc5NmkueARb4$u;{-$o?d;H%oYE7X+y?aAMRy>6rNtx}y15F#1RK!pj6}Nsn~k++dZc&6mUP04rXTI_)Uc z;h2veuQ!$C5ute58GiS2n0~iO`)wE_VFzqPd$Ee5k$-&SIlkPU0In-V7IRLIDK+v^CcQQH}2v%cf=0h|92M?juH-DvKu z2e}r5dWzM$;f|=F{clrEfe^m3en$4jOjyNCcfKRM+>2Zl4s`a4meN+{TX094?KRP$ zMsf0}*2YiwZ1ZIYxS6N_M7XkFutc#@?~0JeUJ%;J4#rT>6v=?rPjkTb*KOA@7c{fJW)#ks_;oMY)+ zl*m|gD3L`{QIy30{rZK+%wQxs@owGi*2W@%Mx)VaG#ZUYQ$6^ndhmMZKG5gt!Lj;b zNB3W`g3W^byq;gSm(e(AppfPYV5~g*!Bc&93z{CR%>bn`xV!JL8zv#1>h2^0wFc4= z(D^U!!m%*8gN$O+%_vF#0ww9+qQqH83$u*g8JqF|j`r`x$~Nyv0g@I))hO_BRT3uI zfXC5lIX4g&^BKmCvlYPSNZemq=kpm@7uPHFAJLAZB6$$TW|Eg5PgH>;&_ZFqQ4&Xq zmn)B@A21f^8g{c;Ne5xliSL$DLj*$Nw4?(c0m4mV1+F%yptmsvJ*1#rAsBXc{X{T) z#l*^^IMA1Y)xi}qAP?+FRPf*iW2@f{s_uDrQKD2V+XbwrXFs67>Eau9U@9U1f* zb>?7xd2#K>oDt#-5d+NKh`lRXA3F8Yy+hX8VY?lIP1@N|)&Me!GZ1*6tc~3RZ=#Ht zRdt?m=e=ap&U;A|L;vl2J5TTLJPEt;M~}Q}mE}5b-=U2+peqgA>BkX<+tVh5Wq+5j z?nlZ>w|c|M5!U&8gno^ zHo7_}c~orp63A#Zpv54^3bWYnz>{b^Nfn-CBRr|blUCtLH^S4_c-mEX+8g1?7*8_D z{CKcp6FeP_r&EQevk{(w#xtnGGq8BJ`GA0yJx4!^>v@X7(H^}`M;QZh(9)I{Mu&so zo{UdMC+m}mddZd$pK#SkJyK)!L_JgQ)K}_4Jy%opUd_}u>QWu6EA>L1e1G!nt5@nq-Ky8>cl8tbjd*p@*^Z82Z*vHbjUfgA~u9s5i&G6~B_ zZ0cAcjFQ2=AI4$rmmxHsO|A%VU)A2L16BJ4KkV*maLw*FwfCpOa{Oqjh4YxUW4&Z5 z-W$se|97^WjDC?XALtMNtL0FeQap2e3Pz7ZrC>|7{n-~+XRF1&Izb+s?5H{kE6@x! zj6-~Lr;!6q5!CXv*dWCQWQb85l{LrAX2q)1ze>YP&vQt>D6ekg0>+TVgvxyz~NCi;q8wdgA8EtVn(G%5YuPGz8RJehARPZMRXrI|A*wAHS~%G zyj|kzPEz_ZCH>QBrk#iVE->q1o!i>}Yx3}t^^{;sPzQxp6V)z9zcHqVh@Wv$#cZ@% zlNo`mG*f;v(Gxy#-x-A_h0c`jS4K3elG4W3oQ=+Z;cC;8(Gnc)YdV0KE`VUGTBx(7 zWSKHPd?&<;;*gu$C6h?_2wmZ+i@xmQ_+XXOs{k6dL{o(FLUkw%+f%&RonNi>*jd1^ z%`WJ>Dd@u~Dn=-vk66fUwa6_e)RufylzG(=bMRI7?5@^|vvVm2QGPzY7f z)an8|3!h7vN@^6XJ3~^HTgJ))$Z~czIM!mdtI5r@Xv-3=_Gw6eGx^(*zp?yHp5K*z_dlbuKa4ZrV>fq0G=4x7!U z>JIg5ZVF|8Wa3Hbb>eqVAAP^K_XM@Yk{i{<=$HiD@d^9{QIj^yF={OV@39IxQ0NnPCN zOgH1@e6g5}Enah5zWvz*)WIz(cuA|r;ZHh^(aUKl$-kzn^Dd)z2 z{z>8HTT(h?X!XSxs0`>X_yCy;VEQ|P#0Y@XLTDQ3HLjsc=xxp$)Fv@jC~7S1We`$5 z9}Gwp1dT`&aHvv{1_~mVk_ZkzMyUVD*WubB98`vbj3T|3w$XhCgBU7IJ~&_2>q%QZ zG*}fFk}cI~s9kAJD6qk<=Hdg~bn^g$DOcZ8*&RSF2PjghdRPL?!R@ME5B@3gO86vq zL_}t!dN3S8fdwtqYv@HS%UV6gJ!vH|6XLZDMQN=}cp5$P!%$Rn`mz`891?=zXB-`| zGLCJ%AWSGnv#{pnHs4Ku#e>CYwm))${6J->dt-B<=H3nEz+lx436Mm-aQy~5F#tRM zOB3R9Nb4lDkDTV~2;Vhv*!~$WXL*>9)EdcEw)aD`e4P0wYE+&adsV4&^X6Vx>KQu! zm>GJGfpn!Q@~YZut_v~V>8UuZb9*CQyk$I_{+1&K==*WLl(CGiZq3s!80FTZ)#{p4 zjq)Qa-4Mf{Ff@gNdD@~;(S4*dX;M_Md1_@*dWP&FJ1=RZ?nHD*Bi*9yQJ?bTwFV#9 zcI0vnc4v_l7o?7DTE_U^HfneI0EOXDbP7!LrNSJeJ2!Ia>qDXt!cJUmMh3 z+>Yr?)I&NTP#Ld*oRk2QZN!w1$&?yp%}oh#ETN`?4P5~3A` z|D3DZ%b)f|qNZSXt?N+GFnUXB;s5XnXf1fkQ#!oiLx{+xb0}5rI|Cwo9z)G!r8DuT z3iHwVSB6b-$NB9-upw7#lk3i`kTGa8osmJ0$Q;!5sPDc^|HDk{=xhZT8)&4&zxAH+ z{}2KrcFbYPyoL3>J|fxo^;w9FX;7T|n2ya2#VbHUq(XIh4X1oC>2`lL>6;0!X7QJn zJN9Vd$kf{+4;?)S|F!IaviAD>AMi2sjGT|9Xf}V~#ygBFgC_Ob{CYh^h0imx?f3;i zEa;#H<4d|ReU65S)-<)1_16?-Dlum@K3m|q`w)(oA)hI>c&H!T6cd&rcD#ImCix3vlF&KH}>)0cI^C{``Xwq z;Q_1W=OUKD23UyS?QR!$8i#wB#B z(rn;}LQh8COQ8$ogQ<{__d3AZjw1{`8F{bYAEdq5X(1yA)&K_`Vd%-o`!Ke4+YyGY zjJ)4(cVI>=6T33BgAx(*wy1rE@+41`GpL0z zZMPKANQqpgV$9IXT(EK+BgZ;|F*m{O0-tGOg!d9mQ$g}0ci@yYWKE~C<^1~H1*H>{qukZx z#(|`L507hCj3;5^U!7r^ot4HHZHks5MlNxI({Sx7SI z$>{uobUj)Q(#;`dn_KDLEkU{BE#j8JTR~Wk6l%Y3i}k2Xdwb_cd$wsym1JPcS%#Qe z?w@A2MOI#*ZkNL#tc}7z1?ayGgJxiWXuAJjPBNIGcAAklUthiEc4Xne7B7?@p&$&nPFJC9`l-!ORO|j=ldfQB%krx?V`{ z;ggJW193a}gwj?aX?X#2<;!6hpP-;B0;u~1OO++dTrbej2_ErSC16fm{IxW^W;@C6G7uT#V@?sFYv+QyC?iU{Dx6m*E8z z7tODvC0)@`8A>V_l7pJdbW<6lmD85XdIrWt!w66exs0Zq3+W>kx(p^B&u`SQbbTnK z(d8j)j(-zxZfp^p`~P+9k{n+IFX@Pb8SJ_i@L|2Zi$pXUhK%(^4*ppX7M^<%fhk7{ zb2Bn-*>;7m#xqm&A36z`&#C1%pQ6JYh$mw z%w&<)t`z0*pJ5&v9 zVd^hZ5fr#3dqr`t3S1zy9P=$LMKIv^ z&5?;Mr!Jz)XcZkFM^BzauU{MXh#g2F6TG?kpAJ&b^ry{#5{abHyWdcKnGeg5C=B@1 zrk$aye{&5i`{hI;mjNV<(uN=8U0jqdSmlyQAJal787r~QM=|eZi z#3S{kvz8ir>P!1YYyAH-|9ZvXfxo%&hwNC#rrH5t;k?8e4m>Kk=1J)krQMZlJz*r; zI@ib0_?+MJljM4!g~4Ry3C#Rh9I6CW&!_Iu)EYYv6Y$X9aLOivv4V05e6-!nrML}n zu~;U#JU))8A@H)lo#u=Ts?s~+siupA=X4OMc?3&AM^F*yfPFsLkK{KE=?5I;2gH7r zeCKn?ucakG{fbwE>$$odT}>C{DaW_iTb}5jP_|qrAv;zrVkBAa_LKFx4%A(+Q zOK3+PpF4k(1mS6E04S%Vk&AyU- z!|myr1iV zda!yBXX7BOW9x&saTM$V?kEUJm!rmLwYv>hytp?Ove$XxB1MSSJ!eD31THmEl=#Xi&9%B3SG8*A;FdW!rveUoT;V7R5yj^(UOD^OPr+V68QB{P zzC4b+8mz>j7luQu_ljsfN)P@8HE1b$t|{4QSMjmWttyW5qKy5Jr|*IcH7be7EoM=Z z&EYoT2t{rZBxxYPLWsr0WBXu6C@3x}Ms(qo22<{3*H>1w^W(2>@=k>2-@^js@Ziot z;Rf~fx34IdvnF+FwkV%rP-PczVGi>TPanVd_KAb}RY3ujm&8i!N1THhh6KPk(s)=)0$emYtK69WBvt3~&^*J|DPr z8Jq+A? zaYdw_`x8}kAVP7W?NWOqU{BE>aVvG46yrinU(S0{iI*^jvMn=~g740CtoYbrBP^Th zg-uj;cB|y4lbe5;MO)kwI-y4w6x(I5r6cvCe$`Nz`G-@psmJ;Ohs{}tPetlU!_V(e z!R>;B$O$>V*Oh~^s7-9wZ^Y_UODCfz_lb{Qbfb97ji_tmz)2lP=lAjaDp-rJh;GGn zUQClSk0NHr=0`qPp^i&PDByq^ofFSZ6l6J#XJ~)*YC4-i^-PZ&t!aw-MF)uqtUpll z=5lN6&p*|@zA1dqLZJ~Ah#G{++&$&Fs*bpHtAe@3CDPc_@Ebwf9bR7=Y5QnGDSkJ$ zq_)Ki^ADXJYiuTq5v|5j&oADSR_mTTZbSMe^vdq}wL*EA4Z-b&AJ) zuVXxCy4>(|JLgzqp5YhIvxR-@o5jA_mLXZ7XmYuY!K#+h4`>-N-lKB>K2_so-|a(w zzv?~?!MX!H7+9oy5s5kOV0C-d3#)v)p07tU^06xkpdk(tR}T4R zzTv;Fm-}e(dgQO9@4TSr6-eDMAV0{oSJ5#43mzNVq@}U$3mBjuYs$@4f9~PNov569 z_7bv=)e=JKNb53m=j%2O^H5|A4j(B$qfDO-ll|J+0SX!Xbuu87ky*;$)XwzP`v*%F z-@4~p;VO;zafUn?&H?1E)-h1#qIgY?g{6ycEJXc*kKkNYDKbLBH`)( zu`+UKW#q3(M+#zbDB@w6^@+qI-|7-`@N+y5HRlE>AM`S3_>tnVUvBRRTcm82E1yyQ z9uc(&qk{Ocj1c1y7stYVmHk|mY zKTe?ZORuZy6GBp1)w4O zG39WEfwW@@aqeM;XN5mZu!V-?LfKmkM2aqWv866Xt4GJ&$#OAYNquk}G;HLD)iu?> zax3Uc0B=qK1hHRHIwHp2j)O35@T=b=^g*MSXVDBU^@m%!Bs5>gwtT;W5a>tYIe^B4 z$AI91^HC8d&c4hlS0*T(5bKiQoZ~ff2LGIhr+_x9<4GwhrXGbLN>2f~C-}PIr6vrYL86>7) z@p{mD{#0%np5$(-tuHSRHSw}yWA>aF;-jxV_mm~DZf&Hok`&A|E^CIkX zU+-TRp)Pz-?~71JzXMopFZc;q%RCgH?(CinhG~G7F7LOLNeDkc37}GBpVncq zRe<~sAnc9Ji~h+@6JV%EV;khAl`D}Ld4;qCwZolI1BE-e99fj!(t6W5+a;Nv?9f^k z)0-JQ2%C@J^PGCNKRY`7UrDaLX>MaK zaA&~SNVVFP`dRFE3?hk23tqasWbiWFG2a*{5RDD{H_nij?Epxp-6)VG^W^oPxRF*@l?(lgP$Vx{#!(rG{deVs^DsOw(Mi(V{C5W4I(|fo=eU3cy5R z9O^C5a0xyvhSYEp}(a3Xgx&eE9NPKSC*`6ui4?#iPMf>QN9*!a_0&5>3FL96QzM z{Lcp65VIwhAYLWBFwsmJ&x?5`92(9GDR~C>c`VID5sv&wahVC>2`g%&bj8=JS1XHj z9zjKXrZ7z@O2IqHO*wC#WdckL<5?tPe6lE%V#gm@KO2gbYeH921#54JGiQ>o`i7 z!!{EQSl+Z?XW_@9U@c?I3j;8UW#EwbJQA})@q3L{f5ZbUvwS|xMNzGQr)mreKMnJ>U`=NwJy0j5Fon|DC}mmmFl+7evnxlNvtH-+48SmGIZ-K5;4h&2TMt%YVVh0z1Ojve-r#^I! zRWuM1^PAI)XXh7ZN3V}h`Rg;dnkguwd?rNTC~Y?j1Cdhj&5m?26`5d1kmunr5{ia2 zfe*+b+R>CJr_yck>I|;zOS!f&yalE6B8NbwgA>}{+;B*g`N>4l{`}(f`T51mqt|qN zesOVneD(7DwcJxW6ZAY2lN3bf(=;mtBRC%w>5%>ESh)?izvr<_#3&0yI?{QT<0FgJ zK=&L4*!XoGg?<7dTa#j<;#dSBHh^6M)w3*=)6HbJUVMG&KC5mR{?CL=+eR%h3t zh0uam3?HQs{s_W%C{Lx`uGvk;;s0Fx>pP5lhnln*pr^-SJc9vwJ$gvpU3kid%RAm- z%!9x4hY=p1zj=4@^7)G^{?Zujkk{#S>DP3cAmGPRDKZfWA6iLs=y68BT%I)ZVi|F; z8i@o!OIxyv!O#b=_JcqAI2`5XdZC*UD>%)x-qzr;yMV&WAiM`ud(Xv znmw_yT1aCOCNfHmQ;c!WquTapE5V%5Av6UY!~S)9Ob-& zpTl6#`=4y%+1uCBCh6q#^7!KA8~!Xev@*0Fc53{409TL;shk%AftRCL0$-o`OLne> zj}!o5Q+l5;QGOdjaX8l5_@(@8KA+8C{&}^coXjK>oLq2-NMvrtOyo4IwUI1E(>N|1 zs@c?#22>Jwtew4IrjCr#*WrZ4qprj;D%J6$SH~!P6owvj^A?{LQu>Z^M9SdxpQr z>iN;pnR@i*j2{Jf1SezSQw+&X9r9E*maAwFgA7=fUqqJXPbh4GN825Dn@Qd7x{T&z z9nC_BkKmN}T+BJ-cY&hdT;K_b)&!H`fqB+5%+f1bSWdPK*spBU*^)sg0EKB~@bg}i zKNyZMh2Y_4A~lV!$0(j#6khNCC^`y-*JTvbJE*wH6t&=sI~KIiYq&#ZMwrZ@6*mF; z`wZ}5gQ)JceI=rZ8XOI?5qvt;U)6WMDY8{DsCcEk z_T4gzUSS_Ao1`E%;@-@zvklsCOLL$S44W9(ACUh!=A0nZAphZ*&beWR!ezm6N@k0w zBv?vztw$Y?B~Y#WhMB)X6G4ddUjTF=RFLPOaH&=@j9)xErajMFaVcz>1{HD^OmOK$ zj5yME$lX2YxCfobWEaVSBo}arP#YqmCO*;Y1BnPA{+2qGu;pyz1MM14t*OjIg4t$4_S|q}0$3fm~Ud zQ>Swv|8WAp!|J)%q|?}lK-KS*8rir+9)ZkClD*5{eMB(%q*{3g9IU~PsY$IqxcmE3 z5K9Z;-GETzU)HI(VGfd2yL|@yCjbk>taLmEznIU42Msl++3R{n6VykUn<`0iY|t~M z5@>Aj+`7_udvz>LGg`0|6ETrh0Vlke&H0tm9d1-0+uJY&c}&PtcuiB}K~{;5IU+c) zA?FwD=W^krilCRM12W`g%Cf4Jm(&>fv#@~9hU|IRG{Z5Sm=fz!msnRaKa_5R9m^uj zIR^fL880u-n|r$mkSx^|?NpNBhq89cl*T1=ma>dVMnp^YhSb3`xkH$z-1)dHGR9Em z50@xp+3L$FDsAz=JX_}4>J?Z>!H9{B-n6z>J!qaa-_eVMu<_xV z`p%P0nOFR`BspB?{{KvIZtYmtNVO?sTSHjHZsZ=4He}mf?FE}{}&j6 z+UiHyPPDP{&&UxN0xv6W+H@d4rsuxM=3?Shb-PqN|uyjd2tSILdxoC>G zt_T<0l8{T zioy}dfH%v9SP`QbiqF%Ko87H6o3sr+g|4l9(eaC;*UwL1oj$&vn9Q)D> zcJ@)e2CRD8CrOR@jT$;H=XSdqUyZgqMmvdVo05uElZCbE?Szm8j z>k^Wa>=r3_ByZfqEx6}%^2_znt5@fLT)#ejesuNn_tR@`79sIjrgK^_5O-R^d)-(x z`Pu3j*H9D-K438p*WKUUH~RCKo{6C)`7uali#ABiIge>q50{E~nC}8;t)^YPpvSH5 zBdcJoHOWE3xoxxIixCx8?d|;}g0L8Pik#jWHM>SdkdZ8BDQf1uzGsz?H`3qp9;kD% z7zL$nYamr?N=ThOaExGjZM)TM$M9gEpyhVeK0keB%1|sPMjvG(N{1%Z%v5b+wqEYf zXVk!|k{)=p3fw&=q2 zl%>m1P0=pAiM8G+jECv^EX8g|MT~{8oavW%tu?G}vMci`se#g8#_Ze_bFC-Uhq;_7 zg?T;~`5i`la&&ci{rl;~B~r7N!Mf`EO_{9fR#}IbpeMz3$OWr9Qn*E^w4P&a7uPqA z_@rY-rUoHLx3!v44`qjhW>5}xMp)lcsQ0N4FCnSsdU41F!J`g-3}?Q0E(` zodAERV`cjxR0RbhM6dE3QX}n$2)e(kQ(Ss29g&)(s*FbcHe>4!$5&MV$?32kxl_4K zbN-G%DvzrkeUdi<)cKC zEGJ>|nXuG}&tY!*uoohD0S9S_+G`nsR^@&woyd6?OIIR zz_3*-P+V^~uB*k4+jRiR>ufR6+xXI~#Z9+s`%&BUV6d7d)ZaCeX23=NL0)%i1$MzJ zZ|Q{(hfje+xz)q=@af?&dn$?8(#j)?e17m1|LbQ(Hs?oQ^@W`+x?-EYoQH)_EWL{b z4ZUyH9bWM|6C5hwO&X`nak()=*|hhR@ybG_JZ@m^TjfoQ^mUEFc58#b1fDh!$t}To zn_E9|STs6vwc6MZBh$=yqG*H4O4}GmJ_qmIhdJczawFYQT)8V`Pq$^2f)K%H>aZZV zM7DNW(@oWJx)$0^O+#ULC5hgkVk=`xy|%ugAG?n0aGr0~<3VFx5#nYbRe%Nqs>_O? zvx`E3msL!!pQ`YhP`$NzYOBr~QvVJm-k+ev`%9Fp=*`Tk&BSIIhl8i|LFZlef)60S zX>WXf?mBL7U+tsaUMa_?X~YK;>VQ~P7VJ^lqclRindcyPDSZqz^_jm4CmZ>3LN_>q z8N};0-A>cp$dzNg4#GpiXAk$2ins5${Z8k8Vqr)Yi?_dt0L@LC7v%S+;PJgFc+3=Z z?@)|Vx|@km@ZY}o(5h3t^f`CvfWAW^RfSV|?5*)_Q2New3%h-V4<4H@T|D%9W|!Lp z$Gl;uE7|gZwp(g`nabeEXBz&ei-vqGcOlu|r=O)J*6D!i zh8#v+$3hmpLET%yd^MeK#@v&LdyE(`-$uOAqD>iMO!phQ)^)mF2U$q}p1KCeW~T>* z-=u57Y6;|$RkOPm@2SNfyZ2rEvD@rm{qA=c_rAZl>+E)Zc;|On+1ldWZ+PQ-(B(N@ z@5cz^@N^%-dViI$-5=DI-Ma(U8e#pvMi`X%&oFGG8pW#(fE67s4b51Y*Hjl``EG1; zEDH?e=j`y2G9Ooc=k&?Rh1-jcAKj+OMS~K znQZjiGIh5ghi#L2jbqmQ`upI$|Gs!H=t^Zms$3zTjwqlLdPWm^PE&e8A$_2TUQtYE zl+Zc7zj*)b{W0Ht$S9|R-qM1W^p3vJKV>IDSy%325mkNhDW*>RbI%&x%`q98F$??v z*m}jJPaCO2Tseq-AV$Fm&ba%mjR^Jzn3kJDw<#nMwRis!f9jG^6xpKMYW^ejH$OBoYbuglZq?kZK?K!=pzA+_3v!wGaQ+ zEa#7QSaY6lW*3>F;)BiH_-B|2|D*o$RsK=GjUJj*N=fd3uzTLByg5MC%1_BKpFN@X z%!Bva)R4*wnvuh-5Z~I~Sp)SLwB+l}2_8?7iI}_qP^M$H;?z~NCRVcBXCd0Fj#h+z zDZ<->nfSt^eECtGrvQtCDQcKmn}=USisyjbdD<~-y~&)i>&NU_%OExIb;h_A-g5dT zAnyjy?3;V%|Er}#F-M}Nv$=ZsYu}csZt^m07HO=f*rSV1M>Y+59B+){Ddo1(ngOIP zvNu@k0OqP$#|@JK<9#IUkaMlasMD+|#u$|&C>}K@Hm;{zK~JpsC0>5jrKu6i&y4+k zSiV}W)WH?)`(!(KAp3EaUhM&w8C$pO$uFVwKmC^1f4H{`W<6}Ex#jvbec4C(DUHo# zALNvts22O56{d%bU*VDik)IbbjbK(idwlON5whkY|8(tPB5P%X`vN4!5+xx@F! zovzY1dJ8` zBhzaMYx5si(HlSK4*3J?Iz*I&;va{CjE;1L(w{HHncWySlal<@S3Mlt^I8dju zN(EP*tI7ZUue!&mpAHl>{qz%CxIF1QWaa|Qd}ojj1F%>mnjQR5joUldYn`30)Jtm0Y+$ZK4Z?f4mQRe@;Intgs zlI&+bD<6nmI60aD` ziNAaNyrH&Gt^yUZshuns9KHhrB+mDfKB!y)*a=CRI))w{7tq|-Qy8(pLM>S8w-J}6 zUGk}xdQY6KVPIvy-ZQ7jVFH?s@~30-Qp(#-o14=6bM=({d5g7DxeW@++hUr_RDzpR z;C=J>*w-6xM!$NKf%*Mwb|-5YOc$Ecz!YljC{4ferEU}GxZ1Wygiapa3)W0l{yQ#ZPT~0z59k zJFuoGCPZW^uP6JF?{D&F1e+;0N4zU+mK36RGnn&TKio%W54D$$#DP`BXl*X;Dj2#d zA=z~Yt&1q+Ha9k9$xiOKwD36q*u4x=a{88TNi6Urwxo zA(_t2MMZN$h9Jvy<-A^z@x1k_muHB-n{6FjrhqXCOA+YGect3Jo0hlOI zTT8qj`evrMAx1+6X5S;dz$f6IYh0>o@)g{6u#NaV{DPAGFjGwH>*7pUhSYSS zBB*j%vQ{zI_gF?uJV1US-YuqkD=1UH!e~T?ASs^h;q01qo370QLw9yxRoC;Y0X-D6l znIQd3&l0i<5M|h7dn9$UdBn$Fl zjzt$2{78tB_*Qv+z1oIT{1X3dH=KXHKjUr=59r@7SuA@iU~w0$)sB!Jq~uVm1FV|j z0z^7g^dJYEHs`R}2m|oWd~u8KQQ)m|6p?}i+!XLj+H_Bk>TO$%&enEkdrQ9&@c|jM zsY_1VFIA)6X>Q>~J`%Dz?mD1o&u&9e=xX4FuGrakCckC`KuKs6v?vEAwu}6SaSDf* z@X3H3#%3LoBEapg{h}5p8Z$dmsx)92H?I4j#Ri)d>Gf6m2iR%ElEa4ER14jYA zMdmxLxNC;e;%!@L0vv({2n~*5bbxa@D#VuE49(ky;>!pwWWmpVDh>MRGg%TXA&&Tv zmO7;=dDRZCN6D65JG*d#r~-DwXpHVqg`BstGp|?&{dx9f8Iq7o2jKZdl<3m&f$^y7 zu9(qh%dyHbv?TuR!eVWj;8|EVS(SAIfIjQ)KbdoVuJ!ie593LNG^9{Q>k(?onpfb< z{byv$0+#eS(Pc!3V66V2D*>p-IZ)+U(1bE*=>(5>EEEFa%{QNsjbda?gWIa-L%@i` zz#s?_4)wb4!?HTUhDbuk5$4C5z^%|DuwRbkH_hyCEEXe1*8KX&-XZoe3f9Ohz1aaNS`r!$XJs7tzvgPxqR zj7!79>T#cAgMLw=du_)5b^U9XM81bz;PYV*=L~bcHywA6IjwaAyucE%&x+CLe(XT; z$?alRaw`fyZWeva?JTGJj)E0IC2OfkX%Do;U28`Ho1DKs`llW8lQ)E^M*6ysCAUo~ zxNSsTWl`|BI~Yf9?9!KF5T5wXenM-gGKY^@4`b7@LmwbTje5FD1f-!Hw`Pzao91wI5DE0;a6}#H z$Y3Fs4x_=YFdpi$h)TaqY+ZmK?CEB9D5X^OmvW>w(v8N}Fshbu^nN2gj4FUTiK-;# z@UYk0JF&|g{558gbDy=4(0M*uctE;fi}qiiQp$5At!m5r5-{J%+3AP37S#k$G1YOK z_X9ge9r>-3=Iqq|;Z04@R@!l|*UAG={lylbJP91oN4PYPcOI}gt3 z0C$8t9MK@m_x9|gqkn#mIvMe!!_%?Er<0(}%F*P^(1ayj7R{3+-|rB7b|!E2Ojgn( zA@aFh*>&FJvG?eSlF|(sR@9PE@W!Gh8^ImI$$B0VHCvGY%S0?DUfY9Np`f@aSkX<8 z8%%qUTz|LB?61Fg$S=Y)e+~(hLxZJ@LY4I6=|_6DM^ANRlv2nPD6#~&(Zl@y^{cbf zV+ZrcjL69!iBx|(Y(Ny+57O#={^+Fs?nHh+oq;#TPubzi2F=d)9_A>HPAEk-z6Q!m zU#l&BJeH?5$nIY6py`XB+ev{~8BB6wg>fD|iu2t`0nVe798Pe&24BbXtYp$QcZM{t z-@iI~_u9;5{qyH_&Cy`CJ0e-z^X|M1&dd}t`A#0t4QHJlhnOEc9AJ82-E<>D}%>#`d2R02Lnz==wJS!Y;~wszn6A_sai*clfP0NFM0|VKc3{p z2ttdu#RWBWX5VAB4?fqPlORtgMI`C&QiC+;ifS!QWp(~-ACmwFf{e$|jrsAFBNe(@i!wD}l3FE3nah2t z-ZEue`;@SZ3Cct*R-v^Qrq{aunjQyS-73JbHyC;Vd*It(j9=tP0S6v*EBs{w`c5}2s|Ji2Q;b~M zMBSL)SZs2ozozDMR0I6qW$Q~9^Vxhbrl6sc8d##A!>>Afl}nd%rc8WWKUuak!RTlO z2IN|EnjlicNlo#{ZIQjBNnF%I!4cdv1T zrt$@O@A9D8EnV&-lfh5tPFEh8o%yHIrA`Vy*lBS-&>w}zDdFlgxeMU|cu7CZ_1|O@ zc-WXr$zda&ajfliMT+o{yG)lycJ`P@dJc~y$zPjCdX`6iA9u8XEqcNpmRQfk9{wo! zNMA}4XgCi*{-DytgD0{_H$UECwnW)3mp_y8BP?nWCK>i)9wEXbE-tZZHJUHCxx@+^ zsVHAARY{uQnyad~X4EOTN`hrp_z4>au-|b?xnv9pG_J' . "\n"; // grab details from database - $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' ); + $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' ); $fields = $this->db->MetaColumns( $table ); $indexes = $this->db->MetaIndexes( $table ); @@ -1983,7 +1984,7 @@ class adoSchema { while( $row = $rs->FetchRow() ) { foreach( $row as $key => $val ) { - $row[$key] = htmlentities($row); + $row[$key] = htmlentities($val); } $schema .= ' ' . implode( '', $row ) . '' . "\n"; diff --git a/phpgwapi/inc/adodb/adodb.inc.php b/phpgwapi/inc/adodb/adodb.inc.php index 118cadb653..698069d55e 100644 --- a/phpgwapi/inc/adodb/adodb.inc.php +++ b/phpgwapi/inc/adodb/adodb.inc.php @@ -14,7 +14,7 @@ /** \mainpage - @version V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved. + @version V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. You can choose which license you prefer. @@ -26,8 +26,8 @@ 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. - + other databases via ODBC. + Latest Download at http://php.weblogs.com/adodb
Manual is at http://php.weblogs.com/adodb_manual @@ -87,7 +87,7 @@ define('ADODB_BAD_RS','

Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

'); // allow [ ] @ ` " and . in table names - define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)'); + define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)'); // prefetching used by oracle if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); @@ -172,7 +172,7 @@ /** * ADODB version as a string. */ - $ADODB_vers = 'V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.'; + $ADODB_vers = 'V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.'; /** * Determines whether recordset->RecordCount() is used. @@ -199,7 +199,7 @@ 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? ^-^ @@ -208,6 +208,7 @@ 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. +*/ } @@ -240,10 +241,10 @@ 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 $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's 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 $length = 'length'; /// string length ofperator var $random = 'rand()'; /// random function var $upperCase = 'upper'; /// uppercase function var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database @@ -252,7 +253,7 @@ 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 $charSet=false; /// character set to use - only for interbase, postgres and oci8 var $metaDatabasesSQL = ''; var $metaTablesSQL = ''; var $uniqueOrderBy = false; /// All order by columns have to be unique @@ -343,6 +344,11 @@ return array('description' => '', 'version' => ''); } + function IsConnected() + { + return !empty($this->_connectionID); + } + function _findvers($str) { if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; @@ -355,7 +361,7 @@ */ function outp($msg,$newline=true) { - global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP; + global $ADODB_FLUSH,$ADODB_OUTP; if (defined('ADODB_OUTP')) { $fn = ADODB_OUTP; @@ -369,7 +375,7 @@ if ($newline) $msg .= "
\n"; - if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) || !$newline) echo $msg; + if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg; else echo strip_tags($msg); @@ -405,17 +411,25 @@ $this->_isPersistentConnection = false; if ($forceNew) { - if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + if ($rez=$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 ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; } - $err = $this->ErrorMsg(); - if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; if ($fn = $this->raiseErrorFn) $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + + $this->_connectionID = false; if ($this->debug) ADOConnection::outp( $this->host.': '.$err); - return false; + return $ret; } function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) @@ -460,17 +474,22 @@ if ($argDatabaseName != "") $this->database = $argDatabaseName; $this->_isPersistentConnection = true; - 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'"; - } + if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; + } if ($fn = $this->raiseErrorFn) { $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); } + $this->_connectionID = false; if ($this->debug) ADOConnection::outp( $this->host.': '.$err); - return false; + return $ret; } // Format date column in sql string given an input format that understands Y M D @@ -499,7 +518,7 @@ { return $sql; } - + /** * Some databases, eg. mssql require a different function for preparing * stored procedures. So we cannot use Prepare(). @@ -732,6 +751,7 @@ } else if ($this->debug) ADOConnection::outp("Smart Commit occurred"); } else { + $this->_transOK = false; $this->RollbackTrans(); if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); } @@ -792,27 +812,37 @@ $sql = ''; $i = 0; foreach($arr as $v) { $sql .= $sqlarr[$i]; - // from Ron Baldwin + // from Ron Baldwin // Only quote string types - if (gettype($v) == 'string') + $typ = gettype($v); + if ($typ == 'string') $sql .= $this->qstr($v); + else if ($typ == 'double') + $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1 + else if ($typ == 'boolean') + $sql .= $v ? $this->true : $this->false; 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)); + if (isset($sqlarr[$i])) { + $sql .= $sqlarr[$i]; + if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); + } else if ($i != sizeof($sqlarr)) + ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql)); $ret =& $this->_Execute($sql); if (!$ret) return $ret; } } else { if ($array_2d) { - $stmt = $this->Prepare($sql); + if (is_string($sql)) + $stmt = $this->Prepare($sql); + else + $stmt = $sql; + foreach($inputarr as $arr) { $ret =& $this->_Execute($stmt,$arr); if (!$ret) return $ret; @@ -829,7 +859,7 @@ } - function& _Execute($sql,$inputarr=false) + function &_Execute($sql,$inputarr=false) { if ($this->debug) { @@ -850,8 +880,8 @@ if ($fn) { $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); } - - return false; + $false = false; + return $false; } if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead @@ -861,7 +891,7 @@ // return real recordset from select statement $rsclass = $this->rsPrefix.$this->databaseType; - $rs =& new $rsclass($this->_queryID,$this->fetchMode); + $rs = new $rsclass($this->_queryID,$this->fetchMode); $rs->connection = &$this; // Pablo suggestion $rs->Init(); if (is_array($sql)) $rs->sql = $sql[0]; @@ -885,7 +915,7 @@ return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); } - function DropSequence($seqname) + function DropSequence($seqname='adodbseq') { if (empty($this->_dropSeqSQL)) return false; return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); @@ -908,7 +938,12 @@ $getnext = sprintf($this->_genIDSQL,$seqname); $holdtransOK = $this->_transOK; - $rs = @$this->Execute($getnext); + + $save_handler = $this->raiseErrorFn; + $this->raiseErrorFn = ''; + @($rs = $this->Execute($getnext)); + $this->raiseErrorFn = $save_handler; + if (!$rs) { $this->_transOK = $holdtransOK; //if the status was ok before reset $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); @@ -940,7 +975,7 @@ /** - * Portable Insert ID. Pablo Roca + * Portable Insert ID. Pablo Roca * * @return the last inserted ID. All databases support this. But aware possible * problems in multiuser environments. Heavy test this before deploying. @@ -977,7 +1012,8 @@ */ function ErrorMsg() { - return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + else return ''; } @@ -1147,8 +1183,10 @@ */ function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) { - if (! $rs) return false; - + if (! $rs) { + $false = false; + 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 ? @@ -1170,11 +1208,12 @@ $arrayClass = $this->arrayClass; - $rs2 =& new $arrayClass(); + $rs2 = new $arrayClass(); $rs2->connection = &$this; $rs2->sql = $rs->sql; $rs2->dataProvider = $this->dataProvider; $rs2->InitArrayFields($arr,$flds); + $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; return $rs2; } @@ -1190,8 +1229,10 @@ function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) { $rs =& $this->Execute($sql, $inputarr); - if (!$rs) return false; - + if (!$rs) { + $false = false; + return $false; + } $arr =& $rs->GetAssoc($force_array,$first2cols); return $arr; } @@ -1203,8 +1244,10 @@ $force_array = $inputarr; } $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); - if (!$rs) return false; - + if (!$rs) { + $false = false; + return $false; + } $arr =& $rs->GetAssoc($force_array,$first2cols); return $arr; } @@ -1224,7 +1267,7 @@ $ret = false; $rs = &$this->Execute($sql,$inputarr); - if ($rs) { + if ($rs) { if (!$rs->EOF) $ret = reset($rs->fields); $rs->Close(); } @@ -1316,7 +1359,10 @@ $ADODB_COUNTRECS = $savec; if (!$rs) if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; + else { + $false = false; + return $false; + } $arr =& $rs->GetArray(); $rs->Close(); return $arr; @@ -1338,8 +1384,10 @@ if (!$rs) if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - + else { + $false = false; + return $false; + } $arr =& $rs->GetArray(); $rs->Close(); return $arr; @@ -1369,7 +1417,8 @@ return $arr; } - return false; + $false = false; + return $false; } function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) @@ -1381,7 +1430,8 @@ $rs->Close(); return $arr; } - return false; + $false = false; + return $false; } /** @@ -1457,7 +1507,8 @@ 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'; + //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f'; + $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; } if ($this->debug) { @@ -1529,21 +1580,28 @@ */ function &CacheExecute($secs2cache,$sql=false,$inputarr=false) { + + if (!is_numeric($secs2cache)) { $inputarr = $sql; $sql = $secs2cache; $secs2cache = $this->cacheSecs; } + + if (is_array($sql)) { + $sqlparam = $sql; + $sql = $sql[0]; + } else + $sqlparam = $sql; + 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); + $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass); $this->numCacheHits += 1; } else { $err='Timeout 1'; @@ -1558,7 +1616,9 @@ } if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); } - $rs = &$this->Execute($sql,$inputarr); + + $rs = &$this->Execute($sqlparam,$inputarr); + if ($rs) { $eof = $rs->EOF; $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately @@ -1589,9 +1649,8 @@ // 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']); + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); $ttl = $rs->timeCreated + $secs2cache - time(); $s = is_array($sql) ? $sql[0] : $sql; if ($inBrowser) $s = ''.htmlspecialchars($s).''; @@ -1603,6 +1662,46 @@ } + /* + Similar to PEAR DB's autoExecute(), except that + $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE + If $mode == 'UPDATE', then $where is compulsory as a safety measure. + + $forceUpdate means that even if the data has not changed, perform update. + */ + function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) + { + $sql = 'SELECT * FROM '.$table; + if ($where!==FALSE) $sql .= ' WHERE '.$where; + else if ($mode == 'UPDATE') { + ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause'); + return false; + } + + $rs =& $this->SelectLimit($sql,1); + if (!$rs) return false; // table does not exist + $rs->tableName = $table; + + switch((string) $mode) { + case 'UPDATE': + case '2': + $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq); + break; + case 'INSERT': + case '1': + $sql = $this->GetInsertSQL($rs, $fields_values, $magicq); + break; + default: + ADOConnection::outp("AutoExecute: Unknown mode=$mode"); + return false; + } + $ret = false; + if ($sql) $ret = $this->Execute($sql); + if ($ret) $ret = true; + return $ret; + } + + /** * Generates an Update Query based on an existing recordset. * $arrFields is an associative array of fields with the value @@ -1631,6 +1730,8 @@ return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force); } + + /** * Generates an Insert Query based on an existing recordset. @@ -1745,6 +1846,19 @@ return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); } + // not the fastest implementation - quick and dirty - jlim + // for best performance, use the actual $rs->MetaType(). + function MetaType($t,$len=-1,$fieldobj=false) + { + + if (empty($this->_metars)) { + $rsclass = $this->rsPrefix.$this->databaseType; + $this->_metars =& new $rsclass(false,$this->fetchMode); + } + + return $this->_metars->MetaType($t,$len,$fieldobj); + } + /** * Change the SQL connection locale to a specified locale. @@ -1753,24 +1867,34 @@ function SetDateLocale($locale = 'En') { $this->locale = $locale; - switch ($locale) + switch (strtoupper($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"; + case 'EN': + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; break; - case 'Ge': - $this->fmtDate="d.m.Y"; - $this->fmtTimeStamp = "d.m.Y H:i:s"; + case 'US': + $this->fmtDate = "'m-d-Y'"; + $this->fmtTimeStamp = "'m-d-Y H:i:s'"; + break; + + case 'NL': + case 'FR': + case 'RO': + case 'IT': + $this->fmtDate="'d-m-Y'"; + $this->fmtTimeStamp = "'d-m-Y H:i:s'"; + break; + + case 'GE': + $this->fmtDate="'d.m.Y'"; + $this->fmtTimeStamp = "'d.m.Y H:i:s'"; + break; + + default: + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; break; } } @@ -1779,14 +1903,11 @@ /** * Close Connection */ - function Close() + function Close() { - return $this->_close(); - - // "Simon Lee" reports that persistent connections need - // to be closed too! - //if ($this->_isPersistentConnection != true) return $this->_close(); - //else return true; + $rez = $this->_close(); + $this->_connectionID = false; + return $rez; } /** @@ -1857,10 +1978,12 @@ { global $ADODB_FETCH_MODE; - if ($mask) return false; + $false = false; + 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; @@ -1870,7 +1993,7 @@ if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; + if ($rs === false) return $false; $arr =& $rs->GetArray(); $arr2 = array(); @@ -1891,7 +2014,7 @@ $rs->Close(); return $arr2; } - return false; + return $false; } @@ -1917,6 +2040,8 @@ { global $ADODB_FETCH_MODE; + $false = false; + if (!empty($this->metaColumnsSQL)) { $schema = false; @@ -1928,11 +2053,11 @@ $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; + if ($rs === false || $rs->EOF) return $false; $retarr = array(); while (!$rs->EOF) { //print_r($rs->fields); - $fld =& new ADOFieldObject(); + $fld = new ADOFieldObject(); $fld->name = $rs->fields[0]; $fld->type = $rs->fields[1]; if (isset($rs->fields[3]) && $rs->fields[3]) { @@ -1949,19 +2074,31 @@ $rs->Close(); return $retarr; } - return false; + return $false; } /** * List indexes on a table as an array. - * @param table table name to query - * @param primary include primary keys. + * @param table table name to query + * @param primary true to only show primary keys. Not actually used for most databases * - * @return array of indexes on current table. + * @return array of indexes on current table. Each element represents an index, and is itself an associative array. + + Array ( + [name_of_index] => Array + ( + [unique] => true or false + [columns] => Array + ( + [0] => firstname + [1] => lastname + ) + ) */ function &MetaIndexes($table, $primary = false, $owner = false) { - return FALSE; + $false = false; + return $false; } /** @@ -1973,8 +2110,10 @@ function &MetaColumnNames($table, $numIndexes=false) { $objarr =& $this->MetaColumns($table); - if (!is_array($objarr)) return false; - + if (!is_array($objarr)) { + $false = false; + return $false; + } $arr = array(); if ($numIndexes) { $i = 0; @@ -2053,6 +2192,12 @@ */ function UnixDate($v) { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + if (is_numeric($v) && strlen($v) !== 8) return $v; if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", ($v), $rr)) return false; @@ -2071,6 +2216,12 @@ */ function UnixTimeStamp($v) { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr)) return false; @@ -2116,6 +2267,7 @@ */ function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false) { + if (!isset($v)) return $this->emptyTimeStamp; # strlen(14) allows YYYYMMDDHHMMSS format if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v); $tt = $this->UnixTimeStamp($v); @@ -2125,6 +2277,11 @@ return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); } + function escape($s,$magic_quotes=false) + { + return $this->addq($s,$magic_quotes); + } + /** * Quotes a string, without prefixing nor appending quotes. */ @@ -2394,6 +2551,8 @@ $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 @@ -2403,12 +2562,21 @@ */ 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, + return $this->GetMenu($name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + /* + Grouped Menu + */ + function GetMenu3($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_gp($this, $name,$defstr,$blank1stItem,$multiple, $size, $selectAttr,false); } - /** * return recordset as a 2-dimensional array. @@ -2510,7 +2678,8 @@ $cols = $this->_numOfFields; if ($cols < 2) { - return false; + $false = false; + return $false; } $numIndex = isset($this->fields[0]); $results = array(); @@ -2624,14 +2793,7 @@ */ function UnixDate($v) { - if (is_numeric($v) && strlen($v) !== 8) return $v; - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; - - if ($rr[1] <= TIMESTAMP_FIRST_YEAR || $rr[1] > 10000) return 0; - - // h-m-s-MM-DD-YY - return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + return ADOConnection::UnixDate($v); } @@ -2642,15 +2804,7 @@ */ 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]); + return ADOConnection::UnixTimeStamp($v); } @@ -2688,7 +2842,10 @@ */ function &FetchRow() { - if ($this->EOF) return false; + if ($this->EOF) { + $false = false; + return $false; + } $arr = $this->fields; $this->_currentRow++; if (!$this->_fetch()) $this->EOF = true; @@ -2832,7 +2989,7 @@ { $this->bind = array(); for ($i=0; $i < $this->_numOfFields; $i++) { - $o =& $this->FetchField($i); + $o = $this->FetchField($i); if ($upper === 2) $this->bind[$o->name] = $i; else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; } @@ -2994,7 +3151,7 @@ function &FetchObject($isupper=true) { if (empty($this->_obj)) { - $this->_obj =& new ADOFetchObj(); + $this->_obj = new ADOFetchObj(); $this->_names = array(); for ($i=0; $i <$this->_numOfFields; $i++) { $f = $this->FetchField($i); @@ -3002,7 +3159,9 @@ } } $i = 0; - $o = &$this->_obj; + if (PHP_VERSION >= 5) $o = clone($this->_obj); + else $o = $this->_obj; + for ($i=0; $i <$this->_numOfFields; $i++) { $name = $this->_names[$i]; if ($isupper) $n = strtoupper($name); @@ -3024,7 +3183,7 @@ */ function &FetchNextObj() { - $o = $this->FetchNextObject(false); + $o =& $this->FetchNextObject(false); return $o; } @@ -3134,6 +3293,9 @@ 'INT IDENTITY' => 'R', ## 'INT' => 'I', + 'INT2' => 'I', + 'INT4' => 'I', + 'INT8' => 'I', 'INTEGER' => 'I', 'INTEGER UNSIGNED' => 'I', 'SHORT' => 'I', @@ -3174,7 +3336,7 @@ $tmap = false; $t = strtoupper($t); - $tmap = @$typeMap[$t]; + $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N'; switch ($tmap) { case 'C': @@ -3349,7 +3511,9 @@ /* Use associative array to get fields array */ function Fields($colname) { - if ($this->fetchMode & ADODB_FETCH_ASSOC) { + $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode; + + if ($mode & ADODB_FETCH_ASSOC) { if (!isset($this->fields[$colname])) $colname = strtolower($colname); return $this->fields[$colname]; } @@ -3451,19 +3615,25 @@ if (!$dbType) return false; $db = strtolower($dbType); switch ($db) { + case 'ado': + if (PHP_VERSION >= 5) $db = 'ado5'; + $class = 'ado'; + break; case 'ifx': - case 'maxsql': $db = 'mysqlt'; break; + case 'maxsql': $class = $db = 'mysqlt'; break; case 'postgres': - case 'pgsql': $db = 'postgres7'; break; + case 'postgres8': + case 'pgsql': $class = $db = 'postgres7'; break; + default: + $class = $db; break; } - @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php"); - $ADODB_LASTDB = $db; - $ok = class_exists("ADODB_" . $db); - if ($ok) return $db; - - print_r(get_declared_classes()); $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; + @include_once($file); + $ADODB_LASTDB = $class; + if (class_exists("ADODB_" . $class)) return $class; + + //ADOConnection::outp(adodb_pr(get_declared_classes(),true)); if (!file_exists($file)) ADOConnection::outp("Missing file: $file"); else ADOConnection::outp("Syntax error in file: $file"); return false; @@ -3492,23 +3662,24 @@ if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; - + $false = false; if (strpos($db,'://')) { $origdsn = $db; $dsna = @parse_url($db); + if (!$dsna) { // special handling of oracle, which might not have host $db = str_replace('@/','@adodb-fakehost/',$db); $dsna = parse_url($db); - if (!$dsna) return false; + if (!$dsna) return $false; $dsna['host'] = ''; } $db = @$dsna['scheme']; - if (!$db) return false; + if (!$db) return $false; $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : ''; $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : ''; - $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; + $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial / if (isset($dsna['query'])) { $opt1 = explode('&',$dsna['query']); @@ -3549,40 +3720,44 @@ } else ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); - return false; + return $false; } $cls = 'ADODB_'.$db; if (!class_exists($cls)) { adodb_backtrace(); - return false; + return $false; } - $obj =& new $cls(); + $obj = new $cls(); } # constructor should not fail if ($obj) { if ($errorfn) $obj->raiseErrorFn = $errorfn; if (isset($dsna)) { - + if (isset($dsna['port'])) $obj->port = $dsna['port']; foreach($opt as $k => $v) { switch(strtolower($k)) { case 'persist': case 'persistent': $persist = $v; break; case 'debug': $obj->debug = (integer) $v; break; #ibase + case 'role': $obj->role = $v; break; case 'dialect': $obj->dialect = (integer) $v; break; - case 'charset': $obj->charset = $v; break; + case 'charset': $obj->charset = $v; $obj->charSet=$v; break; case 'buffers': $obj->buffers = $v; break; case 'fetchmode': $obj->SetFetchMode($v); break; #ado case 'charpage': $obj->charPage = $v; break; #mysql, mysqli case 'clientflags': $obj->clientFlags = $v; break; - #mysqli + #mysql, mysqli, postgres case 'port': $obj->port = $v; break; + #mysqli case 'socket': $obj->socket = $v; break; + #oci8 + case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break; } } if (empty($persist)) @@ -3590,7 +3765,7 @@ else $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - if (!$ok) return false; + if (!$ok) return $false; } } return $obj; @@ -3598,62 +3773,61 @@ - // $perf == true means called by NewPerfMonitor() + // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary 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; - case 'sapdb': - break; - default: - $drivername = 'generic'; - break; - } + switch ($provider) { + case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); + case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); + case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4); + case 'native': break; + default: + return $provider; } + switch($drivername) { + case 'firebird15': $drivername = 'firebird'; break; + case 'oracle': $drivername = 'oci8'; break; + case 'access': if ($perf) $drivername = ''; break; + case 'db2' : break; + case 'sapdb' : break; + default: + $drivername = 'generic'; + break; + } return $drivername; } function &NewPerfMonitor(&$conn) { + $false = false; $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); - if (!$drivername || $drivername == 'generic') return false; + 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); + if (!class_exists($class)) return $false; + $perf = new $class($conn); return $perf; } - function &NewDataDictionary(&$conn) + function &NewDataDictionary(&$conn,$drivername=false) { - $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); - + $false = false; + if (!$drivername) $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; + return $false; } include_once($path); $class = "ADODB2_$drivername"; - $dict =& new $class(); + $dict = new $class(); $dict->dataProvider = $conn->dataProvider; $dict->connection = &$conn; $dict->upperName = strtoupper($drivername); @@ -3669,12 +3843,20 @@ /* Perform a print_r, with pre tags for better formatting. */ - function adodb_pr($var) + function adodb_pr($var,$as_string=false) { + if ($as_string) ob_start(); + if (isset($_SERVER['HTTP_USER_AGENT'])) { echo "
\n";print_r($var);echo "
\n"; } else print_r($var); + + if ($as_string) { + $s = ob_get_contents(); + ob_end_clean(); + return $s; + } } /* diff --git a/phpgwapi/inc/adodb/datadict/datadict-access.inc.php b/phpgwapi/inc/adodb/datadict/datadict-access.inc.php index d718a94e06..f298a6febf 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-access.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-access.inc.php @@ -1,7 +1,7 @@ MetaColumns($tablename); + if ( empty($cols)) { + return $this->CreateTableSQL($tablename, $flds, $tableoptions); + } + + // already exists, alter table instead + list($lines,$pkey) = $this->_GenFields($flds); + $alter = 'ALTER TABLE ' . $this->TableName($tablename); + $sql = array(); + + foreach ( $lines as $id => $v ) { + if ( isset($cols[$id]) && is_object($cols[$id]) ) { + /** + If the first field of $v is the fieldname, and + the second is the field type/size, we assume its an + attempt to modify the column size, so check that it is allowed + $v can have an indeterminate number of blanks between the + fields, so account for that too + */ + $vargs = explode(' ' , $v); + // assume that $vargs[0] is the field name. + $i=0; + // Find the next non-blank value; + for ($i=1;$ialterCol . ' ' . $v; + } else { + $sql[] = $alter . $this->addCol . ' ' . $v; + } + } + + return $sql; + } + } diff --git a/phpgwapi/inc/adodb/datadict/datadict-firebird.inc.php b/phpgwapi/inc/adodb/datadict/datadict-firebird.inc.php index 19fdede5f6..2f7dc7909a 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-firebird.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-firebird.inc.php @@ -1,7 +1,7 @@ typeXL : 'TEXT'; + case 'X': return (isset($this)) ? $this->typeX : 'TEXT'; ## could be varchar(8000), but we want compat with oracle case 'C2': return 'NVARCHAR'; case 'X2': return 'NTEXT'; @@ -60,6 +64,7 @@ class ADODB2_mssql extends ADODB_DataDict { case 'T': return 'DATETIME'; case 'L': return 'BIT'; + case 'R': case 'I': return 'INT'; case 'I1': return 'TINYINT'; case 'I2': return 'SMALLINT'; @@ -83,7 +88,7 @@ class ADODB2_mssql extends ADODB_DataDict { foreach($lines as $v) { $f[] = "\n $v"; } - $s .= implode(',',$f); + $s .= implode(', ',$f); $sql[] = $s; return $sql; } @@ -110,9 +115,9 @@ class ADODB2_mssql extends ADODB_DataDict { $f = array(); $s = 'ALTER TABLE ' . $tabname; foreach($flds as $v) { - $f[] = "\n$this->dropCol $v"; + $f[] = "\n$this->dropCol ".$this->NameQuote($v); } - $s .= implode(',',$f); + $s .= implode(', ',$f); $sql[] = $s; return $sql; } @@ -241,12 +246,9 @@ CREATE TABLE case 'BIGINT': return $ftype; } - if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) { - $ftype .= "(".$fsize; - if (strlen($fprec)) $ftype .= ",".$fprec; - $ftype .= ')'; - } - return $ftype; + if ($ty == 'T') return $ftype; + return parent::_GetSize($ftype, $ty, $fsize, $fprec); + } } -?> +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/datadict/datadict-mysql.inc.php b/phpgwapi/inc/adodb/datadict/datadict-mysql.inc.php index f17a0376b3..5134bae2e6 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-mysql.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-mysql.inc.php @@ -1,7 +1,7 @@ typeX; + case 'XL': return $this->typeXL; case 'C2': return 'NVARCHAR'; case 'X2': return 'NVARCHAR(2000)'; @@ -113,7 +116,7 @@ class ADODB2_oci8 extends ADODB_DataDict { $f[] = "\n $v"; } - $s .= implode(',',$f).')'; + $s .= implode(', ',$f).')'; $sql[] = $s; return $sql; } @@ -126,7 +129,7 @@ class ADODB2_oci8 extends ADODB_DataDict { foreach($lines as $v) { $f[] = "\n $v"; } - $s .= implode(',',$f).')'; + $s .= implode(', ',$f).')'; $sql[] = $s; return $sql; } @@ -134,9 +137,11 @@ class ADODB2_oci8 extends ADODB_DataDict { function DropColumnSQL($tabname, $flds) { if (!is_array($flds)) $flds = explode(',',$flds); + foreach ($flds as $k => $v) $flds[$k] = $this->NameQuote($v); + $sql = array(); $s = "ALTER TABLE $tabname DROP("; - $s .= implode(',',$flds).') CASCADE COSTRAINTS'; + $s .= implode(', ',$flds).') CASCADE CONSTRAINTS'; $sql[] = $s; return $sql; } diff --git a/phpgwapi/inc/adodb/datadict/datadict-postgres.inc.php b/phpgwapi/inc/adodb/datadict/datadict-postgres.inc.php index 8c1bd3544a..223821f07b 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-postgres.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-postgres.inc.php @@ -1,7 +1,7 @@ serverInfo['version']; + $has_drop_column = 7.3 <= (float) @$this->serverInfo['version']; if (!$has_drop_column && !$tableflds) { if ($this->debug) ADOConnection::outp("DropColumnSQL needs complete table-definiton for PostgreSQL < 7.3"); - return array(); - } + return array(); + } if ($has_drop_column) { return ADODB_DataDict::DropColumnSQL($tabname, $flds); } @@ -215,7 +214,7 @@ class ADODB2_postgres extends ADODB_DataDict { // we need to explicit convert varchar to a number to be able to do an AlterColumn of a char column to a nummeric one if (preg_match('/'.$fld->name.' (I|I2|I4|I8|N|F)/i',$tableflds,$matches) && in_array($fld->type,array('varchar','char','text','bytea'))) { - $copyflds[] = "to_number($fld->name,'S9999999999999D99')"; + $copyflds[] = "to_number($fld->name,'S99D99')"; } else { $copyflds[] = $fld->name; } @@ -227,7 +226,7 @@ class ADODB2_postgres extends ADODB_DataDict { } } } - $copyflds = implode(',',$copyflds); + $copyflds = implode(', ',$copyflds); $tempname = $tabname.'_tmp'; $aSql[] = 'BEGIN'; // we use a transaction, to make sure not to loose the content of the table @@ -261,7 +260,7 @@ class ADODB2_postgres extends ADODB_DataDict { return $sql; } - + // return string must begin with space function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint) { @@ -357,4 +356,4 @@ CREATE [ UNIQUE ] INDEX index_name ON table return $sql; } } -?> +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/datadict/datadict-sapdb.inc.php b/phpgwapi/inc/adodb/datadict/datadict-sapdb.inc.php index 2d7b177890..de6fe35bb4 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-sapdb.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-sapdb.inc.php @@ -1,7 +1,7 @@ TableName ($tabname); $sql = array(); list($lines,$pkey) = $this->_GenFields($flds); - return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(',',$lines) . ')' ); + return array( 'ALTER TABLE ' . $tabname . ' ADD (' . implode(', ',$lines) . ')' ); } function AlterColumnSQL($tabname, $flds) @@ -104,7 +104,7 @@ class ADODB2_sapdb extends ADODB_DataDict { $tabname = $this->TableName ($tabname); $sql = array(); list($lines,$pkey) = $this->_GenFields($flds); - return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(',',$lines) . ')' ); + return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' ); } function DropColumnSQL($tabname, $flds) @@ -114,7 +114,7 @@ class ADODB2_sapdb extends ADODB_DataDict { foreach($flds as $k => $v) { $flds[$k] = $this->NameQuote($v); } - return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(',',$flds) . ')' ); + return array( 'ALTER TABLE ' . $tabname . ' DROP (' . implode(', ',$flds) . ')' ); } } diff --git a/phpgwapi/inc/adodb/datadict/datadict-sybase.inc.php b/phpgwapi/inc/adodb/datadict/datadict-sybase.inc.php index fac19ef895..e365ea44fd 100644 --- a/phpgwapi/inc/adodb/datadict/datadict-sybase.inc.php +++ b/phpgwapi/inc/adodb/datadict/datadict-sybase.inc.php @@ -1,7 +1,7 @@ TableName ($tabname); + $tabname = $this->TableName($tabname); if (!is_array($flds)) $flds = explode(',',$flds); $f = array(); $s = "ALTER TABLE $tabname"; foreach($flds as $v) { - $f[] = "\n$this->dropCol $v"; + $f[] = "\n$this->dropCol ".$this->NameQuote($v); } - $s .= implode(',',$f); + $s .= implode(', ',$f); $sql[] = $s; return $sql; } diff --git a/phpgwapi/inc/adodb/docs/docs-adodb.htm b/phpgwapi/inc/adodb/docs/docs-adodb.htm index 24e52debb6..b4b4f000c0 100644 --- a/phpgwapi/inc/adodb/docs/docs-adodb.htm +++ b/phpgwapi/inc/adodb/docs/docs-adodb.htm @@ -1,6 +1,6 @@ - - -ADODB Manual + +ADODB Manual + @@ -11,32 +11,29 @@ pre { font-size: 12px; border: 1px solid #ddd; } - - - + +

ADOdb Library for PHP

-

V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com)

+

V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com)

This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.

- -
Kindly note that the ADOdb home page has moved to http://adodb.sourceforge.net/ because of the persistent - unreliability of http://php.weblogs.com. Please change your links!
-

Useful ADOdb links: Download   Other Docs -

Introduction
+

Useful ADOdb links: Download   Other Docs + +

Introduction
Unique Features
How People are using ADOdb
Feature Requests and Bug Reports
Installation
Minimum Install
Initializing Code and Connectioning to Databases
-
  Data Source Name (DSN) Support   Connection Examples
+
  Data Source Name (DSN) Support   Connection Examples
High Speed ADOdb - tuning tips
Hacking and Modifying ADOdb Safely
PHP5 Features

- foreach iterators exceptions
+ foreach iterators exceptions
Supported Databases
Tutorials
Example 1: Select
@@ -56,22 +53,22 @@ pre { Data Source Names
Caching
Pivot Tables -

REFERENCE -

Variables: $ADODB_COUNTRECS -$ADODB_ANSI_PADDING_OFF - $ADODB_CACHE_DIR
-         $ADODB_FORCE_TYPE - $ADODB_FETCH_MODE - $ADODB_LANG
- Constants:
ADODB_ASSOC_CASE +

REFERENCE +

Variables: $ADODB_COUNTRECS +$ADODB_ANSI_PADDING_OFF + $ADODB_CACHE_DIR
+         $ADODB_FORCE_TYPE + $ADODB_FETCH_MODE + $ADODB_LANG
+ Constants:
ADODB_ASSOC_CASE
ADOConnection
Connections: Connect PConnect - NConnect
+ NConnect IsConnected
Executing SQL: Execute CacheExecute - SelectLimit CacheSelectLimit - Param Prepare PrepareSP - InParameter OutParameter + SelectLimit CacheSelectLimit + Param Prepare PrepareSP + InParameter OutParameter AutoExecute
              GetOne CacheGetOne GetRow CacheGetRow @@ -82,9 +79,8 @@ pre { (oci8 only)
Generates SQL strings: GetUpdateSQL GetInsertSQL Concat IfNull length random substr - qstr Param - OffsetDate SQLDate - DBDate DBTimeStamp + qstr Param OffsetDate SQLDate + DBDate DBTimeStamp
Blobs: UpdateBlob UpdateClob UpdateBlobFile BlobEncode @@ -100,8 +96,8 @@ pre { Dates: DBDate DBTimeStamp UnixDate UnixTimeStamp OffsetDate SQLDate
- Row Management: Affected_Rows Insert_ID RowLock - GenID CreateSequence DropSequence + Row Management: Affected_Rows Insert_ID RowLock + GenID CreateSequence DropSequence
Error Handling: ErrorMsg ErrorNo MetaError MetaErrorMsg
@@ -134,7 +130,8 @@ pre { NextRecordSet
Field Info:FieldCount FetchField MetaType
- Cleanup: Close
+ Cleanup: Close
+

rs2html  example
Differences between ADOdb and ADO
Database Driver Guide
@@ -151,8 +148,8 @@ pre { will contribute drivers to support other databases.

PHP4 supports session variables. You can store your session information using ADOdb for true portability and scalability. See adodb-session.php for more information.

-

Also read http://php.weblogs.com/portable_sql - (also available as tips_portable_sql.htm in the release) for tips on writing +

Also read tips_portable_sql.htm + for tips on writing portable SQL.

Unique Features of ADOdb

    @@ -166,64 +163,66 @@ pre { such as CHAR, TEXT and STRING are equivalent in different databases.
  • Easy to port because all the database dependant code are stored in stub functions. You do not need to port the core logic of the classes.
  • -
  • Portable table and index creation with the datadict classes. -
  • Database performance monitoring and SQL tuning with the performance monitoring classes. -
  • Database-backed sessions with the session management classes. Supports session expiry notification. -
+
  • Portable table and index creation with the datadict classes. +
  • Database performance monitoring and SQL tuning with the performance monitoring classes. +
  • Database-backed sessions with the session management classes. Supports session expiry notification. +
  • How People are using ADOdb

    Here are some examples of how people are using ADOdb (for a much longer list, -visit http://php.weblogs.com/adodb-cool-applications): +visit adodb-cool-apps):
      -
    • PhpLens is a commercial data grid component that allows both cool Web designers and serious unshaved programmers to develop and maintain databases on the Web easily. Developed by the author of ADOdb.

      +

    • PhpLens is a commercial data grid +component that allows both cool Web designers and serious unshaved +programmers to develop and maintain databases on the Web easily. +Developed by the author of ADOdb.

      -

    • PHAkt: PHP Extension for DreamWeaver Ultradev allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.

      +

    • PHAkt: PHP Extension for DreamWeaver Ultradev allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.

      -

    • Analysis Console for Intrusion Databases (ACID): PHP-based analysis engine to search and process a database of security incidents generated by security-related software such as IDSes and firewalls (e.g. Snort, ipchains). By Roman Danyliw.

      +

    • Analysis Console for Intrusion Databases +(ACID): PHP-based analysis engine to search and process a database of +security incidents generated by security-related software such as IDSes +and firewalls (e.g. Snort, ipchains). By Roman Danyliw.

      -

    • PostNuke is a very popular free content management - system and weblog system. It offers full CSS support, HTML 4.01 transitional compliance throughout, an advanced blocks system, and is fully multi-lingual enabled.

      +

    • PostNuke is a very +popular free content management system and weblog system. It offers +full CSS support, HTML 4.01 transitional compliance throughout, an +advanced blocks system, and is fully multi-lingual enabled.

      -

    • EasyPublish CMS is another free content management system for managing information and integrated modules on your internet, intranet- and extranet-sites. From Norway.

      +

    • EasyPublish CMS +is another free content management system for managing information and +integrated modules on your internet, intranet- and extranet-sites. From +Norway.

      -

    • NOLA is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska. -

    +

  • NOLA is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska. +
  • -

    Feature Requests and Bug Reports

    +

    Feature Requests and Bug Reports

    Feature requests and bug reports can be emailed to jlim#natsoft.com.my or posted to the ADOdb Help forums at http://phplens.com/lens/lensforum/topics.php?id=4.

    Installation Guide

    Make sure you are running PHP 4.0.5 or later. Unpack all the files into a directory accessible by your webserver.

    To test, try modifying some of the tutorial examples. Make sure you customize - the connection settings correctly. You can debug using $db->debug = true as shown below:

    -
    <?php
    -	include('adodb/adodb.inc.php');
    -	$db = ADONewConnection($dbdriver); # eg 'mysql' or 'postgres'
    -	$db->debug = true;
    -	$db->Connect($server, $user, $password, $database);
    -	$rs = $db->Execute('select * from some_small_table');
    -	print "<pre>";
    -	print_r($rs->GetRows());
    -	print "</pre>";
    -?>
    + the connection settings correctly. You can debug using $db->debug = true as shown below:

    +
    <?php
    include('adodb/adodb.inc.php');
    $db = ADONewConnection($dbdriver); # eg 'mysql' or 'postgres'
    $db->debug = true;
    $db->Connect($server, $user, $password, $database);
    $rs = $db->Execute('select * from some_small_table');
    print "<pre>";
    print_r($rs->GetRows());
    print "</pre>";
    ?>
    -

    Minimum Install

    +

    Minimum Install

    For developers who want to release a minimal install of ADOdb, you will need: -

      +

      • adodb.inc.php -
      • adodb-lib.inc.php -
      • adodb-time.inc.php -
      • drivers/adodb-$database.inc.php -
      • license.txt (for legal reasons) -
      • adodb-php4.inc.php -
      • adodb-iterator.inc.php -
      +
    • adodb-lib.inc.php +
    • adodb-time.inc.php +
    • drivers/adodb-$database.inc.php +
    • license.txt (for legal reasons) +
    • adodb-php4.inc.php +
    • adodb-iterator.inc.php +
    Optional:
    • adodb-error.inc.php and lang/adodb-$lang.inc.php (if you use MetaError()) -
    • adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc) -
    • adodb-exceptions.inc.php and adodb-errorhandler.inc.php (if you use adodb error handler or php5 exceptions). -
    +
  • adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc) +
  • adodb-exceptions.inc.php and adodb-errorhandler.inc.php (if you use adodb error handler or php5 exceptions). +
  • Code Initialization Examples

    When running ADOdb, at least two files are loaded. First is adodb/adodb.inc.php, @@ -231,129 +230,119 @@ Optional: to a particular database is in the adodb/driver/adodb-????.inc.php file.

    For example, to connect to a mysql database:

    -
    -include('/path/to/set/here/adodb.inc.php');
    -$conn = &ADONewConnection('mysql');
    -
    +
    include('/path/to/set/here/adodb.inc.php');
    $conn = &ADONewConnection('mysql');

    Whenever you need to connect to a database, you create a Connection object using the ADONewConnection($driver) function. NewADOConnection($driver) is an alternative name for the same function.

    -

    At this point, you are not connected to the database (no longer true if you pass in a dsn). You will first need to decide +

    At this point, you are not connected to the database (no longer true if you pass in a dsn). You will first need to decide whether to use persistent or non-persistent connections. The advantage of persistent connections is that they are faster, as the database connection is never closed (even when you call Close()). Non-persistent connections take up much fewer resources though, reducing the risk of your database and your web-server becoming overloaded. -

    For persistent connections, +

    For persistent connections, use $conn->PConnect(), or $conn->Connect() for non-persistent connections. Some database drivers also support NConnect(), which forces the creation of a new connection. - -

    Connection Gotcha: If you create two connections, but both use the same userid and password, + +

    Connection Gotcha: If you create two connections, but both use the same userid and password, PHP will share the same connection. This can cause problems if the connections are meant to different databases. The solution is to always use different userid's for different databases, or use NConnect(). - -

    Data Source Name (DSN) Support

    + +

    Data Source Name (DSN) Support

    Since ADOdb 4.51, you can connect to a database by passing a dsn to NewADOConnection() (or ADONewConnection, which is the same function). The dsn format is: -

    -	$driver://$username:$password@hostname/$database?options[=value]
    -

    +

    	$driver://$username:$password@hostname/$database?options[=value]

    NewADOConnection() calls Connect() or PConnect() internally for you. If the connection fails, false is returned. -

    -	# non-persistent connection
    +

    	# non-persistent connection
     	$dsn = 'mysql://root:pwd@localhost/mydb'; 
     	$db = NewADOConnection($dsn);
     	if (!$db) die("Connection failed");   
     	
    -	# no need to call connect/pconnect!
    -	$arr = $db->GetArray("select * from table");
    +	# no need to call connect/pconnect!
    +	$arr = $db->GetArray("select * from table");
     	
    -	# persistent connection
    +	# persistent connection
     	$dsn2 = 'mysql://root:pwd@localhost/mydb?persist'; 
     

    If you have special characters such as /:? in your dsn, then you need to rawurlencode them first: -

    -	$pwd = rawurlencode($pwd);
    -	$dsn = "mysql://root:$pwd@localhost/mydb";
    -
    +

    	$pwd = rawurlencode($pwd);
    $dsn = "mysql://root:$pwd@localhost/mydb";

    Legal options are: -

    -
    For all drivers +

    +
    For all drivers 'persist', 'persistent', 'debug', 'fetchmode' -
    Interbase/Firebird - - 'dialect', - 'charset', - 'buffers' -
    M'soft ADO +
    Interbase/Firebird + + 'dialect','charset','buffers','role' +
    M'soft ADO 'charpage' -
    MySQL +
    MySQL 'clientflags' -
    MySQLi +
    MySQLi 'port', 'socket', 'clientflags' -
    -

    +

    Oci8 + 'nls_date_format','charset' +
    +

    For all drivers, when the options persist or persistent are set, a persistent connection is forced. -The debug option enables debugging. The fetchmode calls SetFetchMode(). +The debug option enables debugging. The fetchmode calls SetFetchMode(). If no value is defined for an option, then the value is set to 1. -

    +

    ADOdb DSN's are compatible with version 1.0 of PEAR DB's DSN format. - -

    Examples of Connecting to Databases

    -

    MySQL and Most Other Database Drivers

    -

    MySQL connections are very straightforward, and the parameters are identical - to mysql_connect:

    -
    -	$conn = &ADONewConnection('mysql'); 
    -	$conn->PConnect('localhost','userid','password','database');
    -	
    -	# or dsn 
    +
    +

    Examples of Connecting to Databases

    +

    MySQL and Most Other Database Drivers

    +

    MySQL connections are very straightforward, and the parameters are identical + to mysql_connect:

    +
    	$conn = &ADONewConnection('mysql'); 
    $conn->PConnect('localhost','userid','password','database');

    # or dsn $dsn = 'mysql://user:pwd@localhost/mydb'; $conn = ADONewConnection($dsn); # no need for Connect() - # or persistent dsn + # or persistent dsn $dsn = 'mysql://user:pwd@localhost/mydb?persist'; $conn = ADONewConnection($dsn); # no need for PConnect() - # a more complex example: + # a more complex example: $pwd = urlencode($pwd); $flags = MYSQL_CLIENT_COMPRESS; - $dsn = "mysql://user:$pwd@localhost/mydb?persist&clientflags=$flags"; + $dsn = "mysql://user:$pwd@localhost/mydb?persist&clientflags=$flags"; $conn = ADONewConnection($dsn); # no need for PConnect() -
    -

    For most drivers, you can use the standard function: Connect($server, $user, $password, $database), or -a DSN since ADOdb 4.51. Exceptions to this are listed below. -

    PostgreSQL

    -

    PostgreSQL accepts connections using:

    +
    +

    For most drivers, you can use the standard function: Connect($server, $user, $password, $database), or +a DSN since ADOdb 4.51. Exceptions to this are listed below. +

    PostgreSQL

    +

    PostgreSQL 7 and 8 accepts connections using:

    a. the standard connection string:

    -
    -	$conn = &ADONewConnection('postgres7'); 
    -	$conn->PConnect('host=localhost port=5432 dbname=mary');
    +
    	$conn = &ADONewConnection('postgres');  
    $conn->PConnect('host=localhost port=5432 dbname=mary');

    b. the classical 4 parameters:

    -
    -	$conn->PConnect('localhost','userid','password','database');
    - 
    +
    	$conn->PConnect('localhost','userid','password','database');

    c. dsn: -

    -	$dsn = 'postgres7://user:pwd@localhost/mydb?persist';  # persist is optional
    -	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    -
    - +

    	$dsn = 'postgres://user:pwd@localhost/mydb?persist';  # persist is optional
    +	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    +

    LDAP

    Here is an example of querying a LDAP server. Thanks to Josh Eldridge for the driver and this example: -

    - <?php
    +

     require('/path/to/adodb.inc.php');
     
    +/* Make sure to set this BEFORE calling Connect() */
    +$LDAP_CONNECT_OPTIONS = Array(
    +	Array ("OPTION_NAME"=>LDAP_OPT_DEREF, "OPTION_VALUE"=>2),
    +	Array ("OPTION_NAME"=>LDAP_OPT_SIZELIMIT,"OPTION_VALUE"=>100),
    +	Array ("OPTION_NAME"=>LDAP_OPT_TIMELIMIT,"OPTION_VALUE"=>30),
    +	Array ("OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION,"OPTION_VALUE"=>3),
    +	Array ("OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER,"OPTION_VALUE"=>13),
    +	Array ("OPTION_NAME"=>LDAP_OPT_REFERRALS,"OPTION_VALUE"=>FALSE),
    +	Array ("OPTION_NAME"=>LDAP_OPT_RESTART,"OPTION_VALUE"=>FALSE)
    +);
     $host = 'ldap.baylor.edu';
     $ldapbase = 'ou=People,o=Baylor University,c=US';
     
    @@ -381,34 +370,29 @@ if ($rs)
     	} 
     	
     print_r( $ldap->GetArray( $filter ) );
    -
     print_r( $ldap->GetRow( $filter ) );
     
     $ldap->Close();
     echo "</pre>";
    -?>
    +
    +

    Using DSN: +

    +$dsn = "ldap://ldap.baylor.edu/ou=People,o=Baylor University,c=US";
    +$db = NewADOConnection($dsn);
    +

    Interbase/Firebird

    You define the database in the $host parameter: -
    -	$conn = &ADONewConnection('ibase'); 
    -	$conn->PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');
    -
    +
    	$conn = &ADONewConnection('ibase'); 
    $conn->PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');

    Or dsn: -

    -	$dsn = 'firebird://user:pwd@localhost/mydb?persist&dialect=3';  # persist is optional
    -	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    -
    +

    	$dsn = 'firebird://user:pwd@localhost/mydb?persist&dialect=3';  # persist is optional
    $conn = ADONewConnection($dsn); # no need for Connect/PConnect

    SQLite

    Sqlite will create the database file if it does not exist. -
    -	$conn = &ADONewConnection('sqlite'); 
    -	$conn->PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist
    -
    +
    	$conn = &ADONewConnection('sqlite');
    +	$conn->PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist

    Or dsn: -

    -	$dsn = 'sqlite://user:pwd@localhost/mydb?persist';  # persist is optional
    -	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    -
    +

    	$path = urlencode('c:\path\to\sqlite.db');
    +	$dsn = "sqlite://$path/?persist";  # persist is optional
    +	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect

    Oracle (oci8)

    With oci8, you can connect in multiple ways. Note that oci8 works fine with newer versions of the Oracle, eg. 9i and 10g.

    @@ -419,73 +403,51 @@ newer versions of the Oracle, eg. 9i and 10g.

    or

     	$conn->PConnect('myTNS', 'scott', 'tiger');

    c. Host Address and SID

    -
    	$conn->Connect('192.168.0.1', 'scott', 'tiger', 'SID');
    +
    +	$conn->connectSID = true;
    +	$conn->Connect('192.168.0.1', 'scott', 'tiger', 'SID');

    d. Host Address and Service Name

    	$conn->Connect('192.168.0.1', 'scott', 'tiger', 'servicename');

    e. Oracle connection string: -

    	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
    -			(CONNECT_DATA=(SID=$sid)))";
    -	$conn->Connect($cstr, 'scott', 'tiger');
    -
    +

    	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
    (CONNECT_DATA=(SID=$sid)))";
    $conn->Connect($cstr, 'scott', 'tiger');

    f. ADOdb dsn: -

    -	$dsn = 'oci8://user:pwd@tnsname?persist';  # persist is optional
    -	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    -	
    -	$dsn = 'oci8://user:pwd@host/sid';
    -	$conn = ADONewConnection($dsn);
    -	
    -	$dsn = 'oci8://user:pwd@/';   # oracle on local machine
    -	$conn = ADONewConnection($dsn);
    -
    - -

    DSN-less ODBC (access and mssql examples)

    +

    	$dsn = 'oci8://user:pwd@tnsname/?persist';  # persist is optional
    $conn = ADONewConnection($dsn); # no need for Connect/PConnect

    $dsn = 'oci8://user:pwd@host/sid';
    $conn = ADONewConnection($dsn);

    $dsn = 'oci8://user:pwd@/'; # oracle on local machine
    $conn = ADONewConnection($dsn);
    +

    You can also set the charSet for Oracle 9.2 and later, supported since PHP 4.3.2, ADOdb 4.54: +

    	$conn->charSet = 'we8iso8859p1';
    $conn->Connect(...);

    # or
    $dsn = 'oci8://user:pwd@tnsname/?charset=WE8MSWIN1252';
    $db = ADONewConnection($dsn);
    + +

    DSN-less ODBC ( Access, MSSQL and DB2 examples)

    ODBC DSN's can be created in the ODBC control panel, or you can use a DSN-less connection.To use DSN-less connections with ODBC you need PHP 4.3 or later.

    For Microsoft Access:

    -
    -	$db =& ADONewConnection('access');
    -	$dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;";
    -	$db->Connect($dsn);
    +
    	$db =& ADONewConnection('access');
    $dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;"; + $db->Connect($dsn);
    For Microsoft SQL Server: -
    -	$db =& ADONewConnection('odbc_mssql');
    -	$dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";
    -	$db->Connect($dsn,'userid','password');
    -
    +
    	$db =& ADONewConnection('odbc_mssql');
    $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";
    $db->Connect($dsn,'userid','password');
    or if you prefer to use the mssql extension (which is limited to mssql 6.5 functionality): -
    -	$db =& ADONewConnection('mssql');
    -	$db->Execute("localhost', 'userid', 'password', 'northwind');
    -
    +
    	$db =& ADONewConnection('mssql');
    $db->Execute('localhost', 'userid', 'password', 'northwind');
    +For DB2: +
    	$db =& ADONewConnection('db2');
    $dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP;".
    "uid=root; pwd=secret";
    $db->Connect($dsn);
    DSN-less Connections with ADO
    If you are using versions of PHP earlier than PHP 4.3.0, DSN-less connections only work with Microsoft's ADO, which is Microsoft's COM based API. An example using the ADOdb library and Microsoft's ADO: -
    -<?php
    -	include('adodb.inc.php'); 
    -	$db = &ADONewConnection("ado_mssql");
    -	print "<h1>Connecting DSN-less $db->databaseType...</h1>";
    -		
    -	$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
    -		. "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;"  ;
    -	$db->Connect($myDSN);
    +
    <?php
    include('adodb.inc.php');
    $db = &ADONewConnection("ado_mssql");
    print "<h1>Connecting DSN-less $db->databaseType...</h1>";

    $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
    . "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;" ;
    + $db->Connect($myDSN); - $rs = $db->Execute("select * from table"); - $arr = $rs->GetArray(); + $rs = $db->Execute("select * from table"); + $arr = $rs->GetArray(); print_r($arr); -?> -
    +?> +

    High Speed ADOdb - tuning tips

    -

    ADOdb is a big class library, yet it consistently beats all other PHP class +

    ADOdb is a big class library, yet it consistently beats all other PHP class libraries in performance. This is because it is designed in a layered fashion, like an onion, with the fastest functions in the innermost layer. Stick to the following functions for best performance:

    - - +
    + @@ -495,8 +457,8 @@ using the ADOdb library and Microsoft's ADO: MoveNext, Close
    qstr, Affected_Rows, Insert_ID

    -
    Innermost Layer
    -

    The fastest way to access the field data is by accessing the array $recordset->fields +

    +

    The fastest way to access the field data is by accessing the array $recordset->fields directly. Also set the global variables $ADODB_FETCH_MODE = ADODB_FETCH_NUM, and (for oci8, ibase/firebird and odbc) $ADODB_COUNTRECS = false before you connect to your database.

    @@ -505,101 +467,67 @@ using the ADOdb library and Microsoft's ADO: quickly. At the time of writing (Dec 2003), this means oci8 and odbc drivers.

    Lastly make sure you have a PHP accelerator cache installed such as APC, Turck MMCache, Zend Accelerator or ionCube.

    +

    Some examples:

    + +
    Fastest data retrieval using PHPFastest data retrieval using ADOdb extension
    +
    $rs =& $rs->Execute($sql);
    while (!$rs->EOF) {
    var_dump($rs->fields);
    $rs->MoveNext();
    }
    +
    $rs =& $rs->Execute($sql);
    $array = adodb_getall($rs);
    var_dump($array);


    Advanced Tips -

    If you have the ADOdb C extension installed, - you can replace your calls to $rs->MoveNext() with adodb_movenext($rs). +

    If you have the ADOdb C extension installed, + you can replace your calls to $rs->MoveNext() with adodb_movenext($rs). This doubles the speed of this operation. For retrieving entire recordsets at once, use GetArray(), which uses the high speed extension function adodb_getall($rs) internally. -

    Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query() +

    Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query() to reduce query overhead. Both these functions share the same parameters as Execute(). -

    If you do not have any bind parameters or your database supports binding (without emulation), -then you can call _Execute() directly. Calling this function bypasses bind emulation. Debugging is still supported in _Execute(). -

    If you do not require debugging facilities nor emulated binding, and do not require a recordset to be returned, then you can call _query. This is great for inserts, updates and deletes. Calling this function -bypasses emulated binding, debugging, and recordset handling. Either the resultid, true or false are returned by _query(). -

    For Informix, you can disable scrollable cursors with $db->cursorType = 0. -

    +

    If you do not have any bind parameters or your database supports +binding (without emulation), +then you can call _Execute() directly. Calling this function bypasses +bind emulation. Debugging is still supported in _Execute(). +

    If you do not require debugging facilities nor emulated +binding, and do not require a recordset to be returned, then you can +call _query. This is great for inserts, updates and deletes. Calling +this function +bypasses emulated binding, debugging, and recordset handling. Either +the resultid, true or false are returned by _query().

    For Informix, you can disable scrollable cursors with $db->cursorType = 0. +

    Hacking ADOdb Safely

    You might want to modify ADOdb for your own purposes. Luckily you can still maintain backward compatibility by sub-classing ADOdb and using the $ADODB_NEWCONNECTION variable. $ADODB_NEWCONNECTION allows you to override the behaviour of ADONewConnection(). ADOConnection() checks for this variable and will call the function-name stored in this variable if it is defined. -

    In the following example, new functionality for the connection object +

    In the following example, new functionality for the connection object is placed in the hack_mysql and hack_postgres7 classes. The recordset class naming convention can be controlled using $rsPrefix. Here we set it to 'hack_rs_', which will make ADOdb use hack_rs_mysql and hack_rs_postgres7 as the recordset classes. -

    -class hack_mysql extends adodb_mysql {
    -var $rsPrefix = 'hack_rs_';
    -  /* Your mods here */
    -}
    -
    -class hack_rs_mysql extends ADORecordSet_mysql {
    -	 /* Your mods here */
    -}
    -
    -class hack_postgres7 extends adodb_postgres7 {
    -var $rsPrefix = 'hack_rs_';
    -  /* Your mods here */
    -}
    -
    -class hack_rs_postgres7 extends ADORecordSet_postgres7 {
    - /* Your mods here */
    -}
    -
    -$ADODB_NEWCONNECTION = 'hack_factory';
    -
    -function& hack_factory($driver)
    -{
    -	if ($driver !== 'mysql' && $driver !== 'postgres7') return false;
    -	
    -	$driver = 'hack_'.$driver;
    -	$obj = new $driver();
    -	return $obj;
    -}
    -
    -include_once('adodb.inc.php');
    -
    -

    Don't forget to call the constructor of the parent class in your constructor. If you want to use the default ADOdb drivers return false in the above hack_factory() function. +

    class hack_mysql extends adodb_mysql {
    var $rsPrefix = 'hack_rs_';
    /* Your mods here */
    }

    class hack_rs_mysql extends ADORecordSet_mysql {
    /* Your mods here */
    }

    class hack_postgres7 extends adodb_postgres7 {
    var $rsPrefix = 'hack_rs_';
    /* Your mods here */
    }

    class hack_rs_postgres7 extends ADORecordSet_postgres7 {
    /* Your mods here */
    }

    $ADODB_NEWCONNECTION = 'hack_factory';

    function& hack_factory($driver)
    {
    if ($driver !== 'mysql' && $driver !== 'postgres7') return false;

    $driver = 'hack_'.$driver;
    $obj = new $driver();
    return $obj;
    }

    include_once('adodb.inc.php');
    +

    Don't forget to call the constructor of the parent class in +your constructor. If you want to use the default ADOdb drivers return +false in the above hack_factory() function. -

    PHP5 Features

    +

    PHP5 Features

    ADOdb 4.02 or later will transparently determine which version of PHP you are using. If PHP5 is detected, the following features become available:
    • Foreach iterators: This is a very natural way of going through a recordset: -
      -	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
      -	$rs = $db->Execute($sql);
      -	foreach($rs as $k => $row) {
      -		echo "r1=".$row[0]." r2=".$row[1]."<br>";
      -	}
      -
      +
      	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
      $rs = $db->Execute($sql);
      foreach($rs as $k => $row) {
      echo "r1=".$row[0]." r2=".$row[1]."<br>";
      }

      -

    • Exceptions: Just include adodb-exceptions.inc.php and you can now +

    • Exceptions: Just include adodb-exceptions.inc.php and you can now catch exceptions on errors as they occur. -
      -	include("../adodb-exceptions.inc.php"); 
      -	include("../adodb.inc.php");	 
      -	try { 
      -		$db = NewADOConnection("oci8"); 
      -		$db->Connect('','scott','bad-password'); 
      -	} catch (exception $e) { 
      -		var_dump($e); 
      -		adodb_backtrace($e->gettrace());
      -	} 
      -
      +
      	include("../adodb-exceptions.inc.php"); 
      include("../adodb.inc.php");
      try {
      $db = NewADOConnection("oci8");
      $db->Connect('','scott','bad-password');
      } catch (exception $e) {
      var_dump($e);
      adodb_backtrace($e->gettrace());
      }

      Note that reaching EOF is not considered an error nor an exception. If you want to use the default ADOdb drivers return false. -

    +

    Databases Supported

    The name below is the value you pass to NewADOConnection($name) to create a connection object for that database.

    - - +

    +

    + @@ -675,10 +603,10 @@ The name below is the value you pass to NewADOConnection($name) to create + You can set $db->role, $db->dialect, $db->buffers and $db->charSet before connecting. @@ -737,7 +665,7 @@ The name below is the value you pass to NewADOConnection($name) to create @@ -782,8 +710,8 @@ The name below is the value you pass to NewADOConnection($name) to create PConnect('serverip:1521','scott','tiger','service')
    or using an entry in TNSNAMES.ORA or ONAMES or HOSTNAMES:
    PConnect(false, 'scott', 'tiger', $oraname). -

    Since 2.31, we support Oracle REF cursor variables directly - (see ExecuteCursor). +

    Since 2.31, we support Oracle REF cursor variables directly + (see ExecuteCursor).

    @@ -805,7 +733,7 @@ The name below is the value you pass to NewADOConnection($name) to create instead of :bindvar, (b) field names use the more common PHP convention of lowercase names.

    Use this driver if porting from other databases is important. Otherwise the oci8 driver offers better - performance. + performance.

    @@ -842,7 +770,7 @@ The name below is the value you pass to NewADOConnection($name) to create - @@ -872,12 +800,20 @@ The name below is the value you pass to NewADOConnection($name) to create + + + + + + + + + driver. @@ -898,6 +834,14 @@ The name below is the value you pass to NewADOConnection($name) to create + + + + + + + + @@ -929,10 +873,10 @@ The name below is the value you pass to NewADOConnection($name) to create +

    @@ -947,16 +891,24 @@ The name below is the value you pass to NewADOConnection($name) to create -

    -

    Name Tested DatabaseB Interbase 6 or earlier. Some users report you might need to use this
    - $db->PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey") + $db->PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey") to connect. Lacks Affected_Rows currently.

    - You can set $db->dialect, $db->buffers and $db->charSet before connecting.
    Y/N Interbase client Unix and WindowsMssql client

    Unix and Windows.
    Unix install - howto and another + howto and another one.

    Y/N Oracle client Unix and Windows Y/N Oracle client Unix and Windows
    odbtp CGeneric odbtp driver. Odbtp is a software for + Generic odbtp driver. Odbtp is a software for accessing Windows ODBC data sources from other operating systems. Y/N odbtpY ? ?
    pdoCGeneric PDO driver for PHP5. YPDO extension and database specific driversUnix and Windows.
    postgres A Generic PostgreSQL driver. Currently identical to postgres7 - driver. Y PostgreSQL client Unix and Windows. Y PostgreSQL client Unix and Windows.
    postgres8APostgreSQL which supports version 8 functionality.YPostgreSQL clientUnix and Windows.
    sapdbB Portable SQLite driver. This is because assoc mode does not work like other drivers in sqlite. Namely, when selecting (joining) multiple tables, the table - names are included in the assoc keys in the "sqlite" driver.

    - In "sqlitepo" driver, the table names are stripped from the returned column names. + names are included in the assoc keys in the "sqlite" driver.

    + In "sqlitepo" driver, the table names are stripped from the returned column names. When this results in a conflict, the first field get preference. -

    Y -

    Unix and Windows.

    Sybase client

    Unix and Windows.

    + + + sybase_ase + C + Sybase ASE. + Y/N + Sybase client +

    Unix and Windows.

    + + -

    The "Tested" column indicates how extensively the code has been tested +

    The "Tested" column indicates how extensively the code has been tested and used.
    A = well tested and used by many people
    B = tested and usable, but some features might not be implemented
    C = user contributed or experimental driver. Might not fully support all of the latest features of ADOdb.

    -

    The column "RecordCount() usable" indicates whether RecordCount() +

    The column "RecordCount() usable" indicates whether RecordCount() return the number of rows, or returns -1 when a SELECT statement is executed. If this column displays Y/N then the RecordCount() is emulated when the global variable $ADODB_COUNTRECS=true (this is the default). Note that for large recordsets, @@ -966,7 +918,7 @@ The name below is the value you pass to NewADOConnection($name) to create except for PostgreSQL and MySQL. This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.

    -


    +


    Tutorials

    Example 1: Select Statement

    Task: Connect to the Access Northwind DSN, display the first 2 columns of each @@ -981,24 +933,10 @@ The name below is the value you pass to NewADOConnection($name) to create to move from row to row.

    NB: A useful function that is not used in this example is SelectLimit, which allows us to limit the number of rows shown. -

    -<?
    -include('adodb.inc.php');	   # load code common to ADOdb
    -$conn = &ADONewConnection('access');	# create a connection
    -$conn->PConnect('northwind');   # connect to MS-Access, northwind DSN
    -$recordSet = &$conn->Execute('select * from products');
    -if (!$recordSet) 
    -	print $conn->ErrorMsg();
    -else
    -while (!$recordSet->EOF) {
    -	print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>';
    -	$recordSet->MoveNext();
    -}
    +

    <?
    include('adodb.inc.php'); # load code common to ADOdb
    $conn = &ADONewConnection('access'); # create a connection
    $conn->PConnect('northwind'); # connect to MS-Access, northwind DSN
    $recordSet = &$conn->Execute('select * from products');
    if (!$recordSet)
    print $conn->ErrorMsg();
    else
    while (!$recordSet->EOF) {
    print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>';
    $recordSet->MoveNext();
    }
    -$recordSet->Close(); # optional -$conn->Close(); # optional - -?> +$recordSet->Close(); # optional
    $conn->Close(); # optional
    +?>

    The $recordSet returned stores the current row in the $recordSet->fields @@ -1011,13 +949,8 @@ $conn->Close(); # optional array by field name. To force indexing by name - that is associative arrays - use the SetFetchMode function. Each recordset saves and uses whatever fetch mode was set when the recordset was created in Execute() or SelectLimit(). -

    -	$db->SetFetchMode(ADODB_FETCH_NUM);
    -	$rs1 = $db->Execute('select * from table');
    -	$db->SetFetchMode(ADODB_FETCH_ASSOC);
    -	$rs2 = $db->Execute('select * from table');
    -	print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
    -	print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
    +

    	$db->SetFetchMode(ADODB_FETCH_NUM);
    $rs1 = $db->Execute('select * from table');
    $db->SetFetchMode(ADODB_FETCH_ASSOC);
    $rs2 = $db->Execute('select * from table');
    print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1') + print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')

    To get the number of rows in the select statement, you can use $recordSet->RecordCount(). @@ -1025,31 +958,11 @@ $conn->Close(); # optional

    Example 2: Advanced Select with Field Objects

    Select a table, display the first two columns. If the second column is a date or timestamp, reformat the date to US format.

    -
    -<?
    -include('adodb.inc.php');	   # load code common to ADOdb
    -$conn = &ADONewConnection('access');	# create a connection
    -$conn->PConnect('northwind');   # connect to MS-Access, northwind dsn
    -$recordSet = &$conn->Execute('select CustomerID,OrderDate from Orders');
    -if (!$recordSet) 
    -	print $conn->ErrorMsg();
    -else
    -while (!$recordSet->EOF) {
    -	$fld = $recordSet->FetchField(1);
    -	$type = $recordSet->MetaType($fld->type);
    -
    -	if ( $type == 'D' || $type == 'T') 
    -		print $recordSet->fields[0].' '.
    -			$recordSet->UserDate($recordSet->fields[1],'m/d/Y').'<BR>';
    -	else 
    -		print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>';
    -
    -	$recordSet->MoveNext();
    -}
    -$recordSet->Close(); # optional
    -$conn->Close(); # optional
    -
    -?>
    +
    <?
    include('adodb.inc.php'); # load code common to ADOdb
    $conn = &ADONewConnection('access'); # create a connection
    $conn->PConnect('northwind'); # connect to MS-Access, northwind dsn
    $recordSet = &$conn->Execute('select CustomerID,OrderDate from Orders');
    if (!$recordSet)
    print $conn->ErrorMsg();
    else
    while (!$recordSet->EOF) {
    $fld = $recordSet->FetchField(1); + $type = $recordSet->MetaType($fld->type);

    if ( $type == 'D' || $type == 'T')
    print $recordSet->fields[0].' '.
    $recordSet->UserDate($recordSet->fields[1],'m/d/Y').'<BR>';
    else + print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>';

    $recordSet->MoveNext();
    }
    +$recordSet->Close(); # optional
    $conn->Close(); # optional
    +?>

    In this example, we check the field type of the second column using FetchField(). This returns an object with at least 3 fields.

    @@ -1064,11 +977,11 @@ $conn->Close(); # optional to translate the native type to a generic type. Currently the following generic types are defined:

      -
    • C: character fields that should be shown in a <input type="text"> +
    • C: character fields that should be shown in a <input type="text"> tag.
    • X: TeXt, large text fields that should be shown in a <textarea>
    • B: Blobs, or Binary Large Objects. Typically images. -
    • D: Date field
    • +
    • D: Date field
    • T: Timestamp field
    • L: Logical field (boolean or bit-field)
    • I:  Integer field
    • @@ -1086,22 +999,7 @@ $conn->Close(); # optional

      Insert a row to the Orders table containing dates and strings that need to be quoted before they can be accepted by the database, eg: the single-quote in the word John's.

      -
      -<?
      -include('adodb.inc.php');	   # load code common to ADOdb
      -$conn = &ADONewConnection('access');	# create a connection
      -
      -$conn->PConnect('northwind');   # connect to MS-Access, northwind dsn
      -$shipto = $conn->qstr("John's Old Shoppe");
      -
      -$sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
      -$sql .= "values ('ANATR',2,".$conn->DBDate(time()).",$shipto)";
      -
      -if ($conn->Execute($sql) === false) {
      -	print 'error inserting: '.$conn->ErrorMsg().'<BR>';
      -}
      -?>
      -
      +
      <?
      include('adodb.inc.php'); # load code common to ADOdb
      $conn = &ADONewConnection('access'); # create a connection

      $conn->PConnect('northwind'); # connect to MS-Access, northwind dsn
      $shipto = $conn->qstr("John's Old Shoppe");

      $sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
      $sql .= "values ('ANATR',2,".$conn->DBDate(time()).",$shipto)";

      if ($conn->Execute($sql) === false) {
      print 'error inserting: '.$conn->ErrorMsg().'<BR>';
      }
      ?>

      In this example, we see the advanced date and quote handling facilities of ADOdb. The unix timestamp (which is a long integer) is appropriately formated for Access with DBDate(), @@ -1115,15 +1013,8 @@ $sql .= "values ('ANATR',2,".php_track_errors might have to be enabled for error messages to be saved.

      Example 4: Debugging

      -
      <?
      -include('adodb.inc.php');	   # load code common to ADOdb
      -$conn = &ADONewConnection('access');	# create a connection
      -$conn->PConnect('northwind');   # connect to MS-Access, northwind dsn
      -$shipto = $conn->qstr("John's Old Shoppe");
      -$sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
      -$sql .= "values ('ANATR',2,".$conn->FormatDate(time()).",$shipto)";
      -$conn->debug = true;
      -if ($conn->Execute($sql) === false) print 'error inserting';
      +
      <?
      include('adodb.inc.php'); # load code common to ADOdb
      $conn = &ADONewConnection('access'); # create a connection
      $conn->PConnect('northwind'); # connect to MS-Access, northwind dsn
      $shipto = $conn->qstr("John's Old Shoppe");
      $sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
      $sql .= "values ('ANATR',2,".$conn->FormatDate(time()).",$shipto)";
      $conn->debug = true; +if ($conn->Execute($sql) === false) print 'error inserting';
      ?>

      In the above example, we have turned on debugging by setting debug = true. @@ -1131,255 +1022,148 @@ $sql .= "values ('ANATR',2,".$ErrorMsg() in this case. For displaying the recordset, see the rs2html() example.

      -

      Also see the section on Custom Error Handlers.

      +

      Also see the section on Custom Error Handlers.

      Example 5: MySQL and Menus

      Connect to MySQL database agora, and generate a <select> menu from an SQL statement where the <option> captions are in the 1st column, and the value to send back to the server is in the 2nd column.

      -
      <?
      -include('adodb.inc.php'); # load code common to ADOdb
      -$conn = &ADONewConnection('mysql');  # create a connection
      -$conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
      -$sql = 'select CustomerName, CustomerID from customers';
      -$rs = $conn->Execute($sql);
      -print $rs->GetMenu('GetCust','Mary Rosli');
      -?>
      +
      <?
      include('adodb.inc.php'); # load code common to ADOdb
      $conn = &ADONewConnection('mysql'); # create a connection
      $conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
      $sql = 'select CustomerName, CustomerID from customers';
      $rs = $conn->Execute($sql);
      print $rs->GetMenu('GetCust','Mary Rosli');
      ?>

      Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected. See GetMenu(). We also have functions that return the recordset as an array: GetArray(), and as an associative array with the key being the first column: GetAssoc().

      Example 6: Connecting to 2 Databases At Once

      -
      <?
      -include('adodb.inc.php');	 # load code common to ADOdb
      -$conn1 = &ADONewConnection('mysql');  # create a mysql connection
      -$conn2 = &ADONewConnection('oracle');  # create a oracle connection
      -
      -$conn1->PConnect($server, $userid, $password, $database);
      -$conn2->PConnect(false, $ora_userid, $ora_pwd, $oraname);
      -
      -$conn1->Execute('insert ...');
      -$conn2->Execute('update ...');
      -?>
      +
      <?
      include('adodb.inc.php'); # load code common to ADOdb
      $conn1 = &ADONewConnection('mysql'); # create a mysql connection
      $conn2 = &ADONewConnection('oracle'); # create a oracle connection

      $conn1->PConnect($server, $userid, $password, $database);
      $conn2->PConnect(false, $ora_userid, $ora_pwd, $oraname);

      $conn1->Execute('insert ...');
      $conn2->Execute('update ...');
      ?>

      -

      Example 7: Generating Update and Insert SQL

      -ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and +

      Example 7: Generating Update and Insert SQL

      +

      Since ADOdb 4.56, we support AutoExecute(), +which simplifies things by providing an advanced wrapper for GetInsertSQL() and GetUpdateSQL(). For example, +an INSERT can be carried out with: + +

      +    $record["firstname"] = "Bob"; 
      +    $record["lastname"] = "Smith"; 
      +    $record["created"] = time(); 
      +    $insertSQL = $conn->AutoExecute($rs, $record, 'INSERT'); 
      +
      + +and an UPDATE with: +
      +    $record["firstname"] = "Caroline"; 
      +    $record["lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith 
      +    $insertSQL = $conn->AutoExecute($rs, $record, 'UPDATE', 'WHERE id = 1'); 
      +
      +

      +The rest of this section is out-of-date: +

      ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...", -make a copy of the $rs->fields, modify the fields, and then generate the SQL to +make a copy of the $rs->fields, modify the fields, and then generate the SQL to update or insert into the table automatically.

      We show how the functions can be used when accessing a table with the following fields: (ID, FirstName, LastName, Created). -

      Before these functions can be called, you need to initialize the recordset +

      Before these functions can be called, you need to initialize the recordset by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. Since ADOdb 2.42, you can pass a table name instead of a recordset into GetInsertSQL (in $rs), and it will generate an insert statement for that table. -

      -

      <?
      -#==============================================
      -# SAMPLE GetUpdateSQL() and GetInsertSQL() code
      -#==============================================
      -include('adodb.inc.php');
      -include('tohtml.inc.php');
      -
      -#==========================
      -# This code tests an insert
      -
      -$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; 
      -# Select an empty record from the database
      -
      -$conn = &ADONewConnection("mysql");  # create a connection
      -$conn->debug=1;
      -$conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb
      -$rs = $conn->Execute($sql); # Execute the query and get the empty recordset
      -
      -$record = array(); # Initialize an array to hold the record data to insert
      -
      -# Set the values for the fields in the record
      -# Note that field names are case-insensitive
      -$record["firstname"] = "Bob";
      -$record["lastNamE"] = "Smith";
      -$record["creaTed"] = time();
      -
      -# Pass the empty recordset and the array containing the data to insert
      -# into the GetInsertSQL function. The function will process the data and return
      -# a fully formatted insert sql statement.
      -$insertSQL = $conn->GetInsertSQL($rs, $record);
      -
      -$conn->Execute($insertSQL); # Insert the record into the database
      -
      -#==========================
      -# This code tests an update
      -
      -$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; 
      -# Select a record to update
      -
      -$rs = $conn->Execute($sql); # Execute the query and get the existing record to update
      -
      -$record = array(); # Initialize an array to hold the record data to update
      -
      -# Set the values for the fields in the record
      -# Note that field names are case-insensitive
      -$record["firstname"] = "Caroline";
      -$record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith
      -
      -# Pass the single record recordset and the array containing the data to update
      -# into the GetUpdateSQL function. The function will process the data and return
      -# a fully formatted update sql statement with the correct WHERE clause.
      -# If the data has not changed, no recordset is returned
      -$updateSQL = $conn->GetUpdateSQL($rs, $record);
      -
      -$conn->Execute($updateSQL); # Update the record in the database
      -$conn->Close();
      -?>
      -
      - +

      +

      <?
      #==============================================
      # SAMPLE GetUpdateSQL() and GetInsertSQL() code
      #==============================================
      include('adodb.inc.php');
      include('tohtml.inc.php');

      #==========================
      # This code tests an insert

      $sql = "SELECT * FROM ADOXYZ WHERE id = -1";
      # Select an empty record from the database

      $conn = &ADONewConnection("mysql"); # create a connection
      $conn->debug=1;
      $conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb
      $rs = $conn->Execute($sql); # Execute the query and get the empty recordset

      $record = array(); # Initialize an array to hold the record data to insert

      # Set the values for the fields in the record
      # Note that field names are case-insensitive
      $record["firstname"] = "Bob";
      $record["lastNamE"] = "Smith";
      $record["creaTed"] = time();

      # Pass the empty recordset and the array containing the data to insert
      # into the GetInsertSQL function. The function will process the data and return
      # a fully formatted insert sql statement.
      $insertSQL = $conn->GetInsertSQL($rs, $record);

      $conn->Execute($insertSQL); # Insert the record into the database

      #==========================
      # This code tests an update

      $sql = "SELECT * FROM ADOXYZ WHERE id = 1";
      # Select a record to update

      $rs = $conn->Execute($sql); # Execute the query and get the existing record to update

      $record = array(); # Initialize an array to hold the record data to update

      # Set the values for the fields in the record
      # Note that field names are case-insensitive
      $record["firstname"] = "Caroline";
      $record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith

      # Pass the single record recordset and the array containing the data to update
      # into the GetUpdateSQL function. The function will process the data and return
      # a fully formatted update sql statement with the correct WHERE clause.
      # If the data has not changed, no recordset is returned
      $updateSQL = $conn->GetUpdateSQL($rs, $record);

      $conn->Execute($updateSQL); # Update the record in the database
      $conn->Close();
      ?>
      + $ADODB_FORCE_TYPE

      -The behaviour of GetUpdateSQL() and GetInsertSQL() +The behaviour of AutoExecute(), GetUpdateSQL() and GetInsertSQL() when converting empty or null PHP variables to SQL is controlled by the global $ADODB_FORCE_TYPE variable. Set it to one of the values below. Default is ADODB_FORCE_VALUE (3): -

      -0 = ignore empty fields. All empty fields in array are ignored.
      -1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
      -2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
      -3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and 
      -    empty fields '' are set to empty '' sql values.
      -
      -define('ADODB_FORCE_IGNORE',0);
      -define('ADODB_FORCE_NULL',1);
      -define('ADODB_FORCE_EMPTY',2);
      -define('ADODB_FORCE_VALUE',3);
      -
      +

      0 = ignore empty fields. All empty fields in array are ignored.
      1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
      2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
      3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and
      empty fields '' are set to empty '' sql values.

      define('ADODB_FORCE_IGNORE',0);
      define('ADODB_FORCE_NULL',1);
      define('ADODB_FORCE_EMPTY',2);
      define('ADODB_FORCE_VALUE',3);

      Thanks to Niko (nuko#mbnet.fi) for the $ADODB_FORCE_TYPE code. -

      +

      Note: the constant ADODB_FORCE_NULLS is obsolete since 4.52 and is ignored. Set $ADODB_FORCE_TYPE = ADODB_FORCE_NULL for equivalent behaviour. - -

      -

      Example 8: Implementing Scrolling with Next and Previous

      +

      Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called. +

      Example 8: Implementing Scrolling with Next and Previous

      The following code creates a very simple recordset pager, where you can scroll from page to page of a recordset.

      -
      -include_once('../adodb.inc.php');
      -include_once('../adodb-pager.inc.php');
      -session_start();
      -
      -$db = NewADOConnection('mysql');
      -
      -$db->Connect('localhost','root','','xphplens');
      -
      -$sql = "select * from adoxyz ";
      -
      -$pager = new ADODB_Pager($db,$sql);
      -$pager->Render($rows_per_page=5);
      +
      include_once('../adodb.inc.php');
      include_once('../adodb-pager.inc.php');
      session_start();

      $db = NewADOConnection('mysql');

      $db->Connect('localhost','root','','xphplens');

      $sql = "select * from adoxyz ";

      $pager = new ADODB_Pager($db,$sql);
      $pager->Render($rows_per_page=5);

      This will create a basic record pager that looks like this: -

      - - +

      +

      + - + - + -
      |<   << -   >>   >| +   >>   >|  
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      IDFirst NameLast NameDate Created
      36 Alan Turing Sat 06, Oct 2001 
      37 Serena Williams Sat 06, Oct 2001 
      38 Yat Sun Sun Sat 06, Oct 2001 
      39 Wai Hun See Sat 06, Oct 2001 
      40 Steven Oey Sat 06, Oct 2001 
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      IDFirst NameLast NameDate Created
      36 Alan Turing Sat 06, Oct 2001 
      37 Serena Williams Sat 06, Oct 2001 
      38 Yat Sun Sun Sat 06, Oct 2001 
      39 Wai Hun See Sat 06, Oct 2001 
      40 Steven Oey Sat 06, Oct 2001 
      Page 8/10Page 8/10
      -

      The number of rows to display at one time is controled by the Render($rows) + +

      The number of rows to display at one time is controled by the Render($rows) method. If you do not pass any value to Render(), ADODB_Pager will default to 10 records per page. -

      You can control the column titles by modifying your SQL (supported by most +

      You can control the column titles by modifying your SQL (supported by most databases): -

      $sql = 'select id as "ID", firstname as "First Name", 
      -		  lastname as "Last Name", created as "Date Created" 
      from adoxyz';
      +

      $sql = 'select id as "ID", firstname as "First Name", 
      lastname as "Last Name", created as "Date Created"
      from adoxyz';

      The above code can be found in the adodb/tests/testpaging.php example included with this release, and the class ADODB_Pager in adodb/adodb-pager.inc.php. The ADODB_Pager code can be adapted by a programmer so that the text links can be replaced by images, and the dull white background be replaced with more interesting colors. -

      You can also allow display of html by setting $pager->htmlSpecialChars = false. -

      Some of the code used here was contributed by Iván Oliva and Cornel +

      You can also allow display of html by setting $pager->htmlSpecialChars = false. +

      Some of the code used here was contributed by Iván Oliva and Cornel G.

      Example 9: Exporting in CSV or Tab-Delimited Format

      We provide some helper functions to export in comma-separated-value (CSV) and tab-delimited formats:

      include_once('/path/to/adodb/toexport.inc.php');
      include_once('/path/to/adodb/adodb.inc.php');
      -$db = &NewADOConnection('mysql');
      $db->Connect($server, $userid, $password, $database);

      $rs = $db->Execute('select fname as "First Name", surname as "Surname" from table'); - -print "<pre>";
      print rs2csv($rs); # return a string, CSV format

      print '<hr>'; -
      $rs->MoveFirst(); # note, some databases do not support MoveFirst
      print rs2tab($rs,false); # return a string, tab-delimited - # false == suppress field names in first line

      print '<hr>';
      $rs->MoveFirst();
      rs2tabout($rs); # send to stdout directly (there is also an rs2csvout function) -print "</pre>"; - -$rs->MoveFirst();
      $fp = fopen($path, "w"); -if ($fp) {
      rs2csvfile($rs, $fp); # write to file (there is also an rs2tabfile function) - fclose($fp);
      } -
      +$db = &NewADOConnection('mysql');
      $db->Connect($server, $userid, $password, $database);

      $rs = $db->Execute('select fname as "First Name", surname as "Surname" from table');

      print "<pre>";
      print rs2csv($rs); # return a string, CSV format

      print '<hr>';

      $rs->MoveFirst(); # note, some databases do not support MoveFirst
      print rs2tab($rs,false); # return a string, tab-delimited
      # false == suppress field names in first line

      print '<hr>';
      $rs->MoveFirst();
      rs2tabout($rs); # send to stdout directly (there is also an rs2csvout function)
      print "</pre>";

      $rs->MoveFirst();
      $fp = fopen($path, "w");
      if ($fp) {
      rs2csvfile($rs, $fp); # write to file (there is also an rs2tabfile function)
      fclose($fp);
      }

      Carriage-returns or newlines are converted to spaces. Field names are returned in the first line of text. Strings containing the delimiter character are quoted with double-quotes. Double-quotes are double-quoted again. This conforms to Excel import and export guide-lines. -

      All the above functions take as an optional last parameter, $addtitles which +

      All the above functions take as an optional last parameter, $addtitles which defaults to true. When set to false field names in the first line are suppressed.
      -

      Example 10: Recordset Filters

      +

      Example 10: Recordset Filters

      Sometimes we want to pre-process all rows in a recordset before we use it. For example, we want to ucwords all text in recordset. -

      -include_once('adodb/rsfilter.inc.php');
      -include_once('adodb/adodb.inc.php');
      -
      -// ucwords() every element in the recordset
      -function do_ucwords(&$arr,$rs)
      -{
      -	foreach($arr as $k => $v) {
      -		$arr[$k] = ucwords($v);
      -	}
      -}
      -
      -$db = NewADOConnection('mysql');
      -$db->PConnect('server','user','pwd','db');
      -
      -$rs = $db->Execute('select ... from table');
      -$rs = RSFilter($rs,'do_ucwords');
      -
      +

      include_once('adodb/rsfilter.inc.php');
      include_once('adodb/adodb.inc.php');

      // ucwords() every element in the recordset
      function do_ucwords(&$arr,$rs)
      {
      foreach($arr as $k => $v) {
      $arr[$k] = ucwords($v);
      }
      }

      $db = NewADOConnection('mysql');
      $db->PConnect('server','user','pwd','db');

      $rs = $db->Execute('select ... from table');
      $rs = RSFilter($rs,'do_ucwords');

      The RSFilter function takes 2 parameters, the recordset, and the name of the filter function. It returns the processed recordset scrolled to the first record. The filter function takes two parameters, the current @@ -1387,176 +1171,119 @@ $rs = RSFilter($rs,'do_ucwords'); not use the original recordset object.

      Example 11: Smart Transactions

      The old way of doing transactions required you to use -
      -$conn->BeginTrans();
      -$ok = $conn->Execute($sql);
      -if ($ok) $ok = $conn->Execute($sql2);
      -if (!$ok) $conn->RollbackTrans();
      -else $conn->CommitTrans();
      -
      +
      $conn->BeginTrans();
      $ok = $conn->Execute($sql);
      if ($ok) $ok = $conn->Execute($sql2);
      if (!$ok) $conn->RollbackTrans();
      else $conn->CommitTrans();
      This is very complicated for large projects because you have to track the error status. Smart Transactions is much simpler. You start a smart transaction by calling StartTrans(): -
      -$conn->StartTrans();
      -$conn->Execute($sql);
      -$conn->Execute($Sql2);
      -$conn->CompleteTrans();
      -
      +
      $conn->StartTrans();
      $conn->Execute($sql);
      $conn->Execute($Sql2);
      $conn->CompleteTrans();
      CompleteTrans() detects when an SQL error occurs, and will Rollback/Commit as appropriate. To specificly force a rollback even if no error occured, use FailTrans(). Note that the rollback is done in CompleteTrans(), and not in FailTrans(). -
      -$conn->StartTrans();
      -$conn->Execute($sql);
      -if (!CheckRecords()) $conn->FailTrans();
      -$conn->Execute($Sql2);
      -$conn->CompleteTrans();
      -
      +
      $conn->StartTrans();
      $conn->Execute($sql);
      if (!CheckRecords()) $conn->FailTrans();
      $conn->Execute($Sql2);
      $conn->CompleteTrans();

      You can also check if a transaction has failed, using HasFailedTrans(), which returns true if FailTrans() was called, or there was an error in the SQL execution. Make sure you call HasFailedTrans() before you call CompleteTrans(), as it is only works between StartTrans/CompleteTrans. -

      Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block +

      Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable. -

      -$conn->StartTrans();
      -$conn->Execute($sql);
      -  $conn->StartTrans();    # ignored
      -  if (!CheckRecords()) $conn->FailTrans();
      -  $conn->CompleteTrans(); # ignored
      -$conn->Execute($Sql2);
      -$conn->CompleteTrans();
      -
      +

      $conn->StartTrans();
      $conn->Execute($sql);
      $conn->StartTrans(); # ignored + if (!CheckRecords()) $conn->FailTrans(); + $conn->CompleteTrans(); # ignored +$conn->Execute($Sql2); +$conn->CompleteTrans();

      Note: Savepoints are currently not supported. -

      Using Custom Error Handlers and PEAR_Error

      +

      Using Custom Error Handlers and PEAR_Error

      ADOdb supports PHP5 exceptions. Just include adodb-exceptions.inc.php and you can now catch exceptions on errors as they occur. -

      -	include("../adodb-exceptions.inc.php"); 
      -	include("../adodb.inc.php");	 
      -	try { 
      -		$db = NewADOConnection("oci8://scott:bad-password@mytns/"); 
      -	} catch (exception $e) { 
      -		var_dump($e); 
      -		adodb_backtrace($e->gettrace());
      -	} 
      -
      +

      	include("../adodb-exceptions.inc.php"); 
      include("../adodb.inc.php");
      try {
      $db = NewADOConnection("oci8://scott:bad-password@mytns/");
      } catch (exception $e) {
      var_dump($e);
      adodb_backtrace($e->gettrace());
      }

      ADOdb also provides two custom handlers which you can modify for your needs. The first one is in the adodb-errorhandler.inc.php file. This makes use of - the standard PHP functions error_reporting - to control what error messages types to display, and trigger_error + the standard PHP functions error_reporting + to control what error messages types to display, and trigger_error which invokes the default PHP error handler. -

      Including the above file will cause trigger_error($errorstring,E_USER_ERROR) +

      Including the above file will cause trigger_error($errorstring,E_USER_ERROR) to be called when
      (a) Connect() or PConnect() fails, or
      (b) a function that executes SQL statements such as Execute() or SelectLimit() has an error.
      (c) GenID() appears to go into an infinite loop. -

      The $errorstring is generated by ADOdb and will contain useful debugging information +

      The $errorstring is generated by ADOdb and will contain useful debugging information similar to the error.log data generated below. This file adodb-errorhandler.inc.php should be included before you create any ADOConnection objects. -

      If you define error_reporting(0), no errors will be passed to the error handler. +

      If you define error_reporting(0), no errors will be passed to the error handler. If you set error_reporting(E_ALL), all errors will be passed to the error handler. You still need to use ini_set("display_errors", "0" or "1") to control the display of errors. -

      -<?php
      -error_reporting(E_ALL); # pass any error messages triggered to error handler
      -include('adodb-errorhandler.inc.php');
      +

      <?php
      error_reporting(E_ALL); # pass any error messages triggered to error handler
      include('adodb-errorhandler.inc.php');
      include('adodb.inc.php'); include('tohtml.inc.php'); $c = NewADOConnection('mysql'); -$c->PConnect('localhost','root','','northwind'); -$rs=$c->Execute('select * from productsz'); #invalid table productsz'); +$c->PConnect('localhost','root','','northwind'); +$rs=$c->Execute('select * from productsz'); #invalid table productsz'); if ($rs) rs2html($rs); -?> +?>

      If you want to log the error message, you can do so by defining the following optional constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE - is the error log message type (see error_log + is the error log message type (see error_log in the PHP manual). In this case we set it to 3, which means log to the file defined by the constant ADODB_ERROR_LOG_DEST. -

      -<?php
      -error_reporting(E_ALL); # report all errors
      -ini_set("display_errors", "0"); # but do not echo the errors
      -define('ADODB_ERROR_LOG_TYPE',3);
      -define('ADODB_ERROR_LOG_DEST','C:/errors.log');
      -include('adodb-errorhandler.inc.php');
      +

      <?php
      error_reporting(E_ALL); # report all errors
      ini_set("display_errors", "0"); # but do not echo the errors
      define('ADODB_ERROR_LOG_TYPE',3);
      define('ADODB_ERROR_LOG_DEST','C:/errors.log');
      include('adodb-errorhandler.inc.php');
      include('adodb.inc.php'); include('tohtml.inc.php'); $c = NewADOConnection('mysql'); -$c->PConnect('localhost','root','','northwind'); -$rs=$c->Execute('select * from productsz'); ## invalid table productsz +$c->PConnect('localhost','root','','northwind'); +$rs=$c->Execute('select * from productsz'); ## invalid table productsz if ($rs) rs2html($rs); -?> +?>
      The following message will be logged in the error.log file: -
      -(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in
      - EXECUTE("select * from productsz")
      -
      +
      (2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in
      EXECUTE("select * from productsz")
      +

      PEAR_ERROR

      The second error handler is adodb-errorpear.inc.php. This will create a PEAR_Error derived object whenever an error occurs. The last PEAR_Error object created can be retrieved using ADODB_Pear_Error(). -
      -<?php
      -include('adodb-errorpear.inc.php');
      +
      <?php
      include('adodb-errorpear.inc.php'); include('adodb.inc.php'); include('tohtml.inc.php'); $c = NewADOConnection('mysql'); -$c->PConnect('localhost','root','','northwind'); -$rs=$c->Execute('select * from productsz'); #invalid table productsz'); +$c->PConnect('localhost','root','','northwind'); +$rs=$c->Execute('select * from productsz'); #invalid table productsz'); if ($rs) rs2html($rs); -else { - $e = ADODB_Pear_Error(); - echo '<p>',$e->message,'</p>'; -} -?> +else { + $e = ADODB_Pear_Error();
      echo '<p>',$e->message,'</p>';
      +} +?>

      You can use a PEAR_Error derived class by defining the constant ADODB_PEAR_ERROR_CLASS before the adodb-errorpear.inc.php file is included. For easy debugging, you can set the default error handler in the beginning of the PHP script to PEAR_ERROR_DIE, which will cause an error message to be printed, then halt script execution: -

      -include('PEAR.php');
      -PEAR::setErrorHandling('PEAR_ERROR_DIE');
      -
      +

      include('PEAR.php');
      PEAR::setErrorHandling('PEAR_ERROR_DIE');

      Note that we do not explicitly return a PEAR_Error object to you when an error occurs. We return false instead. You have to call ADODB_Pear_Error() to get the last error or use the PEAR_ERROR_DIE technique. +

      +

      MetaError and MetaErrMsg

      +

      If you need error messages that work across multiple databases, then use MetaError(), which returns a virtualized error number, based on PEAR DB's error number system, and MetaErrMsg(). +

      Error Messages

      Error messages are outputted using the static method ADOConnnection::outp($msg,$newline=true). By default, it sends the messages to the client. You can override this to perform error-logging. -

      Data Source Names

      +

      Data Source Names

      We now support connecting using PEAR style DSN's. A DSN is a connection string of the form:

      -

      $dsn = "$driver://$username:$password@$hostname/$databasename";

      +

      $dsn = "$driver://$username:$password@$hostname/$databasename";

      An example:

      -
      -   $username = 'root';
      -   $password = '';
      -   $hostname = 'localhost';
      -   $databasename = 'xphplens';
      -   $driver = 'mysql';
      -   $dsn = "$driver://$username:$password@$hostname/$databasename"
      -   $db = NewADOConnection(); 
      -   # DB::Connect($dsn) also works if you include 'adodb/adodb-pear.inc.php' at the top
      -   $rs = $db->query('select firstname,lastname from adoxyz');
      -   $cnt = 0;
      -   while ($arr = $rs->fetchRow()) {
      -		print_r($arr); print "<br>";
      -   }
      -

      +
         $username = 'root';
      $password = '';
      $hostname = 'localhost';
      $databasename = 'xphplens';
      $driver = 'mysql';
      $dsn = "$driver://$username:$password@$hostname/$databasename"
      $db = NewADOConnection();
      # DB::Connect($dsn) also works if you include 'adodb/adodb-pear.inc.php' at the top
      $rs = $db->query('select firstname,lastname from adoxyz');
      $cnt = 0;
      while ($arr = $rs->fetchRow()) {
      print_r($arr); print "<br>";
      }
      +

      More info and connection examples on the DSN format. -

      PEAR Compatibility

      +

      PEAR Compatibility

      We support DSN's (see above), and the following functions: -
      - DB_Common
      + 
       DB_Common
        	query - returns PEAR_Error on error
       	limitQuery - return PEAR_Error on error
       	prepare - does not return PEAR_Error on error
      @@ -1583,49 +1310,39 @@ PEAR::setErrorHandling('PEAR_ERROR_DIE');
       

      ADOdb now supports caching of recordsets using the CacheExecute( ), CachePageExecute( ) and CacheSelectLimit( ) functions. There are similar to the non-cache functions, except that they take a new first parameter, $secs2cache. -

      An example: -

      -include('adodb.inc.php'); # load code common to ADOdb
      -$ADODB_CACHE_DIR = '/usr/ADODB_cache';
      -$conn = &ADONewConnection('mysql');  # create a connection
      -$conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
      -$sql = 'select CustomerName, CustomerID from customers';
      -$rs = $conn->CacheExecute(15,$sql);
      -

      The first parameter is the number of seconds to cache +

      An example: +

      include('adodb.inc.php'); # load code common to ADOdb
      $ADODB_CACHE_DIR = '/usr/ADODB_cache';
      $conn = &ADONewConnection('mysql'); # create a connection
      $conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
      $sql = 'select CustomerName, CustomerID from customers';
      $rs = $conn->CacheExecute(15,$sql);
      +

      The first parameter is the number of seconds to cache the query. Subsequent calls to that query will used the cached version stored in $ADODB_CACHE_DIR. To force a query to execute and flush the cache, call CacheExecute() with the first parameter set to zero. Alternatively, use the CacheFlush($sql) call.

      -

      For the sake of security, we recommend you set register_globals=off +

      For the sake of security, we recommend you set register_globals=off in php.ini if you are using $ADODB_CACHE_DIR.

      In ADOdb 1.80 onwards, the secs2cache parameter is optional in CacheSelectLimit() - and CacheExecute(). If you leave it out, it will use the $connection->cacheSecs + and CacheExecute(). If you leave it out, it will use the $connection->cacheSecs parameter, which defaults to 60 minutes. -

      -	$conn->Connect(...);
      -	$conn->cacheSecs = 3600*24; # cache 24 hours
      -	$rs = $conn->CacheExecute('select * from table');
      -
      -

      Please note that magic_quotes_runtime should be turned off. More +

      	$conn->Connect(...);
      $conn->cacheSecs = 3600*24; # cache 24 hours
      $rs = $conn->CacheExecute('select * from table');
      +

      Please note that magic_quotes_runtime should be turned off. More info, and do not change $ADODB_FETCH_MODE (or SetFetchMode) - as the cached recordset will use the $ADODB_FETCH_MODE set when the query was executed. + as the cached recordset will use the $ADODB_FETCH_MODE set when the query was executed.

      Pivot Tables

      -

      Since ADOdb 2.30, we support the generation of +

      Since ADOdb 2.30, we support the generation of SQL to create pivot tables, also known as cross-tabulations. For further explanation -read this DevShed Cross-Tabulation +read this DevShed Cross-Tabulation tutorial. We assume that your database supports the SQL case-when expression.

      - +

      In this example, we will use the Northwind database from Microsoft. In the database, we have a products table, and we want to analyze this table by suppliers versus product categories. We will place the suppliers on each row, and pivot on categories. So from the table on the left, we generate the pivot-table on the right:

      - - +
      +
      - - +
      + @@ -1641,12 +1358,12 @@ tutorial. We assume that your database supports the SQL case-when expression -
      Supplier Category
      supplier2 category2
      +
      --> - - +
      + @@ -1664,65 +1381,46 @@ tutorial. We assume that your database supports the SQL case-when expression -
        category1 category21 2
      + - - -

      The following code will generate the SQL for a cross-tabulation: -

      -# Query the main "product" table
      -# Set the rows to CompanyName
      -# and the columns to the values of Categories
      -# and define the joins to link to lookup tables 
      -# "categories" and "suppliers"
      -#
      - include "adodb/pivottable.php";
      - $sql = PivotTableSQL(
      - 	$gDB,                                      # adodb connection
      - 	'products p ,categories c ,suppliers s',   # tables
      -	'CompanyName',                             # rows (multiple fields allowed)
      -	'CategoryName',                            # column to pivot on 
      -	'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
      -);
      -
      -
      -

      This will generate the following SQL:

      + + +

      The following code will generate the SQL for a cross-tabulation: +

      # Query the main "product" table
      # Set the rows to CompanyName
      # and the columns to the values of Categories
      # and define the joins to link to lookup tables
      # "categories" and "suppliers"
      #
      include "adodb/pivottable.php";
      $sql = PivotTableSQL(
      $gDB, # adodb connection
      'products p ,categories c ,suppliers s', # tables
      'CompanyName', # rows (multiple fields allowed)
      'CategoryName', # column to pivot on
      'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
      );
      + +

      This will generate the following SQL:

      SELECT CompanyName,
      - SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", + 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='Condiments' THEN 1 ELSE 0 END) AS "Condiments",
      - SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", + 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='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='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='Produce' THEN 1 ELSE 0 END) AS "Produce",
      - SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", + 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

      You can also pivot on numerical columns and generate totals - by using ranges. This code was revised in ADODB 2.41 + by using ranges. This code was revised in ADODB 2.41 and is not backward compatible. The second example shows this:

      -
      - $sql = PivotTableSQL(
      - 	$gDB,                                       # adodb connection
      - 	'products p ,categories c ,suppliers s',    # tables
      -	'CompanyName',                              # rows (multiple fields allowed)
      +
       $sql = PivotTableSQL(
      $gDB, # adodb connection
      'products p ,categories c ,suppliers s', # tables
      'CompanyName', # rows (multiple fields allowed) array( # column ranges - ' 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' + ' 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 @@ -1731,28 +1429,28 @@ tutorial. We assume that your database supports the SQL case-when expression

      Which generates:

      SELECT CompanyName,
      - SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum - 0 ",
      + 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",
      + 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",
      + 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+",
      + 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

      -
      +

      Class Reference

      Function parameters with [ ] around them are optional.

      Global Variables

      -

      $ADODB_COUNTRECS

      +

      $ADODB_COUNTRECS

      If the database driver API does not support counting the number of records returned in a SELECT statement, the function RecordCount() is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default. @@ -1760,8 +1458,8 @@ tutorial. We assume that your database supports the SQL case-when expression of memory for big recordsets. Set this variable to false for the best performance. This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.

      -

      $ADODB_CACHE_DIR

      - +

      $ADODB_CACHE_DIR

      +

      If you are using recordset caching, this is the directory to save your recordsets in. Define this before you call any caching functions such as CacheExecute( ). We recommend setting register_globals=off in php.ini if you use this @@ -1771,823 +1469,716 @@ tutorial. We assume that your database supports the SQL case-when expression

      chown -R apache /path/to/adodb/cache
      chgrp -R apache /path/to/adodb/cache

      - -

      $ADODB_ANSI_PADDING_OFF

      -

      Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird). +

      $ADODB_ANSI_PADDING_OFF

      +

      Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird). Set to true to trim. Default is false. Currently works for oci8po, ibase and firebird drivers. Added in ADOdb 4.01. -

      $ADODB_LANG

      -

      Determines the language used in MetaErrorMsg(). The default is 'en', for English. +

      $ADODB_LANG

      +

      Determines the language used in MetaErrorMsg(). The default is 'en', for English. To find out what languages are supported, see the files in adodb/lang/adodb-$lang.inc.php, where $lang is the supported langauge. -

      $ADODB_FETCH_MODE

      -

      This is a global variable that determines how arrays are retrieved by recordsets. +

      $ADODB_FETCH_MODE

      +

      This is a global variable that determines how arrays are retrieved by recordsets. The recordset saves this value on creation (eg. in Execute( ) or SelectLimit( )), and any subsequent changes to $ADODB_FETCH_MODE have no affect on existing - recordsets, only on recordsets created in the future.

      -

      The following constants are defined:

      -
      -

      define('ADODB_FETCH_DEFAULT',0);
      + recordsets, only on recordsets created in the future.

      +

      The following constants are defined:

      + +

      define('ADODB_FETCH_DEFAULT',0);
      define('ADODB_FETCH_NUM',1);
      define('ADODB_FETCH_ASSOC',2);
      define('ADODB_FETCH_BOTH',3);

      - -

      An example: -

      -	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
      -	$rs1 = $db->Execute('select * from table');
      -	$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
      -	$rs2 = $db->Execute('select * from table');
      -	print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
      -	print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
      -
      -

      As you can see in the above example, both recordsets store and use different + +

      An example: +

      	$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
      $rs1 = $db->Execute('select * from table');
      $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
      $rs2 = $db->Execute('select * from table');
      print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1') + print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1') +
      +

      As you can see in the above example, both recordsets store and use different fetch modes based on the $ADODB_FETCH_MODE setting when the recordset was - created by Execute().

      -

      If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. + created by Execute().

      +

      If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. The behaviour of this default mode varies from driver to driver, so do not rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM - or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.

      -

      SetFetchMode Function

      -

      Some programmers prefer to use a more object-oriented solution, where the fetch - mode is set by a object function, SetFetchMode. + or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.

      +

      SetFetchMode Function

      +

      If you have multiple connection objects, and want to have different fetch modes for each +connection, then use SetFetchMode. Once this function is called for a connection object, that connection object will ignore the global variable $ADODB_FETCH_MODE and will use the internal - fetchMode property exclusively.

      -
      -	$db->SetFetchMode(ADODB_FETCH_NUM);
      -	$rs1 = $db->Execute('select * from table');
      -	$db->SetFetchMode(ADODB_FETCH_ASSOC);
      -	$rs2 = $db->Execute('select * from table');
      -	print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
      -	print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
      -

      To retrieve the previous fetch mode, you can use check the $db->fetchMode + fetchMode property exclusively.

      +
      	$db->SetFetchMode(ADODB_FETCH_NUM);
      $rs1 = $db->Execute('select * from table');
      $db->SetFetchMode(ADODB_FETCH_ASSOC);
      $rs2 = $db->Execute('select * from table');
      print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1') + print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
      +

      To retrieve the previous fetch mode, you can use check the $db->fetchMode property, or use the return value of SetFetchMode( ). -

      ADODB_ASSOC_CASE

      -

      You can control the associative fetch case for certain drivers which behave +

      ADODB_ASSOC_CASE

      +

      You can control the associative fetch case for certain drivers which behave differently. For the sybase, oci8po, mssql, odbc and ibase drivers and all drivers derived from them, ADODB_ASSOC_CASE will by default generate recordsets where the field name keys are lower-cased. Use the constant ADODB_ASSOC_CASE - to change the case of the keys. There are 3 possible values:

      -

      0 = assoc lowercase field names. $rs->fields['orderid']
      + to change the case of the keys. There are 3 possible values:

      +

      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'] -- this is the - default since ADOdb 2.90

      -

      To use it, declare it before you incldue adodb.inc.php.

      -

      define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC
      - include('adodb.inc.php');

      -

      $ADODB_FORCE_TYPE

      -

      See the GetUpdateSQL tutorial. -


      -

      ADOConnection

      -

      Object that performs the connection to the database, executes SQL statements + default since ADOdb 2.90

      +

      To use it, declare it before you incldue adodb.inc.php.

      +

      define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC
      + include('adodb.inc.php');

      +

      $ADODB_FORCE_TYPE

      +

      See the GetUpdateSQL tutorial. +


      +

      ADOConnection

      +

      Object that performs the connection to the database, executes SQL statements and has a set of utility functions for standardising the format of SQL statements - for issues such as concatenation and date formats.

      -

      ADOConnection Fields

      -

      databaseType: Name of the database system we are connecting to. Eg. - odbc or mssql or mysql.

      -

      dataProvider: The underlying mechanism used to connect to the database. - Normally set to native, unless using odbc or ado.

      -

      host: Name of server or data source name (DSN) to connect to.

      -

      database: Name of the database or to connect to. If ado is used, it - will hold the ado data provider.

      -

      user: Login id to connect to database. Password is not saved for security - reasons.

      -

      raiseErrorFn: Allows you to define an error handling function. See adodb-errorhandler.inc.php - for an example.

      -

      debug: Set to true to make debug statements to appear.

      -

      concat_operator: Set to '+' or '||' normally. The operator used to concatenate - strings in SQL. Used by the Concat function.

      -

      fmtDate: The format used by the DBDate + for issues such as concatenation and date formats.

      +

      ADOConnection Fields

      +

      databaseType: Name of the database system we are connecting to. Eg. + odbc or mssql or mysql.

      +

      dataProvider: The underlying mechanism used to connect to the database. + Normally set to native, unless using odbc or ado.

      +

      host: Name of server or data source name (DSN) to connect to.

      +

      database: Name of the database or to connect to. If ado is used, it + will hold the ado data provider.

      +

      user: Login id to connect to database. Password is not saved for security + reasons.

      +

      raiseErrorFn: Allows you to define an error handling function. See adodb-errorhandler.inc.php + for an example.

      +

      debug: Set to true to make debug statements to appear.

      +

      concat_operator: Set to '+' or '||' normally. The operator used to concatenate + strings in SQL. Used by the Concat function.

      +

      fmtDate: The format used by the DBDate function to send dates to the database. is '#Y-m-d#' for Microsoft Access, - and ''Y-m-d'' for MySQL.

      -

      fmtTimeStamp: The format used by the DBTimeStamp - function to send timestamps to the database.

      -

      true: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for - Microsoft SQL.

      -

      false: The value used to represent false. Eg. '.F.'. for Foxpro, '0' - for Microsoft SQL.

      -

      replaceQuote: The string used to escape quotes. Eg. double single-quotes - for Microsoft SQL, and backslash-quote for MySQL. Used by qstr.

      -

      autoCommit: indicates whether automatic commit is enabled. Default is - true.

      -

      charSet: set the default charset to use. Currently only interbase supports - this.

      -

      dialect: set the default sql dialect to use. Currently only interbase - supports this.

      -

      metaTablesSQL: SQL statement to return a list of available tables. Eg. - SHOW TABLES in MySQL.

      -

      genID: The latest id generated by GenID() if supported by the database.

      -

      cacheSecs: The number of seconds to cache recordsets if CacheExecute() - or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.

      -

      sysDate: String that holds the name of the database function to call - to get the current date. Useful for inserts and updates.

      -

      sysTimeStamp: String that holds the name of the database function to - call to get the current timestamp/datetime value.

      -

      leftOuter: String that holds operator for left outer join, if known. - Otherwise set to false.

      -

      rightOuter: String that holds operator for left outer join, if known. - Otherwise set to false.

      -

      ansiOuter: Boolean that if true indicates that ANSI style outer joins - are permitted. Eg. select * from table1 left join table2 on p1=p2.

      -

      connectSID: Boolean that indicates whether to treat the $database parameter + and ''Y-m-d'' for MySQL.

      +

      fmtTimeStamp: The format used by the DBTimeStamp + function to send timestamps to the database.

      +

      true: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for + Microsoft SQL.

      +

      false: The value used to represent false. Eg. '.F.'. for Foxpro, '0' + for Microsoft SQL.

      +

      replaceQuote: The string used to escape quotes. Eg. double single-quotes + for Microsoft SQL, and backslash-quote for MySQL. Used by qstr.

      +

      autoCommit: indicates whether automatic commit is enabled. Default is + true.

      +

      charSet: set the default charset to use. Currently only interbase/firebird supports + this.

      +

      dialect: set the default sql dialect to use. Currently only interbase/firebird + supports this.

      +

      role: set the role. Currently only interbase/firebird + supports this.

      +

      metaTablesSQL: SQL statement to return a list of available tables. Eg. + SHOW TABLES in MySQL.

      +

      genID: The latest id generated by GenID() if supported by the database.

      +

      cacheSecs: The number of seconds to cache recordsets if CacheExecute() + or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.

      +

      sysDate: String that holds the name of the database function to call + to get the current date. Useful for inserts and updates.

      +

      sysTimeStamp: String that holds the name of the database function to + call to get the current timestamp/datetime value.

      +

      leftOuter: String that holds operator for left outer join, if known. + Otherwise set to false.

      +

      rightOuter: String that holds operator for left outer join, if known. + Otherwise set to false.

      +

      ansiOuter: Boolean that if true indicates that ANSI style outer joins + are permitted. Eg. select * from table1 left join table2 on p1=p2.

      +

      connectSID: Boolean that indicates whether to treat the $database parameter in connects as the SID for the oci8 driver. Defaults to false. Useful for - Oracle 8.0.5 and earlier.

      -

      autoRollback: Persistent connections are auto-rollbacked in PConnect( - ) if this is set to true. Default is false.

      + Oracle 8.0.5 and earlier.

      +

      autoRollback: Persistent connections are auto-rollbacked in PConnect( + ) if this is set to true. Default is false.


      -

      ADOConnection Main Functions

      -

      ADOConnection( )

      -

      Constructor function. Do not call this directly. Use ADONewConnection( ) instead.

      -

      Connect($host,[$user],[$password],[$database])

      -

      Non-persistent connect to data source or server $host, using userid +

      ADOConnection Main Functions

      +

      ADOConnection( )

      +

      Constructor function. Do not call this directly. Use ADONewConnection( ) instead.

      +

      Connect($host,[$user],[$password],[$database])

      +

      Non-persistent connect to data source or server $host, using userid $user and password $password. If the server supports multiple - databases, connect to database $database.

      -

      Returns true/false depending on connection success. Since 4.23, null is returned if the extension is not loaded.

      -

      ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database - parameter to the OLEDB data provider you are using.

      -

      PostgreSQL: An alternative way of connecting to the database is to pass the + databases, connect to database $database.

      +

      Returns true/false depending on connection success. Since 4.23, null is returned if the extension is not loaded.

      +

      ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database + parameter to the OLEDB data provider you are using.

      +

      PostgreSQL: An alternative way of connecting to the database is to pass the standard PostgreSQL connection string in the first parameter $host, and the - other parameters will be ignored.

      -

      For Oracle and Oci8, there are two ways to connect. First is to use the TNS + other parameters will be ignored.

      +

      For Oracle and Oci8, there are two ways to connect. First is to use the TNS name defined in your local tnsnames.ora (or ONAMES or HOSTNAMES). Place the name in the $database field, and set the $host field to false. Alternatively, set $host to the server, and $database to the database SID, this bypassed tnsnames.ora. -

      Examples: -

       # $oraname in tnsnames.ora/ONAMES/HOSTNAMES
      - $conn->Connect(false, 'scott', 'tiger', $oraname); 
      - $conn->Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora
      -

      There are many examples of connecting to a database. -See Connection Examples, php.weblogs.com/ADOdb, - and in the testdatabases.inc.php file included in the release.

      +

      Examples: +

       # $oraname in tnsnames.ora/ONAMES/HOSTNAMES
      $conn->Connect(false, 'scott', 'tiger', $oraname);
      $conn->Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora
      +

      There are many examples of connecting to a database. +See Connection Examples for many examples. -

      PConnect($host,[$user],[$password],[$database])

      -

      Persistent connect to data source or server $host, using userid $user +

      PConnect($host,[$user],[$password],[$database])

      +

      Persistent connect to data source or server $host, using userid $user and password $password. If the server supports multiple databases, - connect to database $database.

      -

      We now perform a rollback on persistent connection for selected databases since + connect to database $database.

      +

      We now perform a rollback on persistent connection for selected databases since 2.21, as advised in the PHP manual. See change log or source code for which databases are affected. -

      Returns true/false depending on connection. Since 4.23, null is returned if the extension is not loaded. -See Connect( ) above for more info.

      -

      Since ADOdb 2.21, we also support autoRollback. If you set:

      -
      -
       $conn = &NewADOConnection('mysql');
      - $conn->autoRollback = true; # default is false
      - $conn->PConnect(...); # rollback here
      +

      Returns true/false depending on connection. Since 4.23, null is returned if the extension is not loaded. +See Connect( ) above for more info.

      +

      Since ADOdb 2.21, we also support autoRollback. If you set:

      + +
       $conn = &NewADOConnection('mysql');
      $conn->autoRollback = true; # default is false
      $conn->PConnect(...); # rollback here

      Then when doing a persistent connection with PConnect( ), ADOdb will perform a rollback first. This is because it is documented that PHP is not guaranteed to rollback existing failed transactions when persistent connections are used. This is implemented in Oracle, MySQL, PgSQL, MSSQL, ODBC currently. -

      Since ADOdb 3.11, you can force non-persistent +

      Since ADOdb 3.11, you can force non-persistent connections even if PConnect is called by defining the constant ADODB_NEVER_PERSIST before you call PConnect. -

      +

      Since 4.23, null is returned if the extension is not loaded. -

      NConnect($host,[$user],[$password],[$database])

      +

      NConnect($host,[$user],[$password],[$database])

      Always force a new connection. In contrast, PHP sometimes reuses connections when you use Connect() or PConnect(). Currently works only on mysql (PHP 4.3.0 or later), postgresql and oci8-derived drivers. For other drivers, NConnect() works like - Connect(). - -

      Execute($sql,$inputarr=false)

      -

      Execute SQL statement $sql and return derived class of ADORecordSet + Connect().

      +

      IsConnected( )

      +

      +Returns true if connected to database. Added in 4.53. + +

      Execute($sql,$inputarr=false)

      +

      Execute SQL statement $sql and return derived class of ADORecordSet if successful. Note that a record set is always returned on success, even if we are executing an insert or update statement. You can also pass in $sql a statement prepared - in Prepare().

      -

      Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql + in Prepare().

      +

      Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql would be returned. False is returned if there was an error in executing the - sql.

      -

      The $inputarr parameter can be used for binding variables to parameters. Below - is an Oracle example:

      -
      - $conn->Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=> $val));
      - 
      -

      Another example, using ODBC,which uses the ? convention:

      -
      -  $conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));
      -
      - -Binding variables

      -Variable binding speeds the compilation and caching of SQL statements, leading + sql.

      +

      The $inputarr parameter can be used for binding variables to parameters. Below + is an Oracle example:

      +
       $conn->Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=> $val));
      +

      Another example, using ODBC,which uses the ? convention:

      +
        $conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));
      + +Binding variables

      +Variable binding speeds the compilation and caching of SQL statements, leading to higher performance. Currently Oracle, Interbase and ODBC supports variable binding. Interbase/ODBC style ? binding is emulated in databases that do not support binding. Note that you do not have to quote strings if you use binding. -

      Variable binding in the odbc, interbase and oci8po drivers. -

      -$rs = $db->Execute('select * from table where val=?', array('10'));
      -
      -Variable binding in the oci8 driver: -
      -$rs = $db->Execute('select name from table where val=:key', 
      -  array('key' => 10));
      -
      - +

      Variable binding in the odbc, interbase and oci8po drivers. +

      $rs = $db->Execute('select * from table where val=?', array('10'));
      +Variable binding in the oci8 driver: +
      $rs = $db->Execute('select name from table where val=:key', 
      array('key' => 10));
      + Bulk binding -

      Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to +

      Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to be bound to an INSERT/UPDATE or DELETE statement. -

      -$arr = array(
      -	array('Ahmad',32),
      -	array('Zulkifli', 24),
      -	array('Rosnah', 21)
      -	);
      -$ok = $db->Execute('insert into table (name,age) values (?,?)',$arr);
      -
      -

      This provides very high performance as the SQL statement is prepared first. +

      $arr = array(
      array('Ahmad',32),
      array('Zulkifli', 24),
      array('Rosnah', 21)
      );
      $ok = $db->Execute('insert into table (name,age) values (?,?)',$arr);
      +

      This provides very high performance as the SQL statement is prepared first. The prepared statement is executed repeatedly for each array row until all rows are completed, or until the first error. Very useful for importing data. -

      CacheExecute([$secs2cache,]$sql,$inputarr=false)

      -

      Similar to Execute, except that the recordset is cached for $secs2cache seconds +

      CacheExecute([$secs2cache,]$sql,$inputarr=false)

      +

      Similar to Execute, except that the recordset is cached for $secs2cache seconds in the $ADODB_CACHE_DIR directory, and $inputarr only accepts 1-dimensional arrays. If CacheExecute() is called again with the same $sql, $inputarr, and also the same database, same userid, and the cached recordset has not expired, the cached recordset is returned. -

      -  include('adodb.inc.php'); 
      -  include('tohtml.inc.php');
      -  $ADODB_CACHE_DIR = '/usr/local/ADOdbcache';
      -  $conn = &ADONewConnection('mysql'); 
      -  $conn->PConnect('localhost','userid','password','database');
      -  $rs = $conn->CacheExecute(15, 'select * from table'); # cache 15 secs
      -  rs2html($rs); /* recordset to html table */  
      -
      -

      Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:

      -
      	$conn->Connect(...);
      -   	$conn->cacheSecs = 3600*24; // cache 24 hours
      -	$rs = $conn->CacheExecute('select * from table');
      -
      -If $secs2cache is omitted, we use the value +

        include('adodb.inc.php'); 
      include('tohtml.inc.php');
      $ADODB_CACHE_DIR = '/usr/local/ADOdbcache';
      $conn = &ADONewConnection('mysql');
      $conn->PConnect('localhost','userid','password','database');
      $rs = $conn->CacheExecute(15, 'select * from table'); # cache 15 secs
      rs2html($rs); /* recordset to html table */
      +

      Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:

      +
      	$conn->Connect(...);
      $conn->cacheSecs = 3600*24; // cache 24 hours
      $rs = $conn->CacheExecute('select * from table');
      +If $secs2cache is omitted, we use the value in $connection->cacheSecs (default is 3600 seconds, or 1 hour). Use CacheExecute() only with SELECT statements. -

      Performance note: I have done some benchmarks and found that they vary so greatly +

      Performance note: I have done some benchmarks and found that they vary so greatly that it's better to talk about when caching is of benefit. When your database server is much slower than your Web server or the database is very overloaded then ADOdb's caching is good because it reduces the load on your database server. If your database server is lightly loaded or much faster - than your Web server, then caching could actually reduce performance.

      -

      ExecuteCursor($sql,$cursorName='rs',$parameters=false)

      -

      Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as + than your Web server, then caching could actually reduce performance.

      +

      ExecuteCursor($sql,$cursorName='rs',$parameters=false)

      +

      Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as a regular ADOdb recordset. Does not work with any other database except oci8. Thanks to Robert Tuttle for the design. -

      -    $db = ADONewConnection("oci8"); 
      -    $db->Connect("foo.com:1521", "uid", "pwd", "FOO"); 
      -    $rs = $db->ExecuteCursor("begin :cursorvar := getdata(:param1); end;", 
      -					'cursorvar',
      -					array('param1'=>10)); 
      -    # $rs is now just like any other ADOdb recordset object
      rs2html($rs);
      -

      ExecuteCursor() is a helper function that does the following internally: -

      -	$stmt = $db->Prepare("begin :cursorvar := getdata(:param1); end;", true); 
      -	$db->Parameter($stmt, $cur, 'cursorvar', false, -1, OCI_B_CURSOR);
      -	$rs = $db->Execute($stmt,$bindarr);
      -
      -

      ExecuteCursor only accepts 1 out parameter. So if you have 2 out parameters, use: -

      -	$vv = 'A%';
      -	$stmt = $db->PrepareSP("BEGIN list_tabs(:crsr,:tt); END;");
      -	$db->OutParameter($stmt, $cur, 'crsr', -1, OCI_B_CURSOR);
      -	$db->OutParameter($stmt, $vv, 'tt', 32); # return varchar(32)
      -	$arr = $db->GetArray($stmt);
      -	print_r($arr);
      -	echo " val = $vv"; ## outputs 'TEST'
      -
      -for the following PL/SQL: -
      -	TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
      -
      -	PROCEDURE list_tabs(tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) IS
      -	BEGIN
      -		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
      -		tablenames := 'TEST';
      -	END list_tabs;
      -
      -

      SelectLimit($sql,$numrows=-1,$offset=-1,$inputarr=false)

      -

      Returns a recordset if successful. Returns false otherwise. Performs a select +

          $db = ADONewConnection("oci8"); 
      $db->Connect("foo.com:1521", "uid", "pwd", "FOO");
      $rs = $db->ExecuteCursor("begin :cursorvar := getdata(:param1); end;",
      'cursorvar',
      array('param1'=>10));
      # $rs is now just like any other ADOdb recordset object
      rs2html($rs);
      +

      ExecuteCursor() is a helper function that does the following internally: +

      	$stmt = $db->Prepare("begin :cursorvar := getdata(:param1); end;", true); 
      $db->Parameter($stmt, $cur, 'cursorvar', false, -1, OCI_B_CURSOR);
      $rs = $db->Execute($stmt,$bindarr);
      +

      ExecuteCursor only accepts 1 out parameter. So if you have 2 out parameters, use: +

      	$vv = 'A%';
      $stmt = $db->PrepareSP("BEGIN list_tabs(:crsr,:tt); END;");
      $db->OutParameter($stmt, $cur, 'crsr', -1, OCI_B_CURSOR);
      $db->OutParameter($stmt, $vv, 'tt', 32); # return varchar(32)
      $arr = $db->GetArray($stmt);
      print_r($arr);
      echo " val = $vv"; ## outputs 'TEST'
      +for the following PL/SQL: +
      	TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;

      PROCEDURE list_tabs(tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) IS
      BEGIN
      OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
      tablenames := 'TEST';
      END list_tabs;
      +

      SelectLimit($sql,$numrows=-1,$offset=-1,$inputarr=false)

      +

      Returns a recordset if successful. Returns false otherwise. Performs a select statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET - $offset clause.

      -

      In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records - only. The equivalent is $connection->SelectLimit('SELECT * FROM TABLE',3). - This functionality is simulated for databases that do not possess this feature.

      -

      And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. - after record 2, return 3 rows). The equivalent in ADOdb is $connection->SelectLimit('SELECT - * FROM TABLE',3,2).

      -

      Note that this is the opposite of MySQL's LIMIT clause. You can also - set $connection->SelectLimit('SELECT * FROM TABLE',-1,10) to - get rows 11 to the last row.

      -

      The last parameter $inputarr is for databases that support variable binding + $offset clause.

      +

      In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records + only. The equivalent is $connection->SelectLimit('SELECT * FROM TABLE',3). + This functionality is simulated for databases that do not possess this feature.

      +

      And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. + after record 2, return 3 rows). The equivalent in ADOdb is $connection->SelectLimit('SELECT + * FROM TABLE',3,2).

      +

      Note that this is the opposite of MySQL's LIMIT clause. You can also + set $connection->SelectLimit('SELECT * FROM TABLE',-1,10) to + get rows 11 to the last row.

      +

      The last parameter $inputarr is for databases that support variable binding such as Oracle oci8. This substantially reduces SQL compilation overhead. - Below is an Oracle example:

      -
      - $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=> $val));
      - 
      -

      The oci8po driver (oracle portable driver) uses the more standard bind variable + Below is an Oracle example:

      +
       $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=> $val));
      +

      The oci8po driver (oracle portable driver) uses the more standard bind variable of ?: -

      - $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=> $val));
      -
      -

      -

      Ron Wilson reports that SelectLimit does not work with UNIONs. -

      CacheSelectLimit([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)

      -

      Similar to SelectLimit, except that the recordset returned is cached for $secs2cache - seconds in the $ADODB_CACHE_DIR directory.

      -

      Since 1.80, $secs2cache has been optional, and you can define the caching time - in $connection->cacheSecs.

      -
      -
      	$conn->Connect(...);
      -   $conn->cacheSecs = 3600*24; // cache 24 hours
      -	$rs = $conn->CacheSelectLimit('select * from table',10);
      - -

      CacheFlush($sql=false,$inputarr=false)

      -

      Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR. -

      If no parameter is passed in, then all adodb_*.cache files are deleted. -

      If you want to flush all cached recordsets manually, execute the following +

       $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=> $val));
      +

      +

      Ron Wilson reports that SelectLimit does not work with UNIONs. +

      CacheSelectLimit([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)

      +

      Similar to SelectLimit, except that the recordset returned is cached for $secs2cache + seconds in the $ADODB_CACHE_DIR directory.

      +

      Since 1.80, $secs2cache has been optional, and you can define the caching time + in $connection->cacheSecs.

      + +
      	$conn->Connect(...);
      $conn->cacheSecs = 3600*24; // cache 24 hours
      $rs = $conn->CacheSelectLimit('select * from table',10);
      + +

      CacheFlush($sql=false,$inputarr=false)

      +

      Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR. +

      If no parameter is passed in, then all adodb_*.cache files are deleted. +

      If you want to flush all cached recordsets manually, execute the following PHP code (works only under Unix):
      -   system("rm -f `find ".$ADODB_CACHE_DIR." -name - adodb_*.cache`");

      -

      For general cleanup of all expired files, you should use crontab +   system("rm -f `find ".$ADODB_CACHE_DIR." -name + adodb_*.cache`");

      +

      For general cleanup of all expired files, you should use crontab on Unix, or at.exe on Windows, and a shell script similar to the following:
      #------------------------------------------------------
      # This particular example deletes files in the TMPPATH
      - # directory with the string ".cache" in their name that
      + # directory with the string ".cache" in their name that
      # are more than 7 days old.
      #------------------------------------------------------
      AGED=7
      - find ${TMPPATH} -mtime +$AGED | grep "\.cache" | xargs rm -f
      -

      -

      MetaError($errno=false)

      -

      Returns a virtualized error number, based on PEAR DB's error number system. You might + find ${TMPPATH} -mtime +$AGED | grep "\.cache" | xargs rm -f
      +

      +

      MetaError($errno=false)

      +

      Returns a virtualized error number, based on PEAR DB's error number system. You might need to include adodb-error.inc.php before you call this function. The parameter $errno is the native error number you want to convert. If you do not pass any parameter, MetaError will call ErrorNo() for you and convert it. If the error number cannot be virtualized, MetaError -will return -1 (DB_ERROR).

      +will return -1 (DB_ERROR).

      -

      MetaErrorMsg($errno)

      -

      Pass the error number returned by MetaError() for the equivalent textual error message.

      -

      ErrorMsg()

      -

      Returns the last status or error message. The error message is reset after every +

      MetaErrorMsg($errno)

      +

      Pass the error number returned by MetaError() for the equivalent textual error message.

      +

      ErrorMsg()

      +

      Returns the last status or error message. The error message is reset after every call to Execute(). -

      -This can return a string even if +

      +This can return a string even if no error occurs. In general you do not need to call this function unless an - ADOdb function returns false on an error.

      -

      Note: If debug is enabled, the SQL error message is always displayed - when the Execute function is called.

      -

      ErrorNo()

      -

      Returns the last error number. The error number is reset after every call to Execute(). + ADOdb function returns false on an error.

      +

      Note: If debug is enabled, the SQL error message is always displayed + when the Execute function is called.

      +

      ErrorNo()

      +

      Returns the last error number. The error number is reset after every call to Execute(). If 0 is returned, no error occurred. -

      -Note that old versions of PHP (pre 4.0.6) do +

      +Note that old versions of PHP (pre 4.0.6) do not support error number for ODBC. In general you do not need to call this - function unless an ADOdb function returns false on an error.

      - -

      SetFetchMode($mode)

      -

      Sets the current fetch mode for the connection and stores + function unless an ADOdb function returns false on an error.

      + +

      SetFetchMode($mode)

      +

      Sets the current fetch mode for the connection and stores it in $db->fetchMode. Legal modes are ADODB_FETCH_ASSOC and ADODB_FETCH_NUM. For more info, see $ADODB_FETCH_MODE.

      -

      Returns the previous fetch mode, which could be false +

      Returns the previous fetch mode, which could be false if SetFetchMode( ) has not been called before.

      - -

      CreateSequence($seqName = 'adodbseq',$startID=1)

      -

      Create a sequence. The next time GenID( ) is called, the value returned will + +

      CreateSequence($seqName = 'adodbseq',$startID=1)

      +

      Create a sequence. The next time GenID( ) is called, the value returned will be $startID. Added in 2.60. -

      DropSequenceD($seqName = 'adodbseq')

      -

      Delete a sequence. Added in 2.60. -

      GenID($seqName = 'adodbseq',$startID=1)

      -

      Generate a sequence number . Works for interbase, +

      DropSequence($seqName = 'adodbseq')

      +

      Delete a sequence. Added in 2.60. +

      GenID($seqName = 'adodbseq',$startID=1)

      +

      Generate a sequence number . Works for interbase, mysql, postgresql, oci8, oci8po, mssql, ODBC based (access,vfp,db2,etc) drivers currently. Uses $seqName as the name of the sequence. GenID() will automatically create the sequence for you if it does not exist (provided the userid has permission to do so). Otherwise you will have to create the sequence yourself. -

      If your database driver emulates sequences, the name of the table is the sequence +

      If your database driver emulates sequences, the name of the table is the sequence name. The table has one column, "id" which should be of type integer, or if you need something larger - numeric(16). -

      For ODBC and databases that do not support sequences natively (eg mssql, mysql), +

      For ODBC and databases that do not support sequences natively (eg mssql, mysql), we create a table for each sequence. If the sequence has not been defined - earlier, it is created with the starting value set in $startID.

      -

      Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.

      -

      UpdateBlob($table,$column,$val,$where)

      -Allows you to store a blob (in $val) into $table into $column in a row at $where. -

      Usage: -

      -

      -	# for oracle
      -	$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');
      -	$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
      -	
      -	# non oracle databases
      -	$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
      -	$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
      -
      -

      Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, + earlier, it is created with the starting value set in $startID.

      +

      Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.

      +

      UpdateBlob($table,$column,$val,$where)

      +Allows you to store a blob (in $val) into $table into $column in a row at $where. +

      Usage: +

      +

      	# for oracle
      $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');
      $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');

      # non oracle databases
      $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
      $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
      +

      Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, Oci8, Oci8po and Interbase drivers. Other drivers might work, depending on - the state of development.

      -

      Note that when an Interbase blob is retrieved using SELECT, it still needs - to be decoded using $connection->DecodeBlob($blob); to derive the original + the state of development.

      +

      Note that when an Interbase blob is retrieved using SELECT, it still needs + to be decoded using $connection->DecodeBlob($blob); to derive the original value in versions of PHP before 4.1.0. -

      For PostgreSQL, you can store your blob using blob oid's or as a bytea field. +

      For PostgreSQL, you can store your blob using blob oid's or as a bytea field. You can use bytea fields but not blob oid's currently with UpdateBlob( ). Conversely UpdateBlobFile( ) supports oid's, but not bytea data.

      If you do not pass in an oid, then UpdateBlob() assumes that you are storing in bytea fields. -

      UpdateClob($table,$column,$val,$where)

      -Allows you to store a clob (in $val) into $table into $column in a row at $where. +

      If you do not have any blob fields, you can improve you can improve general SQL query performance by disabling blob handling with $connection->disableBlobs = true. +

      UpdateClob($table,$column,$val,$where)

      +Allows you to store a clob (in $val) into $table into $column in a row at $where. Similar to UpdateBlob (see above), but for Character Large OBjects. -

      Usage: -

      -	# for oracle
      -	$conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');
      -	$conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');
      -	
      -	# non oracle databases
      -	$conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
      -	$conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');
      -
      -

      UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')

      -

      Similar to UpdateBlob, except that we pass in a file path to where the blob +

      Usage: +

      	# for oracle
      $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');
      $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');

      # non oracle databases
      $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
      $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');
      +

      UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')

      +

      Similar to UpdateBlob, except that we pass in a file path to where the blob resides. -

      For PostgreSQL, if you are using blob oid's, use this interface. This interface +

      For PostgreSQL, if you are using blob oid's, use this interface. This interface does not support bytea fields. -

      Returns true if successful, false otherwise. -

      BlobEncode($blob) -

      Some databases require blob's to be encoded manually before upload. Note if +

      Returns true if successful, false otherwise. +

      BlobEncode($blob) +

      Some databases require blob's to be encoded manually before upload. Note if you use UpdateBlob( ) or UpdateBlobFile( ) the conversion is done automatically for you and you do not have to call this function. For PostgreSQL, currently, BlobEncode() can only be used for bytea fields. -

      Returns the encoded blob value. -

      Note that there is a connection property called blobEncodeType which +

      Returns the encoded blob value. +

      Note that there is a connection property called blobEncodeType which has 3 legal values: -

      false - no need to perform encoding or decoding.
      +

      false - no need to perform encoding or decoding.
      'I' - blob encoding required, and returned encoded blob is a numeric value (no need to quote).
      'C' - blob encoding required, and returned encoded blob is a character value (requires quoting). -

      This is purely for documentation purposes, so that programs that accept multiple +

      This is purely for documentation purposes, so that programs that accept multiple database drivers know what is the right thing to do when processing blobs. -

      BlobDecode($blob) -

      Some databases require blob's to be decoded manually after doing a select statement. +

      BlobDecode($blob, $maxblobsize = false) +

      Some databases require blob's to be decoded manually after doing a select statement. If the database does not require decoding, then this function will return the blob unchanged. Currently BlobDecode is only required for one database, PostgreSQL, and only if you are using blob oid's (if you are using bytea fields, - we auto-decode for you). -

      $rs = $db->Execute("select bloboid from postgres_table where id=$key");
      -$blob = $db->BlobDecode( reset($rs->fields) );
      -

      Replace($table, $arrFields, $keyCols,$autoQuote=false)

      -

      Try to update a record, and if the record is not found, an insert statement + we auto-decode for you). The default maxblobsize is set in $connection->maxblobsize, which + is set to 256K in adodb 4.54.

      + In ADOdb 4.54 and later, the blob is the return value. In earlier versions, the blob data is sent to stdout.

      +

      $rs = $db->Execute("select bloboid from postgres_table where id=$key");
      $blob = $db->BlobDecode( reset($rs->fields) );
      +

      Replace($table, $arrFields, $keyCols,$autoQuote=false)

      +

      Try to update a record, and if the record is not found, an insert statement is generated and executed. Returns 0 on failure, 1 if update statement worked, 2 if no record was found and the insert was executed successfully. This differs from MySQL's replace which deletes the record and inserts a new record. This also means you cannot update the primary key. The only exception to this is Interbase and its derivitives, which uses delete and insert because of some Interbase API limitations. -

      The parameters are $table which is the table name, the $keyCols which is an - associative array where the keys are the field names, and keyCols is the name +

      The parameters are $table which is the table name, the $arrFields which is an + associative array where the keys are the field names, and $keyCols is the name of the primary key, or an array of field names if it is a compound key. If $autoQuote is set to true, then Replace() will quote all values that are non-numeric; auto-quoting will not quote nulls. Note that auto-quoting will not work if you use SQL functions or operators. -

      Examples: +

      Examples: +

      # single field primary key
      $ret = $db->Replace('atable',
      array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
      'id',$autoquote = true);
      # generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000
      # or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')

      # compound key
      $ret = $db->Replace('atable2',
      array('firstname'=>'Harun','lastname'=>'Al-Rashid', 'age' => 33, 'birthday' => 'null'),
      array('lastname','firstname'),
      $autoquote = true);

      # no auto-quoting
      $ret = $db->Replace('atable2',
      array('firstname'=>"'Harun'",'lastname'=>"'Al-Rashid'", 'age' => 'null'),
      array('lastname','firstname'));
      +

      AutoExecute($table, $arrFields, $mode, $where=false, $forceUpdate=true,$magicq=false)

      +

      Since ADOdb 4.56, you can automatically generate and execute INSERTs and UPDATEs on a given table with this +function, which is a wrapper for GetInsertSQL() and GetUpdateSQL(). +

      AutoExecute() inserts or updates $table given an array of $arrFields, where the keys are the field names and the array values are the +field values to store. Note that there is some overhead because the table is first queried to extract key information +before the SQL is generated. We generate an INSERT or UPDATE based on $mode (see below). +

      +Legal values for $mode are +

        +
      • 'INSERT' or 1 or DB_AUTOQUERY_INSERT +
      • 'UPDATE' or 2 or DB_AUTOQUERY_UPDATE +
      +

      You have to define the constants DB_AUTOQUERY_UPDATE and DB_AUTOQUERY_INSERT yourself or include adodb-pear.inc.php. +

      The $where clause is required if $mode == 'UPDATE'. If $forceUpdate=false then we will query the +database first and check if the field value returned by the query matches the current field value; only if they differ do we update that field. +

      Returns true on success, false on error. +

      An example of its use is:

      -# single field primary key
      -$ret = $db->Replace('atable', 
      -	array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
      -	'id',$autoquote = true);	
      -# generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000
      -# or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')
      +$record["firstName"] = "Carol";
      +$record["lasTname"] = "Smith"; 
      +$conn->AutoExecute($table,$record,'INSERT');
      +# executes "INSERT INTO $table (firstName,lasTname) values ('Carol',Smith')";
       
      -# compound key
      -$ret = $db->Replace('atable2', 
      -	array('firstname'=>'Harun','lastname'=>'Al-Rashid', 'age' => 33, 'birthday' => 'null'),
      -	array('lastname','firstname'),
      -	$autoquote = true);
      -
      -# no auto-quoting
      -$ret = $db->Replace('atable2', 
      -	array('firstname'=>"'Harun'",'lastname'=>"'Al-Rashid'", 'age' => 'null'),
      -	array('lastname','firstname'));	
      +$record["firstName"] = "Carol";
      +$record["lasTname"] = "Jones"; 
      +$conn->AutoExecute($table,$record,'UPDATE', "lastname like 'Sm%'");
      +# executes "UPDATE $table SET firstName='Carol',lasTname='Jones' WHERE lastname like 'Sm%'";
       
      -

      GetUpdateSQL(&$rs, $arrFields, $forceUpdate=false,$magicq=false, $force=null)

      -

      Generate SQL to update a table given a recordset $rs, and the modified fields +

      Note: One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated. If $arrFields +contains keys that are invalid field names for $table, they are ignored. There is some overhead in doing this as we have to +query the database to get the field names, but given that you are not directly coding the SQL yourself, you probably aren't interested in +speed at all, but convenience. +

      Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called. +

      GetUpdateSQL(&$rs, $arrFields, $forceUpdate=false,$magicq=false, $force=null)

      +

      Generate SQL to update a table given a recordset $rs, and the modified fields of the array $arrFields (which must be an associative array holding the column names and the new values) are compared with the current recordset. If $forceUpdate is true, then we also generate the SQL even if $arrFields is identical to $rs->fields. Requires the recordset to be associative. $magicq is used to indicate whether magic quotes are enabled (see qstr()). The field names in the array - are case-insensitive.

      -

      Since 4.52, we allow you to pass the $force type parameter, and this overrides the $ADODB_FORCE_TYPE + are case-insensitive.

      +

      Since 4.52, we allow you to pass the $force type parameter, and this overrides the $ADODB_FORCE_TYPE global variable. -

      GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=false)

      -

      Generate SQL to insert into a table given a recordset $rs. Requires the query +

      Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called. +

      GetInsertSQL(&$rs, $arrFields,$magicq=false,$force_type=false)

      +

      Generate SQL to insert into a table given a recordset $rs. Requires the query to be associative. $magicq is used to indicate whether magic quotes are enabled - (for qstr()). The field names in the array are case-insensitive.

      + (for qstr()). The field names in the array are case-insensitive.

      - Since 2.42, you can pass a table name instead of a recordset into + Since 2.42, you can pass a table name instead of a recordset into GetInsertSQL (in $rs), and it will generate an insert statement for that table. -

      Since 4.52, we allow you to pass the $force type parameter, and this overrides the $ADODB_FORCE_TYPE +

      Since 4.52, we allow you to pass the $force_type parameter, and this overrides the $ADODB_FORCE_TYPE global variable. -

      PageExecute($sql, $nrows, $page, $inputarr=false) -

      Used for pagination of recordset. $page is 1-based. See Example - 8.

      - -

      CachePageExecute($secs2cache, +

      Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called. +

      PageExecute($sql, $nrows, $page, $inputarr=false) +

      Used for pagination of recordset. $page is 1-based. See Example + 8.

      + +

      CachePageExecute($secs2cache, $sql, $nrows, $page, $inputarr=false)

      -

      Used for pagination of recordset. $page is 1-based. See +

      Used for pagination of recordset. $page is 1-based. See Example 8. Caching version of PageExecute.

      - -

      -

      Close( )

      -

      Close the database connection. PHP4 proudly states that we no longer have to + +

      +

      Close( )

      +

      Close the database connection. PHP4 proudly states that we no longer have to clean up at the end of the connection because the reference counting mechanism - of PHP4 will automatically clean up for us.

      -

      StartTrans( )

      -

      Start a monitored transaction. As SQL statements are executed, ADOdb will monitor + of PHP4 will automatically clean up for us.

      +

      StartTrans( )

      +

      Start a monitored transaction. As SQL statements are executed, ADOdb will monitor for SQL errors, and if any are detected, when CompleteTrans() is called, we auto-rollback. -

      -

      To understand why StartTrans() is superior to BeginTrans(), +

      +

      To understand why StartTrans() is superior to BeginTrans(), let us examine a few ways of using BeginTrans(). The following is the wrong way to use transactions: -

      -$DB->BeginTrans();
      -$DB->Execute("update table1 set val=$val1 where id=$id");
      -$DB->Execute("update table2 set val=$val2 where id=$id");
      -$DB->CommitTrans();
      -
      -

      because you perform no error checking. It is possible to update table1 and +

      $DB->BeginTrans();
      $DB->Execute("update table1 set val=$val1 where id=$id");
      $DB->Execute("update table2 set val=$val2 where id=$id");
      $DB->CommitTrans();
      +

      because you perform no error checking. It is possible to update table1 and for the update on table2 to fail. Here is a better way: -

      -$DB->BeginTrans();
      -$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
      -if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
      -if ($ok) $DB->CommitTrans();
      -else $DB->RollbackTrans();
      -
      -

      Another way is (since ADOdb 2.0): -

      -$DB->BeginTrans();
      -$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
      -if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
      -$DB->CommitTrans($ok);
      -
      -

      Now it is a headache monitoring $ok all over the place. StartTrans() is an +

      $DB->BeginTrans();
      $ok = $DB->Execute("update table1 set val=$val1 where id=$id");
      if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
      if ($ok) $DB->CommitTrans();
      else $DB->RollbackTrans();
      +

      Another way is (since ADOdb 2.0): +

      $DB->BeginTrans();
      $ok = $DB->Execute("update table1 set val=$val1 where id=$id");
      if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
      $DB->CommitTrans($ok);
      +

      Now it is a headache monitoring $ok all over the place. StartTrans() is an improvement because it monitors all SQL errors for you. This is particularly useful if you are calling black-box functions in which SQL queries might be executed. Also all BeginTrans, CommitTrans and RollbackTrans calls inside a StartTrans block will be disabled, so even if the black box function does a commit, it will be ignored. -

      -$DB->StartTrans();
      -CallBlackBox();
      -$DB->Execute("update table1 set val=$val1 where id=$id");
      -$DB->Execute("update table2 set val=$val2 where id=$id");
      -$DB->CompleteTrans($ok);
      -
      -

      Note that a StartTrans blocks are nestable, the inner blocks are ignored. -

      CompleteTrans($autoComplete=true)

      -

      Complete a transaction called with StartTrans(). This function monitors +

      $DB->StartTrans();
      CallBlackBox();
      $DB->Execute("update table1 set val=$val1 where id=$id");
      $DB->Execute("update table2 set val=$val2 where id=$id");
      $DB->CompleteTrans($ok);
      +

      Note that a StartTrans blocks are nestable, the inner blocks are ignored. +

      CompleteTrans($autoComplete=true)

      +

      Complete a transaction called with StartTrans(). This function monitors for SQL errors, and will commit if no errors have occured, otherwise it will rollback. Returns true on commit, false on rollback. If the parameter $autoComplete is true monitor sql errors and commit and rollback as appropriate. Set $autoComplete to false to force rollback even if no SQL error detected. -

      FailTrans( )

      -

      Fail a transaction started with StartTrans(). The rollback will only occur when +

      FailTrans( )

      +

      Fail a transaction started with StartTrans(). The rollback will only occur when CompleteTrans() is called. -

      HasFailedTrans( )

      -

      Check whether smart transaction has failed, +

      HasFailedTrans( )

      +

      Check whether smart transaction has failed, eg. returns true if there was an error in SQL execution or FailTrans() was called. If not within smart transaction, returns false. -

      BeginTrans( )

      -

      Begin a transaction. Turns off autoCommit. Returns true if successful. Some +

      BeginTrans( )

      +

      Begin a transaction. Turns off autoCommit. Returns true if successful. Some databases will always return false if transaction support is not available. Any open transactions will be rolled back when the connection is closed. Among the databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain - versions of MySQL, DB2, Informix, Sybase, etc.

      -

      Note that StartTrans() and CompleteTrans() is a superior method of - handling transactions, available since ADOdb 3.40. For a explanation, see the StartTrans() documentation. + versions of MySQL, DB2, Informix, Sybase, etc.

      +

      Note that StartTrans() and CompleteTrans() is a superior method of + handling transactions, available since ADOdb 3.40. For a explanation, see the StartTrans() documentation. -

      You can also use the ADOdb error handler to die +

      You can also use the ADOdb error handler to die and rollback your transactions for you transparently. Some buggy database extensions are known to commit all outstanding tranasactions, so you might want to explicitly - do a $DB->RollbackTrans() in your error handler for safety. -

      Detecting Transactions

      -

      Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check - that $connection->transCnt > 0. This variable is incremented whenever BeginTrans() is called, + do a $DB->RollbackTrans() in your error handler for safety. +

      Detecting Transactions

      +

      Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check + that $connection->transCnt > 0. This variable is incremented whenever BeginTrans() is called, and decremented whenever RollbackTrans() or CommitTrans() is called. -

      CommitTrans($ok=true)

      -

      End a transaction successfully. Returns true if successful. If the database +

      CommitTrans($ok=true)

      +

      End a transaction successfully. Returns true if successful. If the database does not support transactions, will return true also as data is always committed. -

      -

      If you pass the parameter $ok=false, the data is rolled back. See example in - BeginTrans().

      -

      RollbackTrans( )

      -

      End a transaction, rollback all changes. Returns true if successful. If the +

      +

      If you pass the parameter $ok=false, the data is rolled back. See example in + BeginTrans().

      +

      RollbackTrans( )

      +

      End a transaction, rollback all changes. Returns true if successful. If the database does not support transactions, will return false as data is never rollbacked. -

      - -

      GetAssoc($sql,$inputarr=false,$force_array=false,$first2cols=false)

      -

      Returns an associative array for the given query $sql with optional bind parameters +

      + +

      GetAssoc($sql,$inputarr=false,$force_array=false,$first2cols=false)

      +

      Returns an associative array for the given query $sql with optional bind parameters in $inputarr. If the number of columns returned is greater to two, a 2-dimensional array is returned, with the first column of the recordset becomes the keys to the rest of the rows. If the columns is equal to two, a 1-dimensional array is created, where the the keys directly map to the values (unless $force_array is set to true, when an array is created for each value). -

      Examples:

      - -

      We have the following data in a recordset:

      -

      row1: Apple, Fruit, Edible
      +

      Examples:

      + +

      We have the following data in a recordset:

      +

      row1: Apple, Fruit, Edible
      row2: Cactus, Plant, Inedible
      row3: Rose, Flower, Edible

      -

      GetAssoc will generate the following 2-dimensional associative +

      GetAssoc will generate the following 2-dimensional associative array:

      -

      Apple => array[Fruit, Edible]
      +

      Apple => array[Fruit, Edible]
      Cactus => array[Plant, Inedible]
      Rose => array[Flower,Edible]

      -

      If the dataset is:

      -

      row1: Apple, - Fruit
      - row2: Cactus, Plant
      - row3: Rose, Flower

      -

      GetAssoc will generate the following - 1-dimensional associative array (with $force_array==false):

      -

      Apple => Fruit
      +

      If the dataset is:

      +

      row1: Apple, Fruit
      +row2: Cactus, Plant
      +row3: Rose, Flower

      +

      GetAssoc will generate the following 1-dimensional associative + array (with $force_array==false):

      +

      Apple => Fruit
      Cactus=>Plant
      - Rose=>Flower

      -

      The function returns:

      -

      The associative array, or false if an error occurs.

      - + Rose=>Flower

      +

      The function returns:

      +

      The associative array, or false if an error occurs.

      +

      CacheGetAssoc([$secs2cache,] $sql,$inputarr=false,$force_array=false,$first2cols=false)

      -
      -

      Caching version of GetAssoc function above. -

      GetOne($sql,$inputarr=false)

      -

      Executes the SQL and returns the first field of the first row. The recordset - and remaining rows are discarded for you automatically. If an error occur, false - is returned.

      -

      GetRow($sql,$inputarr=false)

      -

      Executes the SQL and returns the first row as an array. The recordset and remaining - rows are discarded for you automatically. If an error occurs, false is returned.

      -

      GetAll($sql)

      -

      Executes the SQL and returns the all the rows as a 2-dimensional +

      Caching version of GetAssoc function above. +

      GetOne($sql,$inputarr=false)

      +

      Executes the SQL and returns the first field of the first row. The recordset + and remaining rows are discarded for you automatically. If an error occur, false + is returned.

      +

      GetRow($sql,$inputarr=false)

      +

      Executes the SQL and returns the first row as an array. The recordset and remaining + rows are discarded for you automatically. If an error occurs, false is returned.

      +

      GetAll($sql,$inputarr=false)

      + +

      Executes the SQL and returns the all the rows as a 2-dimensional array. The recordset is discarded for you automatically. If an error occurs, - false is returned.

      + false is returned. GetArray is a synonym for GetAll.

      GetCol($sql,$inputarr=false,$trim=false)

      -

      Executes the SQL and returns all elements of the first column as a +

      Executes the SQL and returns all elements of the first column as a 1-dimensional array. The recordset is discarded for you automatically. If an error occurs, false is returned.

      -

      CacheGetOne([$secs2cache,] +

      CacheGetOne([$secs2cache,] $sql,$inputarr=false), CacheGetRow([$secs2cache,] $sql,$inputarr=false), CacheGetAll([$secs2cache,] $sql,$inputarr=false), CacheGetCol([$secs2cache,] $sql,$inputarr=false,$trim=false)

      - -

      Similar to above Get* functions, except that the recordset is serialized and + +

      Similar to above Get* functions, except that the recordset is serialized and cached in the $ADODB_CACHE_DIR directory for $secs2cache seconds. Good for speeding up queries on rarely changing data. Note that the $secs2cache parameter is optional. If omitted, we use the value in $connection->cacheSecs (default is 3600 seconds, - or 1 hour).

      -

      Prepare($sql )

      -
      -

      Prepares (compiles) an SQL query for repeated execution. Bind parameters + or 1 hour).

      +

      Prepare($sql )

      + +

      Prepares (compiles) an SQL query for repeated execution. Bind parameters are denoted by ?, except for the oci8 driver, which uses the traditional Oracle :varname convention.

      -

      Returns an array containing the original sql statement +

      Returns an array containing the original sql statement in the first array element; the remaining elements of the array are driver dependent. If there is an error, or we are emulating Prepare( ), we return the original $sql string. This is because all error-handling has been centralized in Execute( ).

      -

      Prepare( ) cannot be used with functions that use SQL +

      Prepare( ) cannot be used with functions that use SQL query rewriting techniques, e.g. PageExecute( ) and SelectLimit( ).

      Example:

      -
      $stmt = $DB->Prepare('insert into table (col1,col2) values (?,?)');
      -for ($i=0; $i < $max; $i++)
      $DB->Execute($stmt,array((string) rand(), $i)); -
      - -

      Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase, +

      $stmt = $DB->Prepare('insert into table (col1,col2) values (?,?)');
      for ($i=0; $i < $max; $i++)
      $DB->Execute($stmt,array((string) rand(), $i));
      + +

      Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase, oci8 and selected ODBC-based drivers, otherwise it is emulated. There is no performance advantage to using Prepare() with emulation. -

      Important: Due to limitations or bugs in PHP, if you are getting errors when +

      Important: Due to limitations or bugs in PHP, if you are getting errors when you using prepared queries, try setting $ADODB_COUNTRECS = false before preparing. This behaviour has been observed with ODBC. -

      IfNull($field, $nullReplacementValue)

      -

      Portable IFNULL function (NVL in Oracle). Returns a string that represents +

      IfNull($field, $nullReplacementValue)

      +

      Portable IFNULL function (NVL in Oracle). Returns a string that represents the function that checks whether a $field is null for the given database, and - if null, change the value returned to $nullReplacementValue. Eg.

      -
      $sql = 'SELECT '.$db->IfNull('name', "'- unknown -'"). ' FROM table';
      + if null, change the value returned to $nullReplacementValue. Eg.

      +
      $sql = 'SELECT '.$db->IfNull('name', "'- unknown -'"). ' FROM table';
      -

      length

      -

      This is not a function, but a property. Some databases have "length" and others "len" +

      length

      +

      This is not a function, but a property. Some databases have "length" and others "len" as the function to measure the length of a string. To use this property: -

      -  $sql = "SELECT ".$db->length."(field) from table";
      -  $rs = $db->Execute($sql);
      -
      +

        $sql = "SELECT ".$db->length."(field) from table";
      $rs = $db->Execute($sql);
      -

      random

      -

      This is not a function, but a property. This is a string that holds the sql to +

      random

      +

      This is not a function, but a property. This is a string that holds the sql to generate a random number between 0.0 and 1.0 inclusive. -

      substr

      -

      This is not a function, but a property. Some databases have "substr" and others "substring" +

      substr

      +

      This is not a function, but a property. Some databases have "substr" and others "substring" as the function to retrieve a sub-string. To use this property: -

      -  $sql = "SELECT ".$db->substr."(field, $offset, $length) from table";
      -  $rs = $db->Execute($sql);
      -
      -

      For all databases, the 1st parameter of substr is the field, the 2nd is the +

        $sql = "SELECT ".$db->substr."(field, $offset, $length) from table";
      $rs = $db->Execute($sql);
      +

      For all databases, the 1st parameter of substr is the field, the 2nd is the offset (1-based) to the beginning of the sub-string, and the 3rd is the length of the sub-string. -

      Param($name)

      -

      Generates a bind placeholder portably. For most databases, the bind placeholder +

      Param($name)

      +

      Generates a bind placeholder portably. For most databases, the bind placeholder is "?". However some databases use named bind parameters such as Oracle, eg ":somevar". This allows us to portably define an SQL statement with bind parameters: -

      $sql = 'insert into table (col1,col2) values ('.$DB->Param('a').','.$DB->Param('b').')';
      -# generates 'insert into table (col1,col2) values (?,?)'
      -# or        'insert into table (col1,col2) values (:a,:b)'
      -$stmt = $DB->Prepare($sql);
      -$stmt = $DB->Execute($stmt,array('one','two'));
      -
      - +

      $sql = 'insert into table (col1,col2) values ('.$DB->Param('a').','.$DB->Param('b').')';
      # generates 'insert into table (col1,col2) values (?,?)'
      # or 'insert into table (col1,col2) values (:a,:b)
      '
      $stmt = $DB->Prepare($sql);
      $stmt = $DB->Execute($stmt,array('one','two'));
      +

      -

      PrepareSP($sql, $cursor=false )

      -

      When calling stored procedures in mssql and oci8 (oracle), and you might want - to directly bind to parameters that return values, or for special LOB handling. - PrepareSP() allows you to do so. -

      Returns the same array or $sql string as Prepare( ) above. If you do not need - to bind to return values, you should use Prepare( ) instead.

      -

      The 2nd parameter, $cursor is not used except with oci8. Setting it to true will -force OCINewCursor to be called; this is to support output REF CURSORs. -

      For examples of usage of PrepareSP( ), see InParameter( ) below. -

      Note: in the mssql driver, preparing stored procedures requires a special function - call, mssql_init( ), which is called by this function. PrepareSP( ) is available - in all other drivers, and is emulated by calling Prepare( ).

      -

      InParameter($stmt, $var, $name, - $maxLen = 4000, $type = false )

      -Binds a PHP variable as input to a stored procedure variable. The parameter $stmt - is the value returned by PrepareSP(), $var is the PHP variable you want to bind, $name - is the name of the stored procedure variable. Optional is $maxLen, the maximum length of the - data to bind, and $type which is database dependant. - Consult mssql_bind and ocibindbyname docs - at php.net for more info on legal values for $type. -

      -InParameter() is a wrapper function that calls Parameter() with $isOutput=false. -The advantage of this function is that it is self-documenting, because -the $isOutput parameter is no longer needed. Only for mssql - and oci8 currently. -

      Here is an example using oci8: -

      # For oracle, Prepare and PrepareSP are identical
      +

      PrepareSP($sql, +$cursor=false )

      +

      When calling stored procedures in mssql and oci8 (oracle), + and you might want to directly bind to parameters that return values, or +for special LOB handling. PrepareSP() allows you to do so.

      +

      Returns the same array or $sql string as Prepare( ) + above. If you do not need to bind to return values, you should use Prepare( + ) instead.

      +

      The 2nd parameter, $cursor is not used except with oci8. + Setting it to true will force OCINewCursor to be called; this is to support +output REF CURSORs.

      +

      For examples of usage of PrepareSP( ), see InParameter( +) below.

      +

      Note: in the mssql driver, preparing stored procedures + requires a special function call, mssql_init( ), which is called by this + function. PrepareSP( ) is available in all other drivers, and is emulated + by calling Prepare( ).

      +

      InParameter($stmt, $var, + $name, $maxLen = 4000, $type = false )

      +Binds a PHP variable as input to a stored procedure variable. +The parameter $stmt is the value returned by PrepareSP(), $var is +the PHP variable you want to bind, $name is the name of the stored procedure +variable. Optional is $maxLen, the maximum length of the data to bind, +and $type which is database dependant. Consult mssql_bind and ocibindbyname docs +at php.net for more info on legal values for $type. +

      +InParameter() is a wrapper function that calls Parameter() +with $isOutput=false. The advantage of this function is that it is self-documenting, +because the $isOutput parameter is no longer needed. Only for mssql and oci8 +currently.

      +

      Here is an example using oci8:

      +
      # For oracle, Prepare and PrepareSP are identical
       $stmt = $db->PrepareSP(
      -	"declare RETVAL integer; 
      -	begin
      -	:RETVAL := SP_RUNSOMETHING(:myid,:group);
      -	end;");
      -$db->InParameter($stmt,$id,'myid');
      -$db->InParameter($stmt,$group,'group',64);
      -$db->OutParameter($stmt,$ret,'RETVAL');
      $db->Execute($stmt); -
      -

      The same example using mssql:

      -
      -
      # @RETVAL = SP_RUNSOMETHING @myid,@group
      +	"declare RETVAL integer; 
      begin
      :RETVAL :=
      SP_RUNSOMETHING(:myid,:group);
      end;"
      );
      $db->InParameter($stmt,$id,'myid');
      $db->InParameter($stmt,$group,'group',64);
      $db->OutParameter($stmt,$ret,'RETVAL');
      $db->Execute($stmt);
      +

      The same example using mssql:

      + +
      # @RETVAL = SP_RUNSOMETHING @myid,@group
       $stmt = $db->PrepareSP('SP_RUNSOMETHING'); 
      # note that the parameter name does not have @ in front! $db->InParameter($stmt,$id,'myid'); $db->InParameter($stmt,$group,'group',64); -# return value in mssql - RETVAL is hard-coded name -$db->OutParameter($stmt,$ret,'RETVAL'); -$db->Execute($stmt);
      +# return value in mssql - RETVAL is hard-coded name
      $db->OutParameter($stmt,$ret,'RETVAL');
      $db->Execute($stmt);
      -

      Note that the only difference between the oci8 and mssql implementations is $sql.

      -

      - If $type parameter is set to false, in mssql, $type will be dynamicly determined +

      Note that the only difference between the oci8 and mssql implementations is $sql.

      +

      + If $type parameter is set to false, in mssql, $type will be dynamicly determined based on the type of the PHP variable passed (string => SQLCHAR, boolean =>SQLINT1, integer =>SQLINT4 or float/double=>SQLFLT8). -

      +

      In oci8, $type can be set to OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). To pass in a null, use $db->Parameter($stmt, $null=null, 'param'). -

      OutParameter($stmt, $var, $name, - $maxLen = 4000, $type = false )

      - Binds a PHP variable as output from a stored procedure variable. The parameter $stmt +

      OutParameter($stmt, $var, $name, + $maxLen = 4000, $type = false )

      + Binds a PHP variable as output from a stored procedure variable. The parameter $stmt is the value returned by PrepareSP(), $var is the PHP variable you want to bind, $name is the name of the stored procedure variable. Optional is $maxLen, the maximum length of the data to bind, and $type which is database dependant. -

      - OutParameter() is a wrapper function that calls Parameter() with $isOutput=true. +

      + OutParameter() is a wrapper function that calls Parameter() with $isOutput=true. The advantage of this function is that it is self-documenting, because the $isOutput parameter is no longer needed. Only for mssql and oci8 currently. -

      -For an example, see InParameter. +

      +For an example, see InParameter. -

      Parameter($stmt, $var, $name, $isOutput=false, - $maxLen = 4000, $type = false )

      -

      Note: This function is deprecated, because of the new InParameter() and OutParameter() functions. +

      Parameter($stmt, $var, $name, $isOutput=false, + $maxLen = 4000, $type = false )

      +

      Note: This function is deprecated, because of the new InParameter() and OutParameter() functions. These are superior because they are self-documenting, unlike Parameter(). -

      Adds a bind parameter suitable for return values or special data handling (eg. +

      Adds a bind parameter suitable for return values or special data handling (eg. LOBs) after a statement has been prepared using PrepareSP(). Only for mssql and oci8 currently. The parameters are:

      @@ -2599,22 +2190,17 @@ These are superior because they are self-documenting, unlike Parameter(). [$maxLen] Maximum length of the parameter variable.
      [$type] Consult mssql_bind and ocibindbyname docs at php.net for - more info on legal values for type.

      -

      Lastly, in oci8, bind parameters can be reused without calling PrepareSP( ) - or Parameters again. This is not possible with mssql. An oci8 example:

      -
      $id = 0; $i = 0;
      -$stmt = $db->PrepareSP( "update table set val=:i where id=:id");
      -$db->Parameter($stmt,$id,'id');
      -$db->Parameter($stmt,$i, 'i');
      -for ($cnt=0; $cnt < 1000; $cnt++) {
      -	$id = $cnt; 
      $i = $cnt * $cnt; # works with oci8! - $db->Execute($stmt);
      }
      -

      Bind($stmt, $var, $size=4001, $type=false, $name=false)

      -
      -

      This is a low-level function supported only by the oci8 + more info on legal values for type.

      +

      Lastly, in oci8, bind parameters can be reused without calling PrepareSP( ) + or Parameters again. This is not possible with mssql. An oci8 example:

      +
      $id = 0; $i = 0;
      $stmt = $db->PrepareSP( "update table set val=:i where id=:id");
      $db->Parameter($stmt,$id,'id');
      $db->Parameter($stmt,$i, 'i');
      for ($cnt=0; $cnt < 1000; $cnt++) {
      $id = $cnt;
      $i = $cnt * $cnt; # works with oci8! + $db->Execute($stmt);
      }
      +

      Bind($stmt, $var, $size=4001, $type=false, $name=false)

      + +

      This is a low-level function supported only by the oci8 driver. Avoid using unless you only want to support Oracle. The Parameter( ) function is the recommended way to go with bind variables.

      -

      Bind( ) allows you to use bind variables in your sql +

      Bind( ) allows you to use bind variables in your sql statement. This binds a PHP variable to a name defined in an Oracle sql statement that was previously prepared using Prepare(). Oracle named variables begin with a colon, and ADOdb requires the named variables be called :0, :1, :2, :3, etc. @@ -2626,35 +2212,19 @@ for ($cnt=0; $cnt < 1000; $cnt++) { OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). Lastly, instead of using the default :0, :1, etc names, you can define your own bind-name using $name. -

      The following example shows 3 bind variables being used: +

      The following example shows 3 bind variables being used: p1, p2 and p3. These variables are bound to :0, :1 and :2.

      -
      $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);
      -}
      +
      $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);
      }

      You can also use named variables:

      -
      -$stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:name0, :name1, :name2)");
      -$DB->Bind($stmt, $p1, "name0");
      -$DB->Bind($stmt, $p2, "name1");
      -$DB->Bind($stmt, $p3, "name2");
      -for ($i = 0; $i < $max; $i++) { 
      -   $p1 = ?; $p2 = ?; $p3 = ?;
      -   $DB->Execute($stmt);
      -}
      -

      LogSQL($enable=true)

      +
      $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:name0, :name1, :name2)");
      $DB->Bind($stmt, $p1, "name0");
      $DB->Bind($stmt, $p2, "name1");
      $DB->Bind($stmt, $p3, "name2");
      for ($i = 0; $i < $max; $i++) {
      $p1 = ?; $p2 = ?; $p3 = ?;
      $DB->Execute($stmt);
      }
      +

      LogSQL($enable=true)

      Call this method to install a SQL logging and timing function (using fnExecute). Then all SQL statements are logged into an adodb_logsql table in a database. If the adodb_logsql table does not exist, ADOdb will create the table if you have the appropriate permissions. Returns the previous logging value (true for enabled, false for disabled). Here are samples of the DDL for selected databases:

      -

      -		mysql:
      +

      		mysql:
       		CREATE TABLE adodb_logsql (
       		  created datetime NOT NULL,
       		  sql0 varchar(250) NOT NULL,
      @@ -2695,34 +2265,19 @@ false for disabled). Here are samples of the DDL for selected databases:
       		)
       
      Usage: -
      -	$conn->LogSQL(); // turn on logging
      -	  :
      -	$conn->Execute(...);
      -	  :
      -	$conn->LogSQL(false); // turn off logging
      -	
      -	# output summary of SQL logging results
      -	$perf = NewPerfMonitor($conn);
      -	echo $perf->SuspiciousSQL();
      -	echo $perf->ExpensiveSQL();
      -
      +
      	$conn->LogSQL(); // turn on logging
      :
      $conn->Execute(...);
      :
      $conn->LogSQL(false); // turn off logging

      # output summary of SQL logging results
      $perf = NewPerfMonitor($conn);
      echo $perf->SuspiciousSQL();
      echo $perf->ExpensiveSQL();

      One limitation of logging is that rollback also prevents SQL from being logged. -

      +

      If you prefer to use another name for the table used to store the SQL, you can override it by calling adodb_perf::table($tablename), where $tablename is the new table name (you will still need to manually create the table yourself). An example: -

      -	include('adodb.inc.php');
      -	include('adodb-perf.inc.php');
      -	adodb_perf::table('my_logsql_table');
      -
      -Also see Performance Monitor. -

      fnExecute and fnCacheExecute properties

      +

      	include('adodb.inc.php');
      include('adodb-perf.inc.php');
      adodb_perf::table('my_logsql_table');
      +Also see Performance Monitor. +

      fnExecute and fnCacheExecute properties

      These two properties allow you to define bottleneck functions for all sql statements processed by ADOdb. This allows you to perform statistical analysis and query-rewriting of your sql. -

      Examples of fnExecute

      +

      Examples of fnExecute

      Here is an example of using fnExecute, to count all cached queries and non-cached queries, you can do this:

      # $db is the connection object
      @@ -2738,969 +2293,977 @@ else $EXECS++;
       
       # $db is the connection object
       function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
      -{
      global $CACHED; $CACHED++; -} -
      $db = NewADOConnection('mysql'); -$db->Connect(...); -$db->fnExecute = 'CountExecs'; -$db->fnCacheExecute = 'CountCachedExecs'; - : - :
      # After many sql statements:` -printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED); -
      +{
      global $CACHED; $CACHED++;
      }

      $db = NewADOConnection('mysql');
      $db->Connect(...);
      $db->fnExecute = 'CountExecs';
      $db->fnCacheExecute = 'CountCachedExecs';
      :
      :
      # After many sql statements:`
      printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);

      The fnExecute function is called before the sql is parsed and executed, so you can perform a query rewrite. If you are passing in a prepared statement, then $sql is an array (see Prepare). The fnCacheExecute - function is only called if the recordset returned was cached. + function is only called if the recordset returned was cached. The function parameters match the Execute and CacheExecute functions respectively, except that $this (the connection object) is passed as the first parameter.

      Since ADOdb 3.91, the behaviour of fnExecute varies depending on whether the defined function returns a value. If it does not return a value, then the $sql is executed as before. This is useful for query rewriting or counting sql queries. -

      On the other hand, you might want to replace the Execute function with one +

      On the other hand, you might want to replace the Execute function with one of your own design. If this is the case, then have your function return a value. If a value is returned, that value is returned immediately, without any further processing. This is used internally by ADOdb to implement LogSQL() functionality. -

      -


      -

      ADOConnection Utility Functions

      -

      BlankRecordSet([$queryid])

      -

      No longer available - removed since 1.99.

      -

      Concat($s1,$s2,....)

      -

      Generates the sql string used to concatenate $s1, $s2, etc together. Uses the +

      +

      +


      +

      ADOConnection Utility Functions

      +

      BlankRecordSet([$queryid])

      +

      No longer available - removed since 1.99.

      +

      Concat($s1,$s2,....)

      +

      Generates the sql string used to concatenate $s1, $s2, etc together. Uses the string in the concat_operator field to generate the concatenation. Override - this function if a concatenation operator is not used, eg. MySQL.

      -

      Returns the concatenated string.

      -

      DBDate($date)

      -

      Format the $date in the format the database accepts. This is used in + this function if a concatenation operator is not used, eg. MySQL.

      +

      Returns the concatenated string.

      +

      DBDate($date)

      +

      Format the $date in the format the database accepts. This is used in INSERT/UPDATE statements; for SELECT statements, use SQLDate. The $date parameter can be a Unix integer timestamp or an ISO format Y-m-d. Uses the fmtDate field, which holds the format to use. If null or false - or '' is passed in, it will be converted to an SQL null.

      -

      Returns the date as a quoted string.

      -

      DBTimeStamp($ts)

      -

      Format the timestamp $ts in the format the database accepts; this can + or '' is passed in, it will be converted to an SQL null.

      +

      Returns the date as a quoted string.

      +

      DBTimeStamp($ts)

      +

      Format the timestamp $ts in the format the database accepts; this can be a Unix integer timestamp or an ISO format Y-m-d H:i:s. Uses the fmtTimeStamp field, which holds the format to use. If null or false or '' is passed in, it - will be converted to an SQL null.

      -

      Returns the timestamp as a quoted string.

      -

      qstr($s,[$magic_quotes_enabled=false])

      -

      Quotes a string to be sent to the database. The $magic_quotes_enabled + will be converted to an SQL null.

      +

      Returns the timestamp as a quoted string.

      +

      qstr($s,[$magic_quotes_enabled=false])

      +

      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());

      -

      Returns the quoted string.

      -

      Quote($s)

      -

      Quotes the string $s, escaping the database specific quote character as appropriate. + and once by the magic_quotes_gpc.

      +

      Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());

      +

      Returns the quoted string.

      +

      Quote($s)

      +

      Quotes the string $s, escaping the database specific quote character as appropriate. Formerly checked magic quotes setting, but this was disabled since 3.31 for compatibility with PEAR DB. -

      Affected_Rows( )

      -

      Returns the number of rows affected by a update or delete statement. Returns - false if function not supported.

      -

      Not supported by interbase/firebird currently.

      -

      Insert_ID( )

      -

      Returns the last autonumbering ID inserted. Returns false if function not supported. -

      -

      Only supported by databases that support auto-increment or object id's, such +

      Affected_Rows( )

      +

      Returns the number of rows affected by a update or delete statement. Returns + false if function not supported.

      +

      Not supported by interbase/firebird currently.

      +

      Insert_ID( )

      +

      Returns the last autonumbering ID inserted. Returns false if function not supported. +

      +

      Only supported by databases that support auto-increment or object id's, such as PostgreSQL, MySQL and MS SQL Server currently. PostgreSQL returns the OID, which - can change on a database reload.

      -

      RowLock($table,$where)

      -

      Lock a table row for the duration of a transaction. For example to lock record $id in table1: -

      -	$DB->StartTrans();
      -	$DB->RowLock("table1","rowid=$id");
      -	$DB->Execute($sql1);
      -	$DB->Execute($sql2);
      -	$DB->CompleteTrans();
      -
      -

      Supported in db2, interbase, informix, mssql, oci8, postgres, sybase. -

      MetaDatabases()

      -

      Returns a list of databases available on the server as an array. You have to - connect to the server first. Only available for ODBC, MySQL and ADO.

      -

      MetaTables($ttype = false, $showSchema = false, - $mask=false)

      -

      Returns an array of tables and views for the current database as an array. + can change on a database reload.

      +

      RowLock($table,$where)

      +

      Lock a table row for the duration of a transaction. For example to lock record $id in table1: +

      	$DB->StartTrans();
      $DB->RowLock("table1","rowid=$id");
      $DB->Execute($sql1);
      $DB->Execute($sql2);
      $DB->CompleteTrans();
      +

      Supported in db2, interbase, informix, mssql, oci8, postgres, sybase. +

      MetaDatabases()

      +

      Returns a list of databases available on the server as an array. You have to + connect to the server first. Only available for ODBC, MySQL and ADO.

      +

      MetaTables($ttype = false, $showSchema = false, + $mask=false)

      +

      Returns an array of tables and views for the current database as an array. The array should exclude system catalog tables if possible. To only show tables, - use $db->MetaTables('TABLES'). To show only views, use $db->MetaTables('VIEWS'). + use $db->MetaTables('TABLES'). To show only views, use $db->MetaTables('VIEWS'). The $showSchema parameter currently works only for DB2, and when set to true, - will add the schema name to the table, eg. "SCHEMA.TABLE".

      -

      You can define a mask for matching. For example, setting $mask = 'TMP%' will + will add the schema name to the table, eg. "SCHEMA.TABLE".

      +

      You can define a mask for matching. For example, setting $mask = 'TMP%' will match all tables that begin with 'TMP'. Currently only mssql, oci8, odbc_mssql and postgres* support $mask. -

      MetaColumns($table,$toupper=true)

      -

      Returns an array of ADOFieldObject's, one field object for every column of +

      MetaColumns($table,$toupper=true)

      +

      Returns an array of ADOFieldObject's, one field object for every column of $table. A field object is a class instance with (name, type, max_length) defined. Currently Sybase does not recognise date types, and ADO cannot identify the correct data type (so we default to varchar). -

      The $toupper parameter determines whether we uppercase the table name +

      The $toupper parameter determines whether we uppercase the table name (required for some databases). -

      For schema support, pass in the $table parameter, "$schema.$tablename". This is only +

      For schema support, pass in the $table parameter, "$schema.$tablename". This is only supported for selected databases. -

      MetaColumnNames($table,$numericIndex=false)

      -

      Returns an array of column names for $table. Since ADOdb 4.22, this is an associative array, with the +

      MetaColumnNames($table,$numericIndex=false)

      +

      Returns an array of column names for $table. Since ADOdb 4.22, this is an associative array, with the keys in uppercase. Set $numericIndex=true if you want the old behaviour of numeric indexes (since 4.23). -

      -e.g. array('FIELD1' => 'Field1', 'FIELD2'=>'Field2') -

      -

      MetaPrimaryKeys($table, - $owner=false) -

      Returns an array containing column names that are the +

      +e.g. array('FIELD1' => 'Field1', 'FIELD2'=>'Field2') +

      +

      MetaPrimaryKeys($table, + $owner=false) +

      +

      Returns an array containing column names that are the primary keys of $table. Supported by mysql, odbc (including db2, odbc_mssql, - etc), mssql, postgres, interbase/firebird, oci8 currently. -

      Views (and some tables) have primary keys, but sometimes this information is not available from the +etc), mssql, postgres, interbase/firebird, oci8 currently.

      +

      Views (and some tables) have primary keys, but sometimes this information is not available from the database. You can define a function ADODB_View_PrimaryKeys($databaseType, $database, $view, $owner) that should return an array containing the fields that make up the primary key. If that function exists, it will be called when MetaPrimaryKeys() cannot find a primary key for a table or view. -

      -// In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false 
      -function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)
      -{
      -	switch(strtoupper($view)) {
      -	case 'DATAVIEW': return array('DATAID');
      -	default: return false;
      -	}
      -}
      -
      -$db = NewADOConnection('oci8');
      -$db->Connect('localhost','root','','mydb'); 
      -$db->MetaPrimaryKeys('dataView');
      -
      -

      ServerInfo($table) -

      Returns an array of containing two elements 'description' +

      // In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false 
      function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)
      {
      switch(strtoupper($view)) {
      case 'DATAVIEW': return array('DATAID');
      default: return false;
      }
      }

      $db = NewADOConnection('oci8');
      $db->Connect('localhost','root','','mydb');
      $db->MetaPrimaryKeys('dataView');
      +

      ServerInfo($table) +

      +

      Returns an array of containing two elements 'description' and 'version'. The 'description' element contains the string description of the database. The 'version' naturally holds the version number (which is also - a string). -

      MetaForeignKeys($table, $owner=false, $upper=false) -

      Returns an associate array of foreign keys, or false if not supported. For +a string).

      +

      MetaForeignKeys($table, $owner=false, $upper=false) +

      Returns an associate array of foreign keys, or false if not supported. For example, if table employee has a foreign key where employee.deptkey points to dept_table.deptid, and employee.posn=posn_table.postionid and employee.poscategory=posn_table.category, - then $conn->MetaForeignKeys('employee') will return -

      -	array(
      -		'dept_table' => array('deptkey=deptid'),
      -		'posn_table' => array('posn=positionid','poscategory=category')
      -	)
      -
      -

      The optional schema or owner can be defined in $owner. If $upper is true, then + then $conn->MetaForeignKeys('employee') will return +

      	array(
      'dept_table' => array('deptkey=deptid'),
      'posn_table' => array('posn=positionid','poscategory=category')
      )
      +

      The optional schema or owner can be defined in $owner. If $upper is true, then the table names (array keys) are upper-cased. -


      -

      ADORecordSet

      -

      When an SQL statement successfully is executed by ADOConnection->Execute($sql),an +


      +

      ADORecordSet

      +

      When an SQL statement successfully is executed by ADOConnection->Execute($sql),an ADORecordSet object is returned. This object contains a virtual cursor so we can move from row to row, functions to obtain information about the columns and column types, and helper functions to deal with formating the results to - show to the user.

      -

      ADORecordSet Fields

      -

      fields: Array containing the current row. This is not associative, but + show to the user.

      +

      ADORecordSet Fields

      +

      fields: Array containing the current row. This is not associative, but is an indexed array from 0 to columns-1. See also the function Fields, - which behaves like an associative array.

      -

      dataProvider: The underlying mechanism used to connect to the database. - Normally set to native, unless using odbc or ado.

      -

      blobSize: Maximum size of a char, string or varchar object before it + which behaves like an associative array.

      +

      dataProvider: The underlying mechanism used to connect to the database. + Normally set to native, unless using odbc or ado.

      +

      blobSize: Maximum size of a char, string or varchar object before it is treated as a Blob (Blob's should be shown with textarea's). See the MetaType - function.

      -

      sql: Holds the sql statement used to generate this record set.

      -

      canSeek: Set to true if Move( ) function works.

      -

      EOF: True if we have scrolled the cursor past the last record.

      -

      ADORecordSet Functions

      -

      ADORecordSet( )

      -

      Constructer. Normally you never call this function yourself.

      -

      GetAssoc([$force_array])

      -

      Generates an associative array from the recordset. Note that is this function + function.

      +

      sql: Holds the sql statement used to generate this record set.

      +

      canSeek: Set to true if Move( ) function works.

      +

      EOF: True if we have scrolled the cursor past the last record.

      +

      ADORecordSet Functions

      +

      ADORecordSet( )

      +

      Constructer. Normally you never call this function yourself.

      +

      GetAssoc([$force_array])

      +

      Generates an associative array from the recordset. Note that is this function is also available in the connection object. More details - can be found there.

      -
      -

      GetArray([$number_of_rows])

      -

      Generate a 2-dimensional array of records from the current cursor position, - indexed from 0 to $number_of_rows - 1. If $number_of_rows is undefined, till - EOF.

      -

      GetRows([$number_of_rows])

      -Generate a 2-dimensional array of records from the current cursor position. Synonym -for GetArray() for compatibility with Microsoft ADO. -

      GetMenu($name, [$default_str=''], [$blank1stItem=true], - [$multiple_select=false], [$size=0], [$moreAttr=''])

      -

      Generate a HTML menu (<select><option><option></select>). - The first column of the recordset (fields[0]) will hold the string to display - in the option tags. If the recordset has more than 1 column, the second column - (fields[1]) is the value to send back to the web server.. The menu will be given - the name $name. -

      If $default_str is defined, then if $default_str == fields[0], - that field is selected. If $blank1stItem is true, the first option is - empty. You can also set the first option strings by setting $blank1stItem = - "$value:$text".

      -

      $Default_str can be array for a multiple select listbox.

      -

      To get a listbox, set the $size to a non-zero value (or pass $default_str - as an array). If $multiple_select is true then a listbox will be generated - with $size items (or if $size==0, then 5 items) visible, and we will - return an array to a server. Lastly use $moreAttr to add additional - attributes such as javascript or styles.

      -

      Menu Example 1: GetMenu('menu1','A',true) will generate a menu: - - for the data (A,1), (B,2), (C,3). Also see example 5.

      -

      Menu Example 2: For the same data, GetMenu('menu1',array('A','B'),false) - will generate a menu with both A and B selected:
      - -

      GetMenu2($name, [$default_str=''], [$blank1stItem=true], - [$multiple_select=false], [$size=0], [$moreAttr=''])

      -

      This is nearly identical to GetMenu, except that the $default_str is - matched to fields[1] (the option values).

      -

      Menu Example 3: Given the data in menu example 2, GetMenu2('menu1',array('1','2'),false) - will generate a menu with both A and B selected in menu example 2, but this - time the selection is based on the 2nd column, which holds the values to return - to the Web server. -

      UserDate($str, [$fmt])

      -

      Converts the date string $str to another format. The date format is Y-m-d, -or Unix timestamp format. The default $fmt is Y-m-d.

      -

      UserTimeStamp($str, [$fmt])

      -

      Converts the timestamp string $str to another format. The timestamp - format is Y-m-d H:i:s, as in '2002-02-28 23:00:12', or Unix timestamp format. - UserTimeStamp calls UnixTimeStamp to parse $str, and $fmt defaults to Y-m-d H:i:s if not defined. -

      -

      UnixDate($str)

      -

      Parses the date string $str and returns it in unix mktime format (eg. - a number indicating the seconds after January 1st, 1970). Expects the date to - be in Y-m-d H:i:s format, except for Sybase and Microsoft SQL Server, where - M d Y is also accepted (the 3 letter month strings are controlled by a global - array, which might need localisation).

      -

      This function is available in both ADORecordSet and ADOConnection since 1.91.

      -

      UnixTimeStamp($str)

      -

      Parses the timestamp string $str and returns it in unix mktime format - (eg. a number indicating the seconds after January 1st, 1970). Expects the date - to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00) or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format, except for Sybase and Microsoft SQL Server, where - "M d Y h:i:sA" (Dec 25 1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled by - a global array, which might need localisation).

      -
      -

      This function is available in both ADORecordSet and ADOConnection - since 1.91.

      -

      OffsetDate($dayFraction, + can be found there.

      + +

      GetArray([$number_of_rows])

      +

      Generate a 2-dimensional array of records from the current + cursor position, indexed from 0 to $number_of_rows - 1. If $number_of_rows + is undefined, till EOF.

      +

      GetRows([$number_of_rows])

      +Generate a 2-dimensional array of records from the current +cursor position. Synonym for GetArray() for compatibility with Microsoft ADO. +

      GetMenu($name, [$default_str=''], + [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])

      +

      Generate a HTML menu (<select><option><option></select>). + The first column of the recordset (fields[0]) will hold the string to display + in the option tags. If the recordset has more than 1 column, the second column + (fields[1]) is the value to send back to the web server.. The menu will be +given the name $name.

      +

      If $default_str is defined, then if $default_str == + fields[0], that field is selected. If $blank1stItem is true, the first + option is empty. You can also set the first option strings by setting $blank1stItem + = "$value:$text".

      +

      $Default_str can be array for a multiple select +listbox.

      +

      To get a listbox, set the $size to a non-zero + value (or pass $default_str as an array). If $multiple_select is true + then a listbox will be generated with $size items (or if $size==0, + then 5 items) visible, and we will return an array to a server. Lastly use + $moreAttr to add additional attributes such as javascript or styles.

      +

      Menu Example 1: GetMenu('menu1','A',true) will + generate a menu: + +for the data (A,1), (B,2), (C,3). Also see example 5.

      +

      Menu Example 2: For the same data, GetMenu('menu1',array('A','B'),false) will + generate a menu with both A and B selected:
      + +

      +

      GetMenu2($name, [$default_str=''], + [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])

      +

      This is nearly identical to GetMenu, except that the + $default_str is matched to fields[1] (the option values).

      +

      Menu Example 3: Given the data in menu example 2, GetMenu2('menu1',array('1','2'),false) will + generate a menu with both A and B selected in menu example 2, but this time + the selection is based on the 2nd column, which holds the values to return +to the Web server.

      +

      UserDate($str, [$fmt])

      +

      Converts the date string $str to another format. + The date format is Y-m-d, or Unix timestamp format. The default $fmt is +Y-m-d.

      +

      UserTimeStamp($str, [$fmt])

      +

      Converts the timestamp string $str to another + format. The timestamp format is Y-m-d H:i:s, as in '2002-02-28 23:00:12', + or Unix timestamp format. UserTimeStamp calls UnixTimeStamp to parse $str, +and $fmt defaults to Y-m-d H:i:s if not defined.

      +

      UnixDate($str)

      +

      Parses the date string $str and returns it in + unix mktime format (eg. a number indicating the seconds after January 1st, + 1970). Expects the date to be in Y-m-d H:i:s format, except for Sybase and + Microsoft SQL Server, where M d Y is also accepted (the 3 letter month strings + are controlled by a global array, which might need localisation).

      +

      This function is available in both ADORecordSet and +ADOConnection since 1.91.

      +

      UnixTimeStamp($str)

      +

      Parses the timestamp string $str and returns + it in unix mktime format (eg. a number indicating the seconds after January + 1st, 1970). Expects the date to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00) + or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format, + except for Sybase and Microsoft SQL Server, where "M d Y h:i:sA" (Dec 25 + 1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled +by a global array, which might need localisation).

      + +

      This function is available in both ADORecordSet + and ADOConnection since 1.91.

      +

      OffsetDate($dayFraction, $basedate=false)

      -

      Returns a string with the - native SQL functions to calculate future and past dates based on $basedate in - a portable fashion. If $basedate is not defined, then the current date (at 12 - midnight) is used. Returns the SQL string that performs the calculation when - passed to Execute().

      -

      For example, in Oracle, to find the date and time that +

      Returns a string with the native SQL functions to calculate + future and past dates based on $basedate in a portable fashion. If $basedate + is not defined, then the current date (at 12 midnight) is used. Returns the + SQL string that performs the calculation when passed to Execute().

      +

      For example, in Oracle, to find the date and time that is 2.5 days from today, you can use:

      -
      # get date one week from now
      -$fld = $conn->OffsetDate(7); // returns "(trunc(sysdate)+7")
      -
      # get date and time that is 60 hours from current date and time
      -$fld = $conn->OffsetDate(2.5, $conn->sysTimeStamp);	// returns "(sysdate+2.5)"
      -
      -$conn->Execute("UPDATE TABLE SET dodate=$fld WHERE ID=$id");
      -

      This function is available for mysql, mssql, oracle, oci8 and postgresql drivers - since 2.13. It might work with other drivers provided - they allow performing numeric day arithmetic on dates.

      - -

      SQLDate($dateFormat, $basedate=false)

      -Returns a string which contains the native SQL functions to format a date or date -column $basedate. This is used in SELECT statements. For INSERT/UPDATE statements, -use DBDate. It uses a case-sensitive $dateFormat, which -supports: -
      - Y: 4-digit Year
      - Q: Quarter (1-4)
      - M: Month (Jan-Dec)
      - m: Month (01-12)
      - d: Day (01-31)
      - H: Hour (00-23)
      - h: Hour (1-12)
      - i: Minute (00-59)
      - s: Second (00-60)
      - A: AM/PM indicator
      -

      All other characters are treated as strings. You can also use \ to escape characters. - Available on selected databases, including mysql, postgresql, mssql, oci8 and - DB2. -

      This is useful in writing portable sql statements that GROUP BY on dates. For - example to display total cost of goods sold broken by quarter (dates are stored - in a field called postdate): -

      - $sqlfn = $db->SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1
      - $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";
      - 
      -

      MoveNext( )

      -

      Move the internal cursor to the next row. The $this->fields array is - automatically updated. Returns false if unable to do so (normally because EOF - has been reached), otherwise true. -

      If EOF is reached, then the $this->fields array is set to false (this was - only implemented consistently in ADOdb 3.30). For the pre-3.30 behaviour of - $this->fields (at EOF), set the global variable $ADODB_COMPAT_FETCH = true.

      -

      Example:

      -
      $rs = $db->Execute($sql);
      -if ($rs) 
      -	while (!$rs->EOF) {
      - 		ProcessArray($rs->fields);	
      -		$rs->MoveNext();
      -	} 
      -

      Move($to)

      -

      Moves the internal cursor to a specific row $to. Rows are zero-based - eg. 0 is the first row. The fields array is automatically updated. For - databases that do not support scrolling internally, ADOdb will simulate forward - scrolling. Some databases do not support backward scrolling. If the $to - position is after the EOF, $to will move to the end of the RecordSet - for most databases. Some obscure databases using odbc might not behave this - way.

      -

      Note: This function uses absolute positioning, unlike Microsoft's ADO.

      -

      Returns true or false. If false, the internal cursor is not moved in most implementations, - so AbsolutePosition( ) will return the last cursor position before the Move( - ).

      -

      MoveFirst()

      -

      Internally calls Move(0). Note that some databases do not support this function.

      -

      MoveLast()

      -

      Internally calls Move(RecordCount()-1). Note that some databases do not support - this function.

      -

      GetRowAssoc($toUpper=true)

      -

      Returns an associative array containing the current row. The keys to the array - are the column names. The column names are upper-cased for easy access. To get - the next row, you will still need to call MoveNext().

      -

      For example:
      - Array ( [ID] => 1 [FIRSTNAME] => Caroline [LASTNAME] => Miranda [CREATED] => - 2001-07-05 )

      -

      Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC. - Because they have the same functionality, they will interfere with each other.

      -
      -

      AbsolutePage($page=-1) -

      -

      Returns the current page. Requires PageExecute()/CachePageExecute() to be called. - See Example 8.

      - +
      # get date one week from now
      $fld = $conn->OffsetDate(7); // returns "(trunc(sysdate)+7")
      +
      # get date and time that is 60 hours from current date and time
      $fld = $conn->OffsetDate(2.5, $conn->sysTimeStamp); // returns "(sysdate+2.5)"

      $conn->Execute("UPDATE TABLE SET dodate=$fld WHERE ID=$id");
      +

      This function is available for mysql, mssql, oracle, oci8 and postgresql drivers + since 2.13. It might work with other drivers provided they allow performing + numeric day arithmetic on dates.

      + +

      SQLDate($dateFormat, $basedate=false)

      +Returns a string which contains the native SQL functions +to format a date or date column $basedate. This is used in SELECT statements. +For INSERT/UPDATE statements, use DBDate. It uses a case-sensitive +$dateFormat, which supports: +
       
      +  Y: 4-digit Year
      +  Q: Quarter (1-4)
      +  M: Month (Jan-Dec)
      +  m: Month (01-12)
      +  d: Day (01-31)
      +  H: Hour (00-23)
      +  h: Hour (1-12)
      +  i: Minute (00-59)
      +  s: Second (00-60)
      +  A: AM/PM indicator
      +  w: day of week (0-6 or 1-7 depending on DB)
      +  l: day of week (as string - lowercase L)
      +  
      +

      All other characters are treated as strings. You can + also use \ to escape characters. Available on selected databases, including +mysql, postgresql, mssql, oci8 and DB2.

      +

      This is useful in writing portable sql statements that + GROUP BY on dates. For example to display total cost of goods sold broken +by quarter (dates are stored in a field called postdate):

      +
       $sqlfn = $db->SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1
      $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";
      +

      MoveNext( )

      +

      Move the internal cursor to the next row. The $this->fields array + is automatically updated. Returns false if unable to do so (normally because +EOF has been reached), otherwise true.

      +

      If EOF is reached, then the $this->fields array + is set to false (this was only implemented consistently in ADOdb 3.30). For + the pre-3.30 behaviour of $this->fields (at EOF), set the global variable + $ADODB_COMPAT_FETCH = true.

      +

      Example:

      +
      $rs = $db->Execute($sql);
      if ($rs)
      while (!$rs->EOF) {
      ProcessArray($rs->fields);
      $rs->MoveNext();
      }
      +

      Move($to)

      +

      Moves the internal cursor to a specific row $to. + Rows are zero-based eg. 0 is the first row. The fields array is automatically + updated. For databases that do not support scrolling internally, ADOdb will + simulate forward scrolling. Some databases do not support backward scrolling. + If the $to position is after the EOF, $to will move to the + end of the RecordSet for most databases. Some obscure databases using odbc + might not behave this way.

      +

      Note: This function uses absolute positioning, +unlike Microsoft's ADO.

      +

      Returns true or false. If false, the internal cursor + is not moved in most implementations, so AbsolutePosition( ) will return + the last cursor position before the Move( ).

      +

      MoveFirst()

      +

      Internally calls Move(0). Note that some databases do +not support this function.

      +

      MoveLast()

      +

      Internally calls Move(RecordCount()-1). Note that some + databases do not support this function.

      +

      GetRowAssoc($toUpper=true)

      +

      Returns an associative array containing the current + row. The keys to the array are the column names. The column names are upper-cased + for easy access. To get the next row, you will still need to call MoveNext().

      +

      For example:
      +Array ( [ID] => 1 [FIRSTNAME] => Caroline [LASTNAME] => Miranda [CREATED] +=> 2001-07-05 )

      +

      Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE + = ADODB_FETCH_ASSOC. Because they have the same functionality, they will + interfere with each other.

      + +

      AbsolutePage($page=-1)

      +

      Returns the current page. Requires PageExecute()/CachePageExecute() to be called. + See Example 8.

      +

      AtFirstPage($status='')

      -

      Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute() - to be called. See Example 8.

      +

      Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute() + to be called. See Example 8.

      AtLastPage($status='')

      -

      Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute() - to be called. See Example 8.

      +

      Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute() + to be called. See Example 8.

      Fields($colname)

      -

      Returns the value of the - associated column $colname for the current row. The column name is case-insensitive.

      +

      Returns the value of the associated column $colname for the current + row. The column name is case-insensitive.

      This is a convenience function. For higher performance, use $ADODB_FETCH_MODE.

      -

      FetchRow()

      -
      -

      Returns array containing current row, or false if EOF. - FetchRow( ) internally moves to the next record after returning the current - row.

      -

      Warning: Do not mix using FetchRow() with MoveNext().

      -

      Usage:

      -
      $rs = $db->Execute($sql);
      -if ($rs)
      -	while ($arr = $rs->FetchRow()) {
      -	     # process $arr	
      -	}
      -

      FetchInto(&$array)

      -

      Sets $array to the current row. Returns PEAR_Error object - if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned when - EOF. FetchInto( ) internally moves to the next - record after returning the current row.

      -

      FetchRow() is easier to use. See above.

      - -

      FetchField($column_number)

      -

      Returns an object containing the name, type and max_length - of the associated field. If the max_length cannot be determined reliably, it - will be set to -1. The column numbers are zero-based. See example - 2.

      -

      FieldCount( )

      -

      Returns the number of fields (columns) in the record set.

      -

      RecordCount( )

      -

      Returns the number of rows in the record set. If the number of records returned - cannot be determined from the database driver API, we will buffer all rows and - return a count of the rows after all the records have been retrieved. This buffering - can be disabled (for performance reasons) by setting the global variable $ADODB_COUNTRECS - = false. When disabled, RecordCount( ) will return -1 for certain databases. - See the supported databases list above for more details.

      -

      RowCount is a synonym for RecordCount.

      -

      PO_RecordCount($table, $where)

      -

      Returns the number of rows in the record set. If the database does not support - this, it will perform a SELECT COUNT(*) on the table $table, with the given - $where condition to return an estimate of the recordset size.

      -

      $numrows = $rs->PO_RecordCount("articles_table", "group=$group");

      - NextRecordSet() -

      For databases that allow multiple recordsets to be returned in one query, this - function allows you to switch to the next recordset. Currently only supported - by mssql driver.

      -
      -$rs = $db->Execute('execute return_multiple_rs');
      -$arr1 = $rs->GetArray();
      -$rs->NextRecordSet();
      -$arr2 = $rs->GetArray();
      -

      FetchObject($toupper=true)

      -

      Returns the current row as an object. If you set $toupper to true, then the - object fields are set to upper-case. Note: The newer FetchNextObject() is the - recommended way of accessing rows as objects. See below.

      -

      FetchNextObject($toupper=true)

      -

      Gets the current row as an object and moves to the next row automatically. - Returns false if at end-of-file. If you set $toupper to true, then the object - fields are set to upper-case.

      -
      -$rs = $db->Execute('select firstname,lastname from table');
      -if ($rs) {
      -	while ($o = $rs->FetchNextObject()) {
      -		print "$o->FIRSTNAME, $o->LASTNAME<BR>";
      -	}
      -}
      -
      -

      There is some trade-off in speed in using FetchNextObject(). If performance - is important, you should access rows with the fields[] array. FetchObj() -

      Returns the current record as an object. Fields are not upper-cased, unlike - FetchObject. -

      FetchNextObj() -

      -

      Returns the current record as an object and moves to - the next record. If EOF, false is returned. Fields are not upper-cased, unlike +

      FetchRow()

      +

      Returns array containing current row, or false + if EOF. FetchRow( ) internally moves to the next record after returning the + current row.

      +

      Warning: Do not mix using FetchRow() with MoveNext().

      +

      Usage:

      +
      $rs = $db->Execute($sql);
      if ($rs)
      while ($arr = $rs->FetchRow()) {
        # process $arr
      }
      +

      FetchInto(&$array)

      +

      Sets $array to the current row. Returns PEAR_Error + object if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned + when EOF. FetchInto( ) internally moves to the next record after returning + the current row.

      +

      FetchRow() is easier to use. See above.

      + +

      FetchField($column_number)

      +

      Returns an object containing the name, type and max_length of + the associated field. If the max_length cannot be determined reliably, it + will be set to -1. The column numbers are zero-based. See example + 2.

      +

      FieldCount( )

      +

      Returns the number of fields (columns) in the record +set.

      +

      RecordCount( )

      +

      Returns the number of rows in the record set. If the + number of records returned cannot be determined from the database driver + API, we will buffer all rows and return a count of the rows after all the + records have been retrieved. This buffering can be disabled (for performance + reasons) by setting the global variable $ADODB_COUNTRECS = false. When disabled, + RecordCount( ) will return -1 for certain databases. See the supported databases + list above for more details.

      +

      RowCount is a synonym for RecordCount.

      +

      PO_RecordCount($table, +$where)

      +

      Returns the number of rows in the record set. If the + database does not support this, it will perform a SELECT COUNT(*) on the + table $table, with the given $where condition to return an estimate of the + recordset size.

      +

      $numrows = $rs->PO_RecordCount("articles_table", "group=$group");

      + NextRecordSet() +

      For databases that allow multiple recordsets to be returned + in one query, this function allows you to switch to the next recordset. Currently + only supported by mssql driver.

      +
      $rs = $db->Execute('execute return_multiple_rs');
      $arr1 = $rs->GetArray();
      $rs->NextRecordSet();
      $arr2 = $rs->GetArray();
      +

      FetchObject($toupper=true)

      +

      Returns the current row as an object. If you set $toupper + to true, then the object fields are set to upper-case. Note: The newer FetchNextObject() + is the recommended way of accessing rows as objects. See below.

      +

      FetchNextObject($toupper=true)

      +

      Gets the current row as an object and moves to the next + row automatically. Returns false if at end-of-file. If you set $toupper to + true, then the object fields are set to upper-case.

      +
      $rs = $db->Execute('select firstname,lastname from table');
      if ($rs) {
      while ($o = $rs->FetchNextObject()) {
      print "$o->FIRSTNAME, $o->LASTNAME<BR>";
      }
      }
      +

      There is some trade-off in speed in using FetchNextObject(). +If performance is important, you should access rows with the fields[] array. FetchObj()

      +

      Returns the current record as an object. Fields are + not upper-cased, unlike FetchObject. +

      +

      FetchNextObj()

      +

      Returns the current record as an object and moves to + the next record. If EOF, false is returned. Fields are not upper-cased, unlike FetctNextObject.

      - +

      CurrentRow( )

      Returns the current row of the record set. 0 is the first row.

      AbsolutePosition( )

      -

      Synonym for CurrentRow for compatibility with ADO. Returns the current +

      Synonym for CurrentRow for compatibility with ADO. Returns the current row of the record set. 0 is the first row.

      MetaType($nativeDBType[,$field_max_length],[$fieldobj])

      -

      Determine what generic meta type a database field type is given its - native type $nativeDBType as a string and the length of the field $field_max_length. - Note that field_max_length can be -1 if it is not known. The field object returned - by FetchField() can be passed in $fieldobj or as the 1st parameter $nativeDBType. - This is useful for databases such as mysql which has additional properties +

      Determine what generic meta type a database field type is given its + native type $nativeDBType as a string and the length of the field $field_max_length. + Note that field_max_length can be -1 if it is not known. The field object returned + by FetchField() can be passed in $fieldobj or as the 1st parameter $nativeDBType. + This is useful for databases such as mysql which has additional properties in the field object such as primary_key.

      -

      Uses the field blobSize and compares it with $field_max_length - to determine whether the character field is actually a blob.

      -For example, $db->MetaType('char') will return 'C'. +

      Uses the field blobSize and compares it with $field_max_length to + determine whether the character field is actually a blob.

      +For example, $db->MetaType('char') will return 'C'.

      Returns:

        -
      • C: Character fields that should be shown in a <input type="text"> - tag.
      • -
      • X: Clob (character large objects), or large text fields that should +
      • C: Character fields that should be shown in a <input type="text"> tag.
      • +
      • X: Clob (character large objects), or large text fields that should be shown in a <textarea>
      • D: Date field
      • T: Timestamp field
      • L: Logical field (boolean or bit-field)
      • -
      • N: Numeric field. Includes decimal, numeric, floating point, and +
      • N: Numeric field. Includes decimal, numeric, floating point, and real.
      • I:  Integer field.
      • R: Counter or Autoincrement field. Must be numeric.
      • -
      • B: Blob, or binary large objects.
      • -
      -
      -

      Since ADOdb 3.0, MetaType accepts $fieldobj as the first - parameter, instead of $nativeDBType.

      - -

      Close( )

      -

      Closes the recordset, cleaning all memory and resources associated with the recordset. +

    • B: Blob, or binary large objects.
    • +
    +

    Since ADOdb 3.0, MetaType accepts $fieldobj + as the first parameter, instead of $nativeDBType.

    + +

    Close( )

    +

    Closes the recordset, cleaning all memory and resources +associated with the recordset.

    -If memory management is not an issue, you do not need to call this function as recordsets -are closed for you by PHP at the end of the script. -SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset, so you do not have to call Close() -for such SQL statements.

    +If memory management is not an issue, you do not need to +call this function as recordsets are closed for you by PHP at the end of the +script. SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset, +so you do not have to call Close() for such SQL statements.


    -

    function rs2html($adorecordset,[$tableheader_attributes], - [$col_titles])

    -

    This is a standalone function (rs2html = recordset to html) that is similar - to PHP's odbc_result_all function, it prints a ADORecordSet, $adorecordset - as a HTML table. $tableheader_attributes allow you to control the table - cellpadding, cellspacing and border attributes. Lastly - you can replace the database column names with your own column titles with the - array $col_titles. This is designed more as a quick debugging mechanism, - not a production table recordset viewer.

    -

    You will need to include the file tohtml.inc.php.

    -

    Example of rs2html:

    -
    <?
    -include('tohtml.inc.php'); # load code common to ADOdb 
    -include('adodb.inc.php'); # load code common to ADOdb 
    -$conn = &ADONewConnection('mysql');   # create a connection 
    -$conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
    -$sql = 'select CustomerName, CustomerID from customers'; 
    -$rs   = $conn->Execute($sql); 
    -rs2html($rs,'border=2 cellpadding=3',array('Customer Name','Customer ID'));
    -?>
    +

    function rs2html($adorecordset,[$tableheader_attributes], + [$col_titles])

    +

    This is a standalone function (rs2html = recordset to + html) that is similar to PHP's odbc_result_all function, it prints + a ADORecordSet, $adorecordset as a HTML table. $tableheader_attributes allow + you to control the table cellpadding, cellspacing and border attributes. + Lastly you can replace the database column names with your own column titles + with the array $col_titles. This is designed more as a quick debugging + mechanism, not a production table recordset viewer.

    +

    You will need to include the file tohtml.inc.php.

    +

    Example of rs2html:

    +
    <?
    include('tohtml.inc.php')
    ; # load code common to ADOdb
    include('adodb.inc.php'); # load code common to ADOdb
    $conn = &ADONewConnection('mysql'); # create a connection
    $conn->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
    $sql = 'select CustomerName, CustomerID from customers';
    $rs = $conn->Execute($sql);
    rs2html($rs,'border=2 cellpadding=3',array('Customer Name','Customer ID'));
    ?>

    -

    Differences between this ADOdb library and Microsoft ADO

    +

    Differences between this ADOdb library and Microsoft +ADO

      -
    1. ADOdb only supports recordsets created by a connection object. Recordsets - cannot be created independently.
    2. -
    3. ADO properties are implemented as functions in ADOdb. This makes it easier - to implement any enhanced ADO functionality in the future.
    4. -
    5. ADOdb's ADORecordSet->Move() - uses absolute positioning, not relative. Bookmarks are not supported.
    6. -
    7. ADORecordSet->AbsolutePosition() - cannot be used to move the record cursor.
    8. -
    9. ADO Parameter objects are not supported. Instead we have the ADOConnection::Parameter( - ) function, which provides a simpler interface for calling preparing parameters - and calling stored procedures.
    10. -
    11. Recordset properties for paging records are available, but implemented as - in Example 8.
    12. -
    + +
  • ADOdb only supports recordsets created by a connection object. Recordsets + cannot be created independently.
  • +
  • ADO properties are implemented as functions in ADOdb. This makes it easier + to implement any enhanced ADO functionality in the future.
  • +
  • ADOdb's ADORecordSet->Move() uses + absolute positioning, not relative. Bookmarks are not supported.
  • +
  • ADORecordSet->AbsolutePosition() cannot + be used to move the record cursor.
  • +
  • ADO Parameter objects are not supported. Instead we have the ADOConnection::Parameter( + ) function, which provides a simpler interface for calling preparing parameters + and calling stored procedures.
  • +
  • Recordset properties for paging records are available, but implemented as + in Example 8.
  • +

    -

    Database Driver Guide

    -

    This describes how to create a class to connect to a new database. To ensure - there is no duplication of work, kindly email me at jlim#natsoft.com.my if you - decide to create such a class.

    -

    First decide on a name in lower case to call the database type. Let's say we - call it xbase.

    -

    Then we need to create two classes ADODB_xbase and ADORecordSet_xbase in the - file adodb-xbase.inc.php.

    -

    The simplest form of database driver is an adaptation of an existing ODBC driver. - Then we just need to create the class ADODB_xbase extends ADODB_odbc - to support the new date and timestamp formats, the concatenation - operator used, true and false. For the ADORecordSet_xbase extends - ADORecordSet_odbc we need to change the MetaType function. See - adodb-vfp.inc.php as an example.

    -

    More complicated is a totally new database driver that connects to a new PHP - extension. Then you will need to implement several functions. Fortunately, you - do not have to modify most of the complex code. You only need to override a - few stub functions. See adodb-mysql.inc.php for example.

    -

    The default date format of ADOdb internally is YYYY-MM-DD (Ansi-92). All dates - should be converted to that format when passing to an ADOdb date function. See - Oracle for an example how we use ALTER SESSION to change the default date format - in _pconnect _connect.

    -

    ADOConnection Functions to Override

    -

    Defining a constructor for your ADOConnection derived function is optional. - There is no need to call the base class constructor.

    -

    _connect: Low level implementation of Connect. Returns true or false. - Should set the _connectionID.

    -

    _pconnect: Low level implemention of PConnect. Returns true or false. - Should set the _connectionID.

    -

    _query: Execute a query. Returns the queryID, or false.

    -

    _close: Close the connection -- PHP should clean up all recordsets. +

    Database Driver Guide

    +

    This describes how to create a class to connect to a + new database. To ensure there is no duplication of work, kindly email me + at jlim#natsoft.com.my if you decide to create such a class.

    +

    First decide on a name in lower case to call the database + type. Let's say we call it xbase.

    +

    Then we need to create two classes ADODB_xbase and ADORecordSet_xbase + in the file adodb-xbase.inc.php.

    +

    The simplest form of database driver is an adaptation + of an existing ODBC driver. Then we just need to create the class ADODB_xbase + extends ADODB_odbc to support the new date and timestamp formats, + the concatenation operator used, true and false. For + the ADORecordSet_xbase extends ADORecordSet_odbc we need to change + the MetaType function. See adodb-vfp.inc.php as an example.

    +

    More complicated is a totally new database driver that + connects to a new PHP extension. Then you will need to implement several + functions. Fortunately, you do not have to modify most of the complex code. + You only need to override a few stub functions. See adodb-mysql.inc.php for + example.

    +

    The default date format of ADOdb internally is YYYY-MM-DD + (Ansi-92). All dates should be converted to that format when passing to an + ADOdb date function. See Oracle for an example how we use ALTER SESSION to + change the default date format in _pconnect _connect.

    +

    ADOConnection Functions to Override

    +

    Defining a constructor for your ADOConnection derived + function is optional. There is no need to call the base class constructor.

    +

    _connect: Low level implementation of Connect. + Returns true or false. Should set the _connectionID.

    +

    _pconnect: Low level implemention of PConnect. + Returns true or false. Should set the _connectionID.

    +

    _query: Execute a query. Returns the queryID, +or false.

    +

    _close: Close the connection -- PHP should clean +up all recordsets.

    +

    ErrorMsg: Stores the error message in the private +variable _errorMsg.

    +

    ADOConnection Fields to Set

    +

    _bindInputArray: Set to true if binding of parameters + for SQL inserts and updates is allowed using ?, eg. as with ODBC.

    +

    fmtDate

    +

    fmtTimeStamp

    +

    true

    +

    false

    +

    concat_operator

    +

    replaceQuote

    +

    hasLimit support SELECT * FROM TABLE LIMIT 10 +of MySQL.

    +

    hasTop support Microsoft style SELECT TOP 10 +* FROM TABLE.

    +

    ADORecordSet Functions to Override

    +

    You will need to define a constructor for your ADORecordSet + derived class that calls the parent class constructor.

    +

    FetchField: as documented above in ADORecordSet

    +

    _initrs: low level initialization of the recordset: + setup the _numOfRows and _numOfFields fields -- called by the + constructor.

    +

    _seek: seek to a particular row. Do not load + the data into the fields array. This is done by _fetch. Returns true or false. + Note that some implementations such as Interbase do not support seek. Set + canSeek to false.

    +

    _fetch: fetch a row using the database extension + function and then move to the next row. Sets the fields array. If + the parameter $ignore_fields is true then there is no need to populate the fields array, + just move to the next row. then Returns true or false.

    +

    _close: close the recordset

    +

    Fields: If the array row returned by the PHP + extension is not an associative one, you will have to override this. See + adodb-odbc.inc.php for an example. For databases such as MySQL and MSSQL + where an associative array is returned, there is no need to override this + function.

    +

    ADOConnection Fields to Set

    +

    canSeek: Set to true if the _seek function works.

    +

    Optimizing PHP

    + For info on tuning PHP, read this article on Optimizing + PHP.

    + +

    Change Log

    +

    4.65 22 July 2005 +

    Reverted 'X' in mssql datadict to 'TEXT' to be compat with mssql driver. However now you can +set $datadict->typeX = 'varchar(4000)' or 'TEXT' or 'CLOB' for mssql and oci8 drivers. +

    Added charset support when using DSN for Oracle. +

    _adodb_getmenu did not use fieldcount() to get number of fields. Fixed. +

    MetaForeignKeys() for mysql/mysqli contributed by Juan Carlos Gonzalez. +

    MetaDatabases() now correctly returns an array for mysqli driver. Thx Cristian MARIN. +

    CompleteTrans(false) did not return false. Fixed. Thx to JMF. +

    AutoExecute() did not work with Oracle. Fixed. Thx José Moreira. +

    MetaType() added to connection object. +

    More PHP 4.4 reference return fixes. Thx Ryan C Bonham and others. + +

    4.64 20 June 2005 +

    In datadict, if the default field value is set to '', then it is not applied when the field is created. Fixed by Eugenio. +

    MetaPrimaryKeys for postgres did not work because of true/false change in 4.63. Fixed. +

    Tested ocifetchstatement in oci8. Rejected at the end. +

    Added port to dsn handling. Supported in postgres, mysql, mysqli,ldap. +

    Added 'w' and 'l' to mysqli SQLDate(). +

    Fixed error handling in ldap _connect() to be more consistent. Also added ErrorMsg() handling to ldap. +

    Added support for union in _adodb_getcount, adodb-lib.inc.php for postgres and oci8. +

    rs2html() did not work with null dates properly. +

    PHP 4.4 reference return fixes. + +

    4.63 18 May 2005 +

    Added $nrows<0 check to mysqli's SelectLimit(). +

    Added OptimizeTable() and OptimizeTables() in adodb-perf.inc.php. By Markus Staab. +

    PostgreSQL inconsistencies fixed. true and false set to TRUE and FALSE, and boolean type in datadict-postgres.inc.php set +to 'L' => 'BOOLEAN'. Thx Kevin Jamieson. +

    New adodb_session_create_table() function in adodb-session.inc.php. By Markus Staab. +

    Added null check to UserTimeStamp(). +

    Fixed typo in mysqlt driver in adorecordset. Thx to Andy Staudacher. +

    GenID() had a bug in the raiseErrorFn handling. Fixed. Thx Marcos Pont. +

    Datadict name quoting now handles ( ) in index fields correctly - they aren't part of the index field. +

    Performance monitoring: (1) oci8 Ixora checks moved down; (2) expensive sql changed so that only those sql with +count(*)>1 are shown; (3) changed sql1 field to a length+crc32 checksum - this breaks backward compat. +

    We remap firebird15 to firebird in data dictionary. + +

    4.62 2 Apr 2005 +

    Added 'w' (dow as 0-6 or 1-7) and 'l' (dow as string) for SQLDate for oci8, postgres and mysql. +

    Rolled back MetaType() changes for mysqli done in prev version. +

    Datadict change by chris, cblin#tennaxia.com data mappings from: +

    +oci8:  X->varchar(4000) XL->CLOB
    +mssql: X->XL->TEXT
    +mysql: X->XL->LONGTEXT
    +fbird: X->XL->varchar(4000)
    +
    +

    to: +

    +oci8:  X->varchar(4000) XL->CLOB
    +mssql: X->VARCHAR(4000) XL->TEXT
    +mysql: X->TEXT          XL->LONGTEXT
    +fbird: X->VARCHAR(4000) XL->VARCHAR(32000)
    +
    +

    Added $connection->disableBlobs to postgresql to improve performance when no bytea is used (2-5% improvement). +

    Removed all HTTP_* vars. +

    Added $rs->tableName to be set before calling AutoExecute(). +

    Alex Rootoff rootoff#pisem.net contributed ukrainian language file. +

    Added new mysql_option() support using $conn->optionFlags array. +

    Added support for ldap_set_option() using the $LDAP_CONNECT_OPTIONS global variable. Contributed by Josh Eldridge. +

    Added LDAP_* constant definitions to ldap. +

    Added support for boolean bind variables. We use $conn->false and $conn->true to hold values to set false/true to. +

    We now do not close the session connection in adodb-session.inc.php as other objects could be using this connection. +

    We now strip off \0 at end of Ixora SQL strings in $perf->tohtml() for oci8. +

    4.61 23 Feb 2005 +

    MySQLi added support for mysqli_connect_errno() and mysqli_connect_error(). +

    Massive improvements to alpha PDO driver. +

    Quote string bind parameters logged by performance monitor for easy type checking. Thx Jason Judge. +

    Added support for $role when connecting with Interbase/firebird. +

    Added support for enum recognition in MetaColumns() mysql and mysqli. Thx Amedeo Petrella. +

    The sybase_ase driver contributed by Interakt Online. Thx Cristian Marin cristic#interaktonline.com. +

    Removed not_null, has_default, and default_value from ADOFieldObject. +

    Sessions code, fixed quoting of keys when handling LOBs in session write() function. +

    Sessions code, added adodb_session_regenerate_id(), to reduce risk of session hijacking by changing session cookie dynamically. Thx Joe Li. +

    Perf monitor, polling for CPU did not work for PHP 4.3.10 and 5.0.0-5.0.3 due to PHP bugs, so we special case these versions. +

    Postgresql, UpdateBlob() added code to handle type==CLOB. +

    4.60 24 Jan 2005 +

    Implemented PEAR DB's autoExecute(). Simplified design because I don't like using constants when +strings work fine. +

    _rs2serialize will now update $rs->sql and $rs->oldProvider. +

    Added autoExecute(). +

    Added support for postgres8 driver. Currently just remapped to postgres7 driver. +

    Changed oci8 _query(), so that OCIBindByName() sets the length to -1 if element size is > 4000. This provides better support +for LONGs. +

    Added SetDateLocale() support for netherlands (Nl). +

    Spelling error in pivot code ($iff should be $iif). +

    mysql insert_id() did not work with mysql 3.x. Fixed. +

    "\r\n" not converted to spaces correctly in exporting data. Fixed. +

    _nconnect() in mysqli did not return value correctly. Fixed. +

    Arne Eckmann contributed danish language file. +

    Added clone() support to FetchObject() for PHP5.

    -

    ErrorMsg: Stores the error message in the private variable _errorMsg. +

    Removed SQL_CUR_USE_ODBC from odbc_mssql.

    -

    ADOConnection Fields to Set

    -

    _bindInputArray: Set to true if binding of parameters for SQL inserts - and updates is allowed using ?, eg. as with ODBC.

    -

    fmtDate

    -

    fmtTimeStamp

    -

    true

    -

    false

    -

    concat_operator

    -

    replaceQuote

    -

    hasLimit support SELECT * FROM TABLE LIMIT 10 of MySQL.

    -

    hasTop support Microsoft style SELECT TOP 10 * FROM TABLE.

    -

    ADORecordSet Functions to Override

    -

    You will need to define a constructor for your ADORecordSet derived class that - calls the parent class constructor.

    -

    FetchField: as documented above in ADORecordSet

    -

    _initrs: low level initialization of the recordset: setup the _numOfRows - and _numOfFields fields -- called by the constructor.

    -

    _seek: seek to a particular row. Do not load the data into the fields - array. This is done by _fetch. Returns true or false. Note that some implementations - such as Interbase do not support seek. Set canSeek to false.

    -

    _fetch: fetch a row using the database extension function and then move - to the next row. Sets the fields array. If the parameter $ignore_fields - is true then there is no need to populate the fields array, just move - to the next row. then Returns true or false.

    -

    _close: close the recordset

    -

    Fields: If the array row returned by the PHP extension is not an associative - one, you will have to override this. See adodb-odbc.inc.php for an example. - For databases such as MySQL and MSSQL where an associative array is returned, - there is no need to override this function.

    -

    ADOConnection Fields to Set

    -

    canSeek: Set to true if the _seek function works.

    -

    ToDo:

    -

    See the RoadMap article.

    -

    Also see the ADOdb proxy article - for bridging Windows and Unix databases using http remote procedure calls. For - your education, visit palslib.com for database info, - and read this article on Optimizing - PHP.

    -
    -

    Change Log

    -

    4.52 ?? 2004 -

    Bug found in Replace() when performance logging enabled, introduced in ADOdb 4.50. Fixed. -

    Replace() checks update stmt. If update stmt fails, we now return immediately. Thx to alex. -

    Added support for $ADODB_FORCE_TYPE in GetUpdateSQL/GetInsertSQL. Thx to niko. -

    Added ADODB_ASSOC_CASE support to postgres/postgres7 driver. -

    4.51 29 July 2004 -

    Added adodb-xmlschema 1.0.2. Thx dan and richard. -

    Added new adorecordset_ext_* classes. If ADOdb extension installed for mysql, mysqlt and oci8 +

    4.55 5 Jan 2005 +

    Found bug in Execute() with bind params for db's that do not support binding natively. +

    DropSequence() now correctly uses default parameter. +

    Now Execute() ignores locale for floats, so 1.23 is NEVER converted to 1,23. +

    SetFetchMode() not properly saved in adodb-perf, suspicious sql and expensive sql. Fixed. +

    Added INET to postgresql metatypes. Thx motzel. +

    Allow oracle hints to work when counting with _adodb_getcount in adodb-lib.inc.php. Thx Chris Wrye. +

    Changed mysql insert_id() to use SELECT LAST_INSERT_ID(). +

    If alter col in datadict does not modify col type/size of actual +col, then it is removed from alter col code. By Mark Newham. Not +perfect as MetaType() !== ActualType(). +

    Added handling of view fields in metacolumns() for postgresql. Thx Renato De Giovanni. +

    Added to informix MetaPrimaryKeys and MetaColumns fixes for null bit. Thx to Cecilio Albero. +

    Removed obsolete connection_timeout() from perf code. +

    Added support for arrayClass in adodb-csv.inc.php. +

    RSFilter now accepts methods of the form $array($obj, 'methodname'). Thx to blake#near-time.com. +

    Changed CacheFlush to $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; +

    For better cursor concurrency, added code to free ref cursors in +oci8 when $rs->Close() is called. Note that CLose() is called +internally by the Get* functions too. +

    Added IIF support for access when pivoting. Thx Volodia Krupach. +

    Added mssql datadict support for timestamp. Thx Alexios. +

    Informix pager fix. By Mario Ramirez. +

    ADODB_TABLE_REGEX now includes ':'. By Mario Ramirez. +

    Mark Newnham contributed MetaIndexes for oci8 and db2. +

    4.54 5 Nov 2004 +

    +Now you can set $db->charSet = ?? before doing a Connect() in oci8. +

    +Added adodbFetchMode to sqlite. +

    +Perf code, added a string typecast to substr in adodb_log_sql(). +

    +Postgres: Changed BlobDecode() to use po_loread, added new $maxblobsize parameter, and now it returns the blob instead +of sending it to stdout - make sure to mention that as a compat warning. +Also added $db->IsOID($oid) function; uses a heuristic, not guaranteed to work 100%. +

    +Contributed arabic language file by "El-Shamaa, Khaled" k.el-shamaa#cgiar.org +

    +PHP5 exceptions did not handle @ protocol properly. Fixed. +

    +Added ifnull handling for postgresql (using coalesce). +

    +Added metatables() support for Postgresql 8.0 (no longer uses pg_% dictionary tables). +

    +Improved Sybase ErrorMsg() function. By Gaetano Giunta. +

    +Improved oci8 SelectLimit() to use Prepare(). By Cristiano Duarte. +

    +Type-cast $row parameter in ifx_fetch_row() to int. Thx stefan bodgan. +

    Ralf becker contributed improvements in postgresql, sapdb, mysql data dictionary handling:
    +- MySql and Postgres MetaType was reporting every int column which was +part of a primary key and unique as serial
    +- Postgres was not reporting the scale of decimal types
    +- MaxDB was padding the defaults of none-string types with spaces
    +- MySql now correctly converts enum columns to varchar +

    +Ralf also changed Postgresql datadict:
    +- you cant add NOT NULL columns in postgres in one go, they need to be +added as NULL and then altered to NOT NULL
    +- AlterColumnSQL could not change a varchar column with numbers into an +integer column, postgres need an explicit conversation
    +- a re-created sequence was not set to the correct value, if the name +was the old name (no implicit sequence), now always the new name of the +implicit sequence is used
    +

    Sergio Strampelli added extra $intoken check to Lens_ParseArgs() in datadict code. +

    4.53 28 Sept 2004 +

    FetchMode cached in recordset is sometimes mapped to native db fetchMode. Normally this does not matter, +but when using cached recordsets, we need to switch back to using adodb fetchmode. So we cache this +in $rs->adodbFetchMode if it differs from the db's fetchMode. +

    For informix we now set canSeek = false driver because stefan bodgan tells me that seeking doesn't work. +

    SetDateLocale() never worked till now ;-) Thx david#tomato.it +

    Set $_bindInputArray = true in sapdb driver. Required for clob support. +

    Fixed some PEAR::DB emulation issues with isError() and isWarning. Thx to Gert-Rainer Bitterlich. +

    Empty() used in getupdatesql without strlen() check. Fixed.

    +

    Added unsigned detection to mysql and mysqli drivers. Thx to dan cech. +

    Added hungarian language file. Thx to Halászvári Gábor. +

    Improved fieldname-type formatting of datadict SQL generated (adding $widespacing parameter to _GenField). +

    Datadict oci8 DROP CONSTRAINTS misspelt. Fixed. Thx Mark Newnham. +

    Changed odbtp to dynamically change databaseType based on connection, eg. from 'odbtp' to 'odbtp_mssql' when connecting +to mssql database. +

    In datadict, MySQL I4 was wrongly mapped to MEDIUMINT, which is actually I3. Fixed. +

    Fixed mysqli MetaType() recognition. Mysqli returns numeric types unlike mysql extension. Thx Francesco Riosa. +

    VFP odbc driver curmode set wrongly, causing problems with memo fields. Fixed. +

    Odbc driver did not recognize odbc version 2 driver date types properly. Fixed. Thx Bostjan. +

    ChangeTableSQL() fixes to datadict-db2.inc.php by Mark Newnham. +

    Perf monitoring with odbc improved. Now we try in perf code to manually set the sysTimeStamp using date() if sysTimeStamp +is empty. +

    All ADO errors are thrown as exceptions in PHP5. +So we added exception handling to ado in PHP5 by creating new adodb-ado5.inc.php driver. +

    Added IsConnected(). Returns true if connection object connected. By Luca.Gioppo. +

    "Ralf Becker" +RalfBecker#digitalROCK.de contributed new sapdb data-dictionary driver +and a large patch that implements field and table renaming for oracle, +mssql, postgresql, mysql and sapdb. See the new RenameTableSQL() and +RenameColumnSQL() functions. +

    We now check ExecuteCursor to see if PrepareSP was initially called. +

    Changed oci8 datadict to use MODIFY for $dd->alterCol. Thx Mark Newnham. +

    4.52 10 Aug 2004 +

    Bug found in Replace() when performance logging enabled, introduced in ADOdb 4.50. Fixed. +

    Replace() checks update stmt. If update stmt fails, we now return immediately. Thx to alex. +

    Added support for $ADODB_FORCE_TYPE in GetUpdateSQL/GetInsertSQL. Thx to niko. +

    Added ADODB_ASSOC_CASE support to postgres/postgres7 driver. +

    Support for DECLARE stmt in oci8. Thx Lochbrunner. +

    4.51 29 July 2004 +

    Added adodb-xmlschema 1.0.2. Thx dan and richard. +

    Added new adorecordset_ext_* classes. If ADOdb extension installed for mysql, mysqlt and oci8 (but not oci8po), we use the superfast ADOdb extension code for movenext. -

    Added schema support to mssql and odbc_mssql MetaPrimaryKeys(). -

    Patched MSSQL driver to support PHP NULL and Boolean values +

    Added schema support to mssql and odbc_mssql MetaPrimaryKeys(). +

    Patched MSSQL driver to support PHP NULL and Boolean values while binding the input array parameters in the _query() function. By Stephen Farmer. -

    Added support for clob's for mssql, UpdateBlob(). Thx to gfran#directa.com.br -

    Added normalize support for postgresql (true=lowercase table name, or false=case-sensitive table names) +

    Added support for clob's for mssql, UpdateBlob(). Thx to gfran#directa.com.br +

    Added normalize support for postgresql (true=lowercase table name, or false=case-sensitive table names) to MetaColumns($table, $normalize=true). -

    PHP5 variant dates in ADO not working. Fixed in adodb-ado.inc.php. -

    Constant ADODB_FORCE_NULLS was not working properly for many releases (for GetUpdateSQL). Fixed. -Also GetUpdateSQL strips off ORDER BY now - thx Elieser Leão. -

    Perf Monitor for oci8 now dynamically highlights optimizer_* params if too high/low. -

    Added dsn support to NewADOConnection/ADONewConnection. -

    Fixed out of page bounds bug in _adodb_pageexecute_all_rows() Thx to "Sergio Strampelli" sergio#rir.it -

    Speedup of movenext for mysql and oci8 drivers. -

    Moved debugging code _adodb_debug_execute() to adodb-lib.inc.php. -

    Fixed postgresql bytea detection bug. See http://phplens.com/lens/lensforum/msgs.php?id=9849. -

    Fixed ibase datetimestamp typo in PHP5. Thx stefan. -

    Removed whitespace at end of odbtp drivers. -

    Added db2 metaprimarykeys fix. -

    Optimizations to MoveNext() for mysql and oci8. Misc speedups to Get* functions. -

    4.50 6 July 2004 -

    Bumped it to 4.50 to avoid confusion with PHP 4.3.x series. -

    Added db2 metatables and metacolumns extensions. -

    Added alpha PDO driver. Very buggy, only works with odbc. -

    Tested mysqli. Set poorAffectedRows = true. Cleaned up movenext() and _fetch(). -

    PageExecute does not work properly with php5 (return val not a variable). Reported Dmytro Sychevsky sych#php.com.ua. Fixed. -

    MetaTables() for mysql, $showschema parameter was not backward compatible with older versions of adodb. Fixed. -

    Changed mysql GetOne() to work with mysql 3.23 when using with non-select stmts (e.g. SHOW TABLES). -

    Changed TRIG_ prefix to a variable in datadict-oci8.inc.php. Thx to Luca.Gioppo#csi.it. -

    New to adodb-time code. We allow you to define your own daylights savings function, +

    PHP5 variant dates in ADO not working. Fixed in adodb-ado.inc.php. +

    Constant ADODB_FORCE_NULLS was not working properly for many releases (for GetUpdateSQL). Fixed. +Also GetUpdateSQL strips off ORDER BY now - thx Elieser Leão. +

    Perf Monitor for oci8 now dynamically highlights optimizer_* params if too high/low. +

    Added dsn support to NewADOConnection/ADONewConnection. +

    Fixed out of page bounds bug in _adodb_pageexecute_all_rows() Thx to "Sergio Strampelli" sergio#rir.it +

    Speedup of movenext for mysql and oci8 drivers. +

    Moved debugging code _adodb_debug_execute() to adodb-lib.inc.php. +

    Fixed postgresql bytea detection bug. See http://phplens.com/lens/lensforum/msgs.php?id=9849. +

    Fixed ibase datetimestamp typo in PHP5. Thx stefan. +

    Removed whitespace at end of odbtp drivers. +

    Added db2 metaprimarykeys fix. +

    Optimizations to MoveNext() for mysql and oci8. Misc speedups to Get* functions. +

    4.50 6 July 2004 +

    Bumped it to 4.50 to avoid confusion with PHP 4.3.x series. +

    Added db2 metatables and metacolumns extensions. +

    Added alpha PDO driver. Very buggy, only works with odbc. +

    Tested mysqli. Set poorAffectedRows = true. Cleaned up movenext() and _fetch(). +

    PageExecute does not work properly with php5 (return val not a variable). Reported Dmytro Sychevsky sych#php.com.ua. Fixed. +

    MetaTables() for mysql, $showschema parameter was not backward compatible with older versions of adodb. Fixed. +

    Changed mysql GetOne() to work with mysql 3.23 when using with non-select stmts (e.g. SHOW TABLES). +

    Changed TRIG_ prefix to a variable in datadict-oci8.inc.php. Thx to Luca.Gioppo#csi.it. +

    New to adodb-time code. We allow you to define your own daylights savings function, adodb_daylight_sv for pre-1970 dates. If the function is defined (somewhere in an include), then you can correct for daylights savings. See http://phplens.com/phpeverywhere/node/view/16#daylightsavings for more info. -

    New sqlitepo driver. This is because assoc mode does not work like other drivers in sqlite. +

    New sqlitepo driver. This is because assoc mode does not work like other drivers in sqlite. Namely, when selecting (joining) multiple tables, in assoc mode the table names are included in the assoc keys in the "sqlite" driver. In "sqlitepo" driver, the table names are stripped from the returned column names. When this results in a conflict, the first field get preference. Contributed by Herman Kuiper herman#ozuzo.net -

    Added $forcenull parameter to GetInsertSQL/GetUpdateSQL. Idea by Marco Aurelio Silva. -

    More XHTML changes for GetMenu. By Jeremy Evans. -

    Fixes some ibase date issues. Thx to stefan bogdan. -

    Improvements to mysqli driver to support $ADODB_COUNTRECS. -

    Fixed adodb-csvlib.inc.php problem when reading stream from socket. We need to poll stream continiously. -

    4.23 16 June 2004 -

    +

    Added $forcenull parameter to GetInsertSQL/GetUpdateSQL. Idea by Marco Aurelio Silva. +

    More XHTML changes for GetMenu. By Jeremy Evans. +

    Fixes some ibase date issues. Thx to stefan bogdan. +

    Improvements to mysqli driver to support $ADODB_COUNTRECS. +

    Fixed adodb-csvlib.inc.php problem when reading stream from socket. We need to poll stream continiously. +

    4.23 16 June 2004 +

    New interbase/firebird fixes thx to Lester Caine. Driver fixes a problem with getting field names in the result array, and corrects a couple of data conversions. Also we default to dialect3 for firebird. Also ibase sysDate property was wrong. Changed to cast as timestamp. -

    +

    The datadict driver is set up to give quoted tables and fields as this was the only way round reserved words being used as field names in TikiWiki. TikiPro is tidying that up, and I hope to be able to produce a build of THAT which uses what I consider proper UPPERCASE field and table names. The conversion of TikiWiki to ADOdb helped in that, but until the database is completely tidied up in TikiPro ... -

    Modified _gencachename() to include fetchmode in name hash. +

    Modified _gencachename() to include fetchmode in name hash. This means you should clear your cache directory after installing this release as the cache name algorithm has changed. -

    Now Cache* functions work in safe mode, because we do not create sub-directories in the $ADODB_CACHE_DIR in safe mode. In non-safe mode we still create sub-directories. Done by modifying _gencachename(). -

    Added $gmt parameter (true/false) to UserDate and UserTimeStamp in connection class, to force conversion of input (in local time) to be converted to UTC/GMT. -

    Mssql datadict did not support INT types properly (no size param allowed). +

    Now Cache* functions work in safe +mode, because we do not create sub-directories in the $ADODB_CACHE_DIR +in safe mode. In non-safe mode we still create sub-directories. Done by +modifying _gencachename(). +

    Added $gmt parameter (true/false) +to UserDate and UserTimeStamp in connection class, to force conversion +of input (in local time) to be converted to UTC/GMT. +

    Mssql datadict did not support INT types properly (no size param allowed). Added _GetSize() to datadict-mssql.inc.php. -

    For borland_ibase, BeginTrans(), changed:
    -

       $this->_transactionID = $this->_connectionID;
    +

    For borland_ibase, BeginTrans(), changed:
    +

       $this->_transactionID = $this->_connectionID;
    to
    -
       $this->_transactionID = ibase_trans($this->ibasetrans, $this->_connectionID);
    +
       $this->_transactionID = ibase_trans($this->ibasetrans, $this->_connectionID);

    Fixed typo in mysqi_field_seek(). Thx to Sh4dow (sh4dow#php.pl). -

    LogSQL did not work with Firebird/Interbase. Fixed. -

    Postgres: made errorno() handling more consistent. Thx to Michael Jahn, Michael.Jahn#mailbox.tu-dresden.de. -

    Added informix patch to better support metatables, metacolumns by "Cecilio Albero" c-albero#eos-i.com -

    Cyril Malevanov contributed patch to oci8 to support passing of LOB parameters: -

    -	$text = 'test test test';
    -	$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
    -	$stmt = $conn -> PrepareSP($sql);
    -	$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB);
    -	$rs = '';
    -	$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
    -	$conn -> Execute($stmt);
    -	echo "return = ".$rs."<br>";
    -
    +

    LogSQL did not work with Firebird/Interbase. Fixed. +

    Postgres: made errorno() handling more consistent. Thx to Michael Jahn, Michael.Jahn#mailbox.tu-dresden.de. +

    Added informix patch to better support metatables, metacolumns by "Cecilio Albero" c-albero#eos-i.com +

    Cyril Malevanov contributed patch to oci8 to support passing of LOB parameters: +

    	$text = 'test test test';
    $sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
    $stmt = $conn -> PrepareSP($sql);
    $conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB);
    $rs = '';
    $conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
    $conn -> Execute($stmt);
    echo "return = ".$rs."<br>";
    As he says, the LOBs limitations are: -
    - - use OCINewDescriptor before binding
    - - if Param is IN, uses save() before each execute. This is done automatically for you.
    - - if Param is OUT, uses load() after each execute. This is done automatically for you.
    - - when we bind $var as LOB, we create new descriptor and return it as a
    -   Bind Result, so if we want to use OUT parameters, we have to store
    -   somewhere &$var to load() data from LOB to it.
    - - IN OUT params are not working now (should not be a big problem to fix it)
    - - now mass binding not working too (I've wrote about it before)
    -
    +
     - use OCINewDescriptor before binding
    - if Param is IN, uses save() before each execute. This is done automatically for you.
    - if Param is OUT, uses load() after each execute. This is done automatically for you.
    - when we bind $var as LOB, we create new descriptor and return it as a
    Bind Result, so if we want to use OUT parameters, we have to store
    somewhere &$var to load() data from LOB to it.
    - IN OUT params are not working now (should not be a big problem to fix it)
    - now mass binding not working too (I've wrote about it before)

    Simplified Connect() and PConnect() error handling. -

    When extension not loaded, Connect() and PConnect() will return null. On connect error, the fns will return false. -

    CacheGetArray() added to code. -

    Added Init() to adorecordset_empty(). -

    Changed postgres64 driver, MetaColumns() to not strip off quotes in default value if :: detected (type-casting of default). -

    Added test: if (!defined('ADODB_DIR')) die(). Useful to prevent hackers from detecting file paths. -

    Changed metaTablesSQL to ignore Postgres 7.4 information schemas (sql_*). -

    New polish language file by Grzegorz Pacan -

    Added support for UNION in _adodb_getcount(). -

    Added security check for ADODB_DIR to limit path disclosure issues. Requested by postnuke team. -

    Added better error message support to oracle driver. Thx to Gaetano Giunta. -

    Added showSchema support to mysql. -

    Bind in oci8 did not handle $name=false properly. Fixed. -

    If extension not loaded, Connect(), PConnect(), NConnect() will return null. -

    4.22 15 Apr 2004 -

    Moved docs to own adodb/docs folder. -

    Fixed session bug when quoting compressed/encrypted data in Replace(). -

    Netezza Driver and LDAP drivers contributed by Josh Eldridge. -

    GetMenu now uses rtrim() on values instead of trim(). -

    Changed MetaColumnNames to return an associative array, keys being the field names in uppercase. -

    Suggested fix to adodb-ado.inc.php affected_rows to support PHP5 variants. Thx to Alexios Fakos. -

    Contributed bulgarian language file by Valentin Sheiretsky valio#valio.eu.org. -

    Contributed romanian language file by stefan bogdan. -

    GetInsertSQL now checks for table name (string) in $rs, and will create a recordset for that +

    When extension not loaded, Connect() and PConnect() will return null. On connect error, the fns will return false. +

    CacheGetArray() added to code. +

    Added Init() to adorecordset_empty(). +

    Changed postgres64 driver, MetaColumns() to not strip off quotes in default value if :: detected (type-casting of default). +

    Added test: if (!defined('ADODB_DIR')) die(). Useful to prevent hackers from detecting file paths. +

    Changed metaTablesSQL to ignore Postgres 7.4 information schemas (sql_*). +

    New polish language file by Grzegorz Pacan +

    Added support for UNION in _adodb_getcount(). +

    Added security check for ADODB_DIR to limit path disclosure issues. Requested by postnuke team. +

    Added better error message support to oracle driver. Thx to Gaetano Giunta. +

    Added showSchema support to mysql. +

    Bind in oci8 did not handle $name=false properly. Fixed. +

    If extension not loaded, Connect(), PConnect(), NConnect() will return null. +

    4.22 15 Apr 2004 +

    Moved docs to own adodb/docs folder. +

    Fixed session bug when quoting compressed/encrypted data in Replace(). +

    Netezza Driver and LDAP drivers contributed by Josh Eldridge. +

    GetMenu now uses rtrim() on values instead of trim(). +

    Changed MetaColumnNames to return an associative array, keys being the field names in uppercase. +

    Suggested fix to adodb-ado.inc.php affected_rows to support PHP5 variants. Thx to Alexios Fakos. +

    Contributed bulgarian language file by Valentin Sheiretsky valio#valio.eu.org. +

    Contributed romanian language file by stefan bogdan. +

    GetInsertSQL now checks for table name (string) in $rs, and will create a recordset for that table automatically. Contributed by Walt Boring. Also added OCI_B_BLOB in bind on Walt's request - hope it doesn't break anything :-) -

    Some minor postgres speedups in _initrs(). -

    ChangeTableSQL checks now if MetaColumns returns empty. Thx Jason Judge. -

    Added ADOConnection::Time(), returns current database time in unix timestamp format, or false. -

    4.21 20 Mar 2004 -

    We no longer in SelectLimit for VFP driver add SELECT TOP X unless an ORDER BY exists. -

    Pim Koeman contributed dutch language file adodb-nl.inc.php. -

    Rick Hickerson added CLOB support to db2 datadict. -

    Added odbtp driver. Thx to "stefan bogdan" sbogdan#rsb.ro. -

    Changed PrepareSP() 2nd parameter, $cursor, to default to true (formerly false). Fixes oci8 backward +

    Some minor postgres speedups in _initrs(). +

    ChangeTableSQL checks now if MetaColumns returns empty. Thx Jason Judge. +

    Added ADOConnection::Time(), returns current database time in unix timestamp format, or false. +

    4.21 20 Mar 2004 +

    We no longer in SelectLimit for VFP driver add SELECT TOP X unless an ORDER BY exists. +

    Pim Koeman contributed dutch language file adodb-nl.inc.php. +

    Rick Hickerson added CLOB support to db2 datadict. +

    Added odbtp driver. Thx to "stefan bogdan" sbogdan#rsb.ro. +

    Changed PrepareSP() 2nd parameter, $cursor, to default to true (formerly false). Fixes oci8 backward compat problems with OUT params. -

    Fixed month calculation error in adodb-time.inc.php. 2102-June-01 appeared as 2102-May-32. -

    Updated PHP5 RC1 iterator support. API changed, hasMore() renamed to valid(). -

    Changed internal format of serialized cache recordsets. As we store a version number, this should be +

    Fixed month calculation error in adodb-time.inc.php. 2102-June-01 appeared as 2102-May-32. +

    Updated PHP5 RC1 iterator support. API changed, hasMore() renamed to valid(). +

    Changed internal format of serialized cache recordsets. As we store a version number, this should be backward compatible. -

    Error handling when driver file not found was flawed in ADOLoadCode(). Fixed. -

    4.20 27 Feb 2004 -

    Updated to AXMLS 1.01. -

    MetaForeignKeys for postgres7 modified by Edward Jaramilla, works on pg 7.4. -

    Now numbers accepts function calls or sequences for GetInsertSQL/GetUpdateSQL numeric fields. -

    Changed quotes of 'delete from $perf_table' to "". Thx Kehui (webmaster#kehui.net) -

    Added ServerInfo() for ifx, and putenv trim fix. Thx Fernando Ortiz. -

    Added addq(), which is analogous to addslashes(). -

    Tested with php5b4. Fix some php5 compat problems with exceptions and sybase. -

    Carl-Christian Salvesen added patch to mssql _query to support binds greater than 4000 chars. -

    Mike suggested patch to PHP5 exception handler. $errno must be numeric. -

    Added double quotes (") to ADODB_TABLE_REGEX. -

    For oci8, Prepare(...,$cursor), $cursor's meaning was accidentally inverted in 4.11. This causes problems with ExecuteCursor() too, which calls Prepare() internally. Thx to William Lovaton. -

    Now dateHasTime property in connection object renamed to datetime for consistency. This could break bc. -

    Csongor Halmai reports that db2 SelectLimit with input array is not working. Fixed.. -

    4.11 27 Jan 2004 -

    Csongor Halmai reports db2 binding not working. Reverted back to emulated binding. -

    Dan Cech modifies datadict code. Adds support for DropIndex. Minor cleanups. -

    Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W. -

    UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed. -

    Changed oci8 Prepare(). Does not auto-allocate OCINewCursor automatically, unless 2nd param is set to true. +

    Error handling when driver file not found was flawed in ADOLoadCode(). Fixed. +

    4.20 27 Feb 2004 +

    Updated to AXMLS 1.01. +

    MetaForeignKeys for postgres7 modified by Edward Jaramilla, works on pg 7.4. +

    Now numbers accepts function calls or sequences for GetInsertSQL/GetUpdateSQL numeric fields. +

    Changed quotes of 'delete from $perf_table' to "". Thx Kehui (webmaster#kehui.net) +

    Added ServerInfo() for ifx, and putenv trim fix. Thx Fernando Ortiz. +

    Added addq(), which is analogous to addslashes(). +

    Tested with php5b4. Fix some php5 compat problems with exceptions and sybase. +

    Carl-Christian Salvesen added patch to mssql _query to support binds greater than 4000 chars. +

    Mike suggested patch to PHP5 exception handler. $errno must be numeric. +

    Added double quotes (") to ADODB_TABLE_REGEX. +

    For oci8, Prepare(...,$cursor), +$cursor's meaning was accidentally inverted in 4.11. This causes +problems with ExecuteCursor() too, which calls Prepare() internally. +Thx to William Lovaton. +

    Now dateHasTime property in connection object renamed to datetime for consistency. This could break bc. +

    Csongor Halmai reports that db2 SelectLimit with input array is not working. Fixed.. +

    4.11 27 Jan 2004 +

    Csongor Halmai reports db2 binding not working. Reverted back to emulated binding. +

    Dan Cech modifies datadict code. Adds support for DropIndex. Minor cleanups. +

    Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W. +

    UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed. +

    Changed oci8 Prepare(). Does not auto-allocate OCINewCursor automatically, unless 2nd param is set to true. This will break backward compat, if Prepare/Execute is used instead of ExecuteCursor. Reported by Chris Jones. -

    Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they +

    Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they are self-documenting. -

    Added 'R' handling in ActualType() to datadict-mysql.inc.php -

    Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session. -

    Added "Run SQL" to performance UI(). -

    Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs. -

    MetaIndexes() for ibase contributed by Heinz Hombergs. -

    4.10 12 Jan 2004 -

    Dan Cech contributed extensive changes to data dictionary to support name quoting (with `), and drop table/index. -

    Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance. -

    Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys(). -

    Simplified chinese file, adodb-cn.inc.php from cysoft. -

    Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge. -

    Added connection parameter to ibase Prepare(). Fix by Daniel Hassan. -

    Added nameQuote for quoting identifiers and names to connection obj. Requested by Jason Judge. Also the +

    Added 'R' handling in ActualType() to datadict-mysql.inc.php +

    Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session. +

    Added "Run SQL" to performance UI(). +

    Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs. +

    MetaIndexes() for ibase contributed by Heinz Hombergs. +

    4.10 12 Jan 2004 +

    Dan Cech contributed extensive changes to data dictionary to support name quoting (with `), and drop table/index. +

    Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance. +

    Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys(). +

    Simplified chinese file, adodb-cn.inc.php from cysoft. +

    Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge. +

    Added connection parameter to ibase Prepare(). Fix by Daniel Hassan. +

    Added nameQuote for quoting identifiers and names to connection obj. Requested by Jason Judge. Also the data dictionary parser now detects `field name` and generates column names with spaces correctly. -

    BOOL type not recognised correctly as L. Fixed. -

    Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003) -

    Added Schema to postgresql MetaTables. Thx to col#gear.hu -

    Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed. -

    CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio. -

    Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html). -

    Fixed some fr and it lang errors. Thx to Gaetano G. -

    Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G. -

    Fixed array recordset bugs when _skiprow1 is true. Thx to Gaetano G. -

    Fixed pivot table code when count is false. -

    +

    BOOL type not recognised correctly as L. Fixed. +

    Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003) +

    Added Schema to postgresql MetaTables. Thx to col#gear.hu +

    Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed. +

    CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio. +

    Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html). +

    Fixed some fr and it lang errors. Thx to Gaetano G. +

    Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G. +

    Fixed array recordset bugs when _skiprow1 is true. Thx to Gaetano G. +

    Fixed pivot table code when count is false. +

    -

    4.05 13 Dec 2003 -

    Added MetaIndexes - thx to Dan Cech. -

    Rewritten session code by Ross Smith. Moved code to adodb/session directory. -

    Added function exists check on connecting to most drivers, so we don't crash with the unknown function error. -

    Smart Transactions failed with GenID() when it no seq table has been created because the sql +

    4.05 13 Dec 2003 +

    Added MetaIndexes to data-dict code - thx to Dan Cech. +

    Rewritten session code by Ross Smith. Moved code to adodb/session directory. +

    Added function exists check on connecting to most drivers, so we don't crash with the unknown function error. +

    Smart Transactions failed with GenID() when it no seq table has been created because the sql statement fails. Fix by Mark Newnham. -

    Added $db->length, which holds name of function that returns strlen. -

    Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler. -

    Datadict did not handle types like 16.0 properly in _GetSize. Fixed. -

    Oci8 driver SelectLimit() bug &= instead of =& used. Thx to Swen Thümmler. -

    Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added. -

    MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php. -

    New mysqli driver contributed by Arjen de Rijke. Based on adodb 3.40 driver. +

    Added $db->length, which holds name of function that returns strlen. +

    Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler. +

    Datadict did not handle types like 16.0 properly in _GetSize. Fixed. +

    Oci8 driver SelectLimit() bug &= instead of =& used. Thx to Swen Thümmler. +

    Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added. +

    MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php. +

    New mysqli driver contributed by Arjen de Rijke. Based on adodb 3.40 driver. Then jlim added BeginTrans, CommitTrans, RollbackTrans, IfNull, SQLDate. Also fixed return ref bug. -

    $ADODB_FLUSH added, if true then force flush in debugging outp. Default is false. In earlier +

    $ADODB_FLUSH added, if true then force flush in debugging outp. Default is false. In earlier versions, outp defaulted to flush, which is not compat with apache 2.0. -

    Mysql driver's GenID() function did not work when when sql logging is on. Fixed. -

    $ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed. -

    The input array not passed to Execute() in _adodb_getcount(). Fixed. -

    4.04 13 Nov 2003 -

    Switched back to foreach - faster than list-each. -

    Fixed bug in ado driver - wiping out $this->fields with date fields. -

    Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)>max($_GET length). Fixed. -

    Performance monitor, oci8 driver added memory sort ratio. -

    Added random property, returns SQL to generate a floating point number between 0 and 1; -

    4.03 6 Nov 2003 -

    The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly. -

    Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski. -

    Force autorollback for pgsql persistent connections - +

    Mysql driver's GenID() function did not work when when sql logging is on. Fixed. +

    $ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed. +

    The input array not passed to Execute() in _adodb_getcount(). Fixed. +

    4.04 13 Nov 2003 +

    Switched back to foreach - faster than list-each. +

    Fixed bug in ado driver - wiping out $this->fields with date fields. +

    Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)>max($_GET length). Fixed. +

    Performance monitor, oci8 driver added memory sort ratio. +

    Added random property, returns SQL to generate a floating point number between 0 and 1; +

    4.03 6 Nov 2003 +

    The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly. +

    Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski. +

    Force autorollback for pgsql persistent connections - apparently pgsql did not autorollback properly before 4.3.4. See http://bugs.php.net/bug.php?id=25404 -

    4.02 5 Nov 2003 -

    Some errors in adodb_error_pg() fixed. Thx to Styve. -

    Spurious Insert_ID() error was generated by LogSQL(). Fixed. -

    Insert_ID was interfering with Affected_Rows() and Replace() when LogSQL() enabled. Fixed. -

    More foreach loops optimized with list/each. -

    Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!). -

    Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made +

    4.02 5 Nov 2003 +

    Some errors in adodb_error_pg() fixed. Thx to Styve. +

    Spurious Insert_ID() error was generated by LogSQL(). Fixed. +

    Insert_ID was interfering with Affected_Rows() and Replace() when LogSQL() enabled. Fixed. +

    More foreach loops optimized with list/each. +

    Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!). +

    Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made interbase MetaColumns work with firebird/interbase, and added lang/adodb-de.inc.php. -

    Added INFORMIXSERVER environment variable. -

    Added $ADODB_ANSI_PADDING_OFF for interbase/firebird. -

    PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support. -

    4.01 23 Oct 2003 -

    Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells. -

    Fixed insert_id() incorrectly generated when logsql() enabled. -

    Modified PostgreSQL _fixblobs to use list/each instead of foreach. -

    Informix ErrorNo() implemented correctly. -

    Modified several places to use list/each, including GetRowAssoc(). -

    Added UserTimeStamp() to connection class. -

    Added $ADODB_ANSI_PADDING_OFF for oci8po. -

    4.00 20 Oct 2003 -

    Upgraded adodb-xmlschema to 1 Oct 2003 snapshot. -

    Fix to rs2html warning message. Thx to Filo. -

    Fix for odbc_mssql/mssql SQLDate(), hours was wrong. -

    Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson. -

    Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns -

    3.94 11 Oct 2003 -

    Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed. -

    ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed. -

    Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections. -

    Added SQLDate support for sybase. Thx to Chris Phillipson -

    Postgresql checking of pgsql resultset resource was incorrect. Fix by Bharat Mediratta bharat#menalto.com. +

    Added INFORMIXSERVER environment variable. +

    Added $ADODB_ANSI_PADDING_OFF for interbase/firebird. +

    PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support. +

    4.01 23 Oct 2003 +

    Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells. +

    Fixed insert_id() incorrectly generated when logsql() enabled. +

    Modified PostgreSQL _fixblobs to use list/each instead of foreach. +

    Informix ErrorNo() implemented correctly. +

    Modified several places to use list/each, including GetRowAssoc(). +

    Added UserTimeStamp() to connection class. +

    Added $ADODB_ANSI_PADDING_OFF for oci8po. +

    4.00 20 Oct 2003 +

    Upgraded adodb-xmlschema to 1 Oct 2003 snapshot. +

    Fix to rs2html warning message. Thx to Filo. +

    Fix for odbc_mssql/mssql SQLDate(), hours was wrong. +

    Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson. +

    Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns +

    3.94 11 Oct 2003 +

    Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed. +

    ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed. +

    Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections. +

    Added SQLDate support for sybase. Thx to Chris Phillipson +

    Postgresql checking of pgsql resultset resource was incorrect. Fix by Bharat Mediratta bharat#menalto.com. Same patch applied to _insertid and _affectedrows for adodb-postgres64.inc.php. -

    Added support for NConnect for postgresql. -

    Added Sybase data dict support. Thx to Chris Phillipson -

    Extensive improvements in $perf->UI(), eg. Explain now opens in new window, we show scripts +

    Added support for NConnect for postgresql. +

    Added Sybase data dict support. Thx to Chris Phillipson +

    Extensive improvements in $perf->UI(), eg. Explain now opens in new window, we show scripts which call sql, etc. -

    Perf Monitor UI works with magic quotes enabled. -

    rsPrefix was declared twice. Removed. -

    Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed. -

    Tiraboschi Massimiliano contributed italian language file. -

    Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor. -

    Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT Stéphane. -

    3.92 22 Sept 2003 -

    Added GetAssoc and CacheGetAssoc to connection object. -

    Removed TextMax and CharMax functions from adodb.inc.php. -

    HasFailedTrans() returned false when trans failed. Fixed. -

    Moved perf driver classes into adodb/perf/*.php. -

    Misc improvements to performance monitoring, including UI(). -

    RETVAL in mssql Parameter(), we do not append @ now. -

    Added Param($name) to connection class, returns '?' or ":$name", for defining - bind parameters portably. -

    LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 - _stmt and _affectedrows() bugs. -

    Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT - stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also - added new $conn->datetime field to oci8, controls whether MetaType() returns - 'D' ($this->datetime==false) or 'T' ($this->datetime == true) for DATE type. -

    Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php. -

    Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL(). -

    Tuned include_once handling to reduce file-system checking overhead. -

    3.91 9 Sept 2003 -

    Only released to InterAkt -

    Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory - for driver instantiation. -

    Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com -

    Added portable substr support. -

    Now rs2html() has new parameter, $echo. Set to false to return $html instead - of echoing it. -

    3.90 5 Sept 2003 -

    First beta of performance monitoring released. -

    MySQL supports MetaTable() masking. -

    Fixed key_exists() bug in adodb-lib.inc.php -

    Added sp_executesql Prepare() support to mssql. -

    Added bind support to db2. -

    Added swedish language file - Christian Tiberg" christian#commsoft.nu -

    Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich. -

    Left join setting for oci8 was wrong. Thx to johnwilk#juno.com -

    3.80 27 Aug 2003 -

    Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility. -

    Added matching mask for MetaTables. Only for oci8, mssql and postgres currently. -

    Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano. -

    Added better debugging for Smart Transactions. -

    Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP. -

    ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define - it after including adodb.inc.php. -

    Added portugese (brazilian) to languages. Thx to "Levi Fukumori". -

    Removed arg3 parameter from Execute/SelectLimit/Cache* functions. -

    Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() - to note change in sql query counting with 2-d arrays. -

    Added MONEY to MetaType in PostgreSQL. -

    Added more debugging output to CacheFlush(). -

    3.72 9 Aug 2003 -

    Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes - and does the right thing... -

    Fixed CacheFlush() bug - Thx to martin#gmx.de -

    Walt Boring contributed MetaForeignKeys for postgres7. -

    _fetch() called _BlobDecode() wrongly in interbase. Fixed. -

    adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980 -

    3.71 4 Aug 2003 -

    The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner - == false. -

    Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru. -

    Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com. -

    Error handling in oci8 bugfix - if there was an error in Execute(), then when - calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but - the 2nd call would return no error. -

    Error handling in odbc bugfix. ODBC would always return the last error, even - if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to - 0 everytime before CacheExecute() and Execute(). -

    3.70 29 July 2003 -

    Added new SQLite driver. Tested on PHP 4.3 and PHP 5. -

    Added limited "sapdb" driver support - mainly date support. -

    The oci8 driver did not identify NUMBER with no defined precision correctly. -

    Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls - in GetInsertSQL/GetUpdateSQL. -

    DBDate() and DBTimeStamp() format for postgresql had problems. Fixed. -

    Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit. -

    Added charset support to postgresql. Thx to Julian Tarkhanov. -

    Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS) -

    Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn. -

    adodb-cryptsession.php includes wrong. Fixed. -

    Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8. -

    Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring. -

    adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking - in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn. -

    Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring. -

    Upgraded to adodb-xmlschema.inc.php 0.0.2. -

    NConnect for mysql now returns value. Thx to Dennis Verspuij. -

    ADODB_FETCH_BOTH support added to interbase/firebird. -

    Czech language file contributed by Kamil Jakubovic jake#host.sk. -

    PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec. -

    Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it -

    ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed. -

    3.60 16 June 2003 -

    We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with - mssql driver. -

    The property $emptyDate missing from connection class. Also changed 1903 to - constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn. -

    ADOdb speedup optimization - we now return all arrays by reference. -

    Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. - Suggested by vincent. -

    Added GetArray() to connection class. -

    Added not_null check in informix metacolumns(). -

    Connection parameters for postgresql did not work correctly when port was defined. -

    DB2 is now a tested driver, making adodb 100% compatible. Extensive changes - to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching - to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit() - fixes. -

    The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed. -

    Some bugs in adodb_backtrace() fixed. -

    Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql - properly. -

    MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions - to odbc MetaColumns() for vfp and db2 compat. -

    Added unsigned support to mysql datadict class. Thx to iamsure. -

    Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to - Josh R, Night_Wulfe#hotmail.com. -

    ChangeTableSQL contributed by Florian Buzin. -

    The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with - mssql driver. -


    +

    Perf Monitor UI works with magic quotes enabled. +

    rsPrefix was declared twice. Removed. +

    Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed. +

    Tiraboschi Massimiliano contributed italian language file. +

    Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor. +

    Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT Stéphane.


    0.10 Sept 9 2000 First release -

    Old changelog history moved to old-changelog.htm. +

    Old change log history moved to old-changelog.htm.

     

    -

    - - +

    +

    \ No newline at end of file diff --git a/phpgwapi/inc/adodb/docs/docs-datadict.htm b/phpgwapi/inc/adodb/docs/docs-datadict.htm index a575f4dde8..b6605c3e9e 100644 --- a/phpgwapi/inc/adodb/docs/docs-datadict.htm +++ b/phpgwapi/inc/adodb/docs/docs-datadict.htm @@ -20,22 +20,13 @@

    ADOdb Data Dictionary Library for PHP

    -

    V4.50 6 July 2004 (c) 2000-2004 John Lim (V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my).
    AXMLS (c) 2004 ars Cognita, Inc

    This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.

    - - - - - - -
    Kindly note that the ADOdb home page has -moved to http://adodb.sourceforge.net/ -because of the persistent unreliability of http://php.weblogs.com. Please -change your links!
    +

    Useful ADOdb links: Download   Other Docs

    @@ -57,7 +48,14 @@ generic ODBC. color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.
    # Field types use 1 character codes, and fields are separated by commas.
    # The following example creates three fields: "col1", "col2" and "col3":

    $flds = "
    col1 C(32) NOTNULL DEFAULT 'abc',
    col2 I DEFAULT 0,
    col3 N(12.2)

    ";

    # We demonstrate creating tables and indexes
    $sqlarray = $dict->CreateTableSQL($tabname, $flds, $taboptarray);
    $dict->ExecuteSQLArray($sqlarray);

    $idxflds = 'co11, col2';
    $sqlarray = $dict->CreateIndexSQL($idxname, $tabname, $idxflds);
    $dict->ExecuteSQLArray($sqlarray);

    -

    Functions

    +

    Class Factory

    +

    NewDataDictionary($connection, $drivername=false)

    +

    Creates a new data dictionary object. You pass a database connection object in $connection. The $connection does not have to be actually connected to the database. Some database connection objects are generic (eg. odbtp and odbc). Since 4.53, you can tell ADOdb the actual database with $drivername. E.g.

    +
    +$db =& NewADOConnection('odbtp');
    +$datadict = NewDataDictionary($db, 'mssql'); # force mssql
    +
    +

    Class Functions

    function CreateDatabase($dbname, $optionsarray=false)

    Create a database with the name $dbname;

    function CreateTableSQL($tabname, $fldarray, $taboptarray=false)

    @@ -76,7 +74,7 @@ field. Each row has this format:

    field type can be a portable type codes or the actual type for that database.

    Legal portable type codes include:

    -
      C:  varchar
    X: Largest varchar size
    XL: For Oracle, returns CLOB, otherwise same as 'X' above

    C2: Multibyte varchar
    X2: Multibyte varchar (largest size)

    B: BLOB (binary large object)

    D: Date (some databases do not support this, and we return a datetime type)
    T: Datetime or Timestamp
    L: Integer field suitable for storing booleans (0 or 1)
    I: Integer (mapped to I4)
    I1: 1-byte integer
    I2: 2-byte integer
    I4: 4-byte integer
    I8: 8-byte integer
    F: Floating point number
    N: Numeric or decimal number
    +
      C:  Varchar, capped to 255 characters.
    X: Larger varchar, capped to 4000 characters (to be compatible with Oracle).
    XL: For Oracle, returns CLOB, otherwise the largest varchar size.

    C2: Multibyte varchar
    X2: Multibyte varchar (largest size)

    B: BLOB (binary large object)

    D: Date (some databases do not support this, and we return a datetime type)
    T: Datetime or Timestamp
    L: Integer field suitable for storing booleans (0 or 1)
    I: Integer (mapped to I4)
    I1: 1-byte integer
    I2: 2-byte integer
    I4: 4-byte integer
    I8: 8-byte integer
    F: Floating point number
    N: Numeric or decimal number

    The $colsize field represents the size of the field. If a decimal number is used, then it is assumed that the number following the dot is the precision, so 6.2 means a number of size 6 digits and 2 decimal @@ -104,7 +102,7 @@ Indicates that the previous table definition should be removed Drop table. Useful for removing unused tables.

  • CONSTRAINTS
    Define this as the key, with the constraint as the value. See the -postgresql example below. Additional constraints defined for the whole +postgresql example below. Additional constraints defined for the whole table. You will probably need to prefix this with a comma.
  • Database specific table options can be defined also using the name @@ -113,7 +111,7 @@ the table as ISAM with MySQL, and store the table in the "users" tablespace if using Oracle. And because we specified REPLACE, drop the table first.

      $taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users', 'REPLACE');
    -

    You can also define foreignkey constraints. The following is syntax +

    You can also define foreign key constraints. The following is syntax for postgresql:

      $taboptarray = array('constraints' => ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');
    @@ -127,6 +125,10 @@ $column if field does not exist.

    The class must be connected to the database for ChangeTableSQL to detect the existence of the table. Idea and code contributed by Florian Buzin.

    +

    function RenameTableSQL($tabname,$newname)

    +

    Rename a table. Returns the an array of strings, which is the SQL required to rename a table. Since ADOdb 4.53. Contributed by Ralf Becker.

    +

    function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')

    +

    Rename a table field. Returns the an array of strings, which is the SQL required to rename a column. The optional $flds is a complete column-defintion-string like for AddColumnSQL, only used by mysql at the moment. Since ADOdb 4.53. Contributed by Ralf Becker.

    function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)

      RETURNS:      an array of strings, the sql to be executed, or false
    $idxname: name of index
    $tabname: name of table
    $flds: list of fields as a comma delimited string or an array of strings
    $idxoptarray: array of index creation options
    diff --git a/phpgwapi/inc/adodb/docs/docs-oracle.htm b/phpgwapi/inc/adodb/docs/docs-oracle.htm new file mode 100644 index 0000000000..c0f4598594 --- /dev/null +++ b/phpgwapi/inc/adodb/docs/docs-oracle.htm @@ -0,0 +1,542 @@ + + + + +ADOdb with PHP and Oracle + + + + + +
    +

    Using ADOdb with PHP and Oracle: an advanced tutorial

    +
    +

    (c)2004-2005 John Lim. All rights reserved.

    +

    1. Introduction

    +

    Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:

    +
      +
    • The oracle extension
    • +
    • The oci8 extension
    • +
    • PEAR DB library
    • +
    • ADOdb library
    • +
    +

    The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and show you the advantages of using ADOdb.

    +

    First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a guide to installing Oracle and PHP on Linux.

    + + + + + + + + + +
    Oracle extensionDesigned for Oracle 7 or earlier. This is obsolete.
    Oci8 extension Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).
    +

    Here is an example of using the oci8 extension to query the emp table of the scott schema with bind parameters: +

    +$conn = OCILogon("scott","tiger", $tnsName); 
    +
    +$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno"); 
    +$emp = 7900;
    +OCIBindByName($stmt, ':emp', $emp);
    +$ok = OCIExecute($stmt);
    +while (OCIFetchInto($stmt,$arr)) {
    +	print_r($arr);
    +	echo "<hr>";	
    +} 
    +
    +

    This generates the following output: +

    +Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 ) +
    + Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 ) +
    +

    We also have many higher level PHP libraries that allow you to simplify the above code. The most popular are PEAR DB and ADOdb. Here are some of the differences between these libraries:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FeaturePEAR DB 1.6ADOdb 4.52
    General StyleSimple, easy to use. Lacks Oracle specific functionality.Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.
    Support for PrepareYes, but only on one statement, as the last prepare overwrites previous prepares.Yes (multiple simultaneous prepare's allowed)
    Support for LOBsNoYes, using update semantics
    Support for REF CursorsNoYes
    Support for IN ParametersYesYes
    Support for OUT ParametersNoYes
    Schema creation using XMLNoYes, including ability to define tablespaces and constraints
    Provides database portability featuresNoYes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.
    Performance monitoring and tracingNoYes. SQL can be traced and linked to web page it was executed on. Explain plan support included.
    Recordset caching for frequently used queriesNoYes. Provides great speedups for SQL involving complex where, group-by and order-by clauses.
    PopularityYes, part of PEAR releaseYes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.
    SpeedMedium speed.Very high speed. Fastest database abstraction library available for PHP. Benchmarks are available.
    High Speed Extension availableNoYes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.
    +

    PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about connecting to Oracle later in this guide.

    +

    ADOdb Example

    +

    In ADOdb, the above oci8 example querying the emp table could be written as:

    +
    +include "/path/to/adodb.inc.php";
    +$db = NewADOConnection("oci8");
    +$db->Connect($tnsName, "scott", "tiger");
    +
    +$rs = $db->Execute("select * from emp where empno>:emp order by empno", 
    +                    array('emp' => 7900));
    +while ($arr = $rs->FetchRow()) {
    +    print_r($arr);
    +	echo "<hr>";
    +}
    +
    +

    The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset->FetchRow( ).

    +

    If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:

    + + + + + + + + + +
    Oci8ADOdb
    $stmt = OCIParse($conn,
    +       "select * from emp where empno > :emp"); 
    +$emp = 7900;
    +OCIBindByName($stmt, ':emp', $emp);
    +$ok = OCIExecute($stmt);
    +
    +while (OCIFetchInto($stmt,$arr)) {
    +	print_r($arr);
    +	echo "<hr>";	
    +} 
    $recordset = $db->Execute("select * from emp where empno>:emp", 
    +                           array('emp' => 7900));
    +
    +while ($arr = $recordset->FetchRow()) {
    +	print_r($arr);
    +	echo "<hr>";
    +}
    +

     

    +

    2. ADOdb Query Semantics

    +

    You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the fields property of the recordset object, $rs. +MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset: +

    +$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
    +while (!$rs->EOF) {
    +	print_r($rs->fields);
    +	$rs->MoveNext();
    +}
    +
    +

    And if you are interested in having the data returned in a 2-dimensional array, you can use: +

    +$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
    +
    +

    Now to obtain only the first row as an array: +

    +$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));
    +
    +

    Or to retrieve only the first field of the first row: +

    +$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));
    +
    +

    For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 200: +

    +$offset = 200; $limitrows = 100;
    +$rs = $db->SelectLimit('select * from table', $offset, $limitrows);
    +
    +

    The $limitrows parameter is optional. +

    Array Fetch Mode

    +

    When data is being returned in an array, you can choose the type of array the data is returned in. +

      +
    1. Numeric indexes - use $connection->SetFetchMode(ADODB_FETCH_NUM).
    2. +
    3. Associative indexes - the keys of the array are the names of the fields (in upper-case). Use $connection->SetFetchMode(ADODB_FETCH_ASSOC).
    4. +
    5. Both numeric and associative indexes - use $connection->SetFetchMode(ADODB_FETCH_BOTH).
    6. +
    +

    The default is ADODB_FETCH_BOTH for Oracle.

    +

    Caching

    +

    You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.

    +

    This example will cache the following select statement for 3600 seconds (1 hour):

    +
    +$ADODB_CACHE_DIR = '/var/adodb/tmp';
    +$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");
    +
    +There are analogous CacheGetArray( +), CacheGetRow( ), CacheGetOne( ) and CacheSelectLimit( ) functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above). +

    There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs + property of the connection object: +

    +$ADODB_CACHE_DIR = '/var/adodb/tmp';
    +$connection->cacheSecs = 3600;
    +$rs = $connection->CacheExecute($sql, array('id' => 1));
    +
    +

     

    +

    3. Using Prepare( ) For Frequently Used Statements

    +

    Prepare( ) is for compiling frequently used SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:

    +
    +$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
    +foreach ($arrayToInsert as $key => $value) {
    +	$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
    +}
    +
    +

     

    +

    4. Working With LOBs

    +

    Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory.

    +

    ADOdb will transparently handle LOBs in select statements. The LOBs are automatically converted to PHP variables without any special coding.

    +

    For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory: +

    +$ok = $db->Execute("insert into aTable (id, name, ablob) 
    +                                values (aSequence.nextVal, 'Name', null)");
    +if (!$ok) return LogError($db->ErrorMsg());
    +# params: $tableName, $blobFieldName, $blobValue, $whereClause
    +$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');
    +
    +

    and the analogous CLOB example: +

    +$ok = $db->Execute("insert into aTable (id, name, aclob) 
    +                                values (aSequence.nextVal, 'Name', null)");
    +if (!$ok) return LogError($db->ErrorMsg());
    +$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');
    +
    +

    Note that LogError( ) is a user-defined function, and not part of ADOdb. +

    Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this + (assuming that the photo field is a BLOB, and we want to store $blob_data into + this field, and the primary key is the id field): +

    +	$sql = "INSERT INTO photos ( ID, photo) ".
    +			"VALUES ( :id, empty_blob() )".
    +			" RETURNING photo INTO :xx";
    +
    + 		$stmt = $db->PrepareSP($sql);
    +		$db->InParameter($stmt, $id, 'id');
    +		$blob = $db->InParameter($stmt, $blob_data, 'xx',-1, OCI_B_BLOB);
    +		$db->StartTrans();
    +		$ok = $db->Execute($stmt);
    +		$db->CompleteTrans();
    +
    +

    +

    5. REF CURSORs

    +

    Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function open_tab that returns a REF CURSOR in the first parameter:

    +
    +TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
    +
    +PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
    +	BEGIN
    +		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
    +	END open_tab;
    +
    +

    In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find + all table names that begin with 'A' in the current schema: +

    +$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
    +while ($arr = $rs->FetchRow()) print_r($arr);
    +
    +

    The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor. +

    +

     

    +

    6. In and Out Parameters

    +

    The following PL/SQL +stored procedure requires an input variable, and returns a result into an output variable: +

    +PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
    +	BEGIN
    +		output := 'I love '||input;
    +	END;
    +
    +

    The following ADOdb code allows you to call the stored procedure:

    +
    +$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
    +$input = 'Sophia Loren';
    +$db->InParameter($stmt,$input,'a1');
    +$db->OutParameter($stmt,$output,'a2');
    +$ok = $db->Execute($stmt);
    +if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';
    +
    +

    PrepareSP( ) is a special function that knows about bind parameters. +The main limitation currently is that IN OUT parameters do not work. +

    Bind Parameters and REF CURSORs

    +

    We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later): +

    +$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
    +$input = 'A%';
    +$db->InParameter($stmt,$input,'tabname');
    +$rs = $db->ExecuteCursor($stmt,'refc');
    +while ($arr = $rs->FetchRow()) print_r($arr);
    +
    +

    Bind Parameters and LOBs

    +

    You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs. +

    +	$text = 'test test test';
    +	$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
    +	$stmt = $conn -> PrepareSP($sql);
    +	$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
    +	$rs = '';
    +	$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
    +	$conn -> Execute($stmt);
    +	echo "return = ".$rs."<br>";
    +
    +

    Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs. +

    Reusing Bind Parameters with CURSOR_SHARING=FORCE

    +

    Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:

    +
    +$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
    +
    +

    They prefer entering the values inside the SQL: +

    +$arr = $db->GetArray("select * from emp where empno>7900");
    +
    +

    This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL +is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login: +

    +ALTER SESSION SET CURSOR_SHARING=FORCE
    +
    +

    This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.

    +

    More speedup tips.

    +

     

    +

    7. Dates and Datetime in ADOdb

    +

    There are two things you need to know about dates in ADOdb.

    +

    First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).

    +

    Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:

    +
    +$db = NewADOConnection('oci8');
    +$db->NLS_DATE_FORMAT =  'RRRR-MM-DD HH24:MI:SS';
    +$db->Connect($tns, $user, $pwd);
    +
    +

    Or execute:

    +
    $sql = "ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'";
    +$db->Execute($sql);
    +
    +

    If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead. +

    +

    8. Database Portability Layer

    +

    ADOdb provides the following functions for portably generating SQL functions + as strings to be merged into your SQL statements:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    FunctionDescription
    DBDate($date)Pass in a UNIX timestamp or ISO date and it will convert it to a date + string formatted for INSERT/UPDATE
    DBTimeStamp($date)Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp + string formatted for INSERT/UPDATE
    SQLDate($date, $fmt)Portably generate a date formatted using $fmt mask, for use in SELECT + statements.
    OffsetDate($date, $ndays)Portably generate a $date offset by $ndays.
    Concat($s1, $s2, ...)Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, + which allows || operator.
    IfNull($fld, $replaceNull)Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.
    Param($name)Generates bind placeholders, using ? or named conventions as appropriate.
    $db->sysDateProperty that holds the SQL function that returns today's date
    $db->sysTimeStampProperty that holds the SQL function that returns the current +timestamp (date+time). +
    $db->concat_operatorProperty that holds the concatenation operator +
    $db->lengthProperty that holds the name of the SQL strlen function. +
    $db->upperCaseProperty that holds the name of the SQL strtoupper function. +
    $db->randomProperty that holds the SQL to generate a random number between 0.00 and 1.00. +
    $db->substrProperty that holds the name of the SQL substring function. +
    +

    ADOdb also provides multiple oracle oci8 drivers for different scenarios:

    + + + + + + + + + + + + + + + + + +
    Driver NameDescription
    oci805 Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).
    oci8The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.
    oci8po The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :bindvar for binding variables, which is the standard for other databases. Also the keys of associative arrays are in lower-case like other databases.
    +

    Here's an example of calling the oci8po driver. Note that the bind variables use question-mark:

    +
    $db = NewADOConnection('oci8po');
    +$db->Connect($tns, $user, $pwd);
    +$db->Execute("insert into atable (f1, f2) values (?,?)", array(12, 'abc'));
    +

      +

    9. Connecting to Oracle

    +

    Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at oracle.com.

    +

    Should You Use Persistent Connections

    +

    One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called Shared Server (also known as MTS).

    +

    The author's benchmarks suggest that using non-persistent connections and the Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.

    +

    Connection Examples

    +

    Just in case you are having problems connecting to Oracle, here are some examples:

    +

    a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:

    +
    	$conn = NewADOConnection('oci8');
    +	$conn->Connect(false, 'scott', 'tiger');
    +

    b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:

    +
    	$conn = NewADOConnection('oci8');
    +	$conn->PConnect(false, 'scott', 'tiger', 'myTNS');
    +

    or

    +
     	$conn->PConnect('myTNS', 'scott', 'tiger');
    +

    c. Host Address and SID

    +
    +	$conn->connectSID = true;	
    +	$conn->Connect('192.168.0.1', 'scott', 'tiger', 'SID');
    +

    d. Host Address and Service Name

    +
    	$conn->Connect('192.168.0.1', 'scott', 'tiger', 'servicename');
    +

    e. Oracle connection string: +

    	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
    +			(CONNECT_DATA=(SID=$sid)))";
    +	$conn->Connect($cstr, 'scott', 'tiger');
    +
    +

    f. ADOdb data source names (dsn): +

    +	$dsn = 'oci8://user:pwd@tnsname/?persist';  # persist is optional
    +	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
    +	
    +	$dsn = 'oci8://user:pwd@host/sid';
    +	$conn = ADONewConnection($dsn);
    +	
    +	$dsn = 'oci8://user:pwd@/';   # oracle on local machine
    +	$conn = ADONewConnection($dsn);
    +

    With ADOdb data source names, +you don't have to call Connect( ) or PConnect( ). +

    +

     

    +

    10. Error Checking

    +

    The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is: +

    function InvokeErrorHandler()
    +{
    global $db; ## assume global + MyLogFunction($db->ErrorNo(), $db->ErrorMsg()); +} +if (!$db->Connect($tns, $usr, $pwd)) InvokeErrorHandler(); + +$rs = $db->Execute("select * from emp where empno>:emp order by empno", + array('emp' => 7900)); +if (!$rs) return InvokeErrorHandler(); +while ($arr = $rs->FetchRow()) { + print_r($arr); + echo "<hr>"; +} +
    +

    You can retrieve the error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also define a custom error handler function. +ADOdb also supports throwing exceptions in PHP5. +

     

    +

    Handling Large Recordsets (added 27 May 2005)

    +The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount() +is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default. +We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets. + Set $ADODB_COUNTRECS to false for the best performance. +

    +This variable is checked every time a query is executed, so you can selectively choose which recordsets to count. +

     

    +

    11. Other ADOdb Features

    +

    Schema generation. This allows you to define a schema using XML and import it into different RDBMS systems portably.

    +

    Performance monitoring and tracing. Highlights of performance monitoring include identification of poor and suspicious SQL, with explain plan support, and identifying which web pages the SQL ran on.

    +

     

    +

    12. Download

    +

    You can download ADOdb from sourceforge. ADOdb uses a BSD style license. That means that it is free for commercial use, and redistribution without source code is allowed.

    +

     

    +

    13. Resources

    + + + diff --git a/phpgwapi/inc/adodb/docs/docs-perf.htm b/phpgwapi/inc/adodb/docs/docs-perf.htm index edfbc22d4a..68b1109f94 100644 --- a/phpgwapi/inc/adodb/docs/docs-perf.htm +++ b/phpgwapi/inc/adodb/docs/docs-perf.htm @@ -18,20 +18,10 @@ font-size: 8pt;

    The ADOdb Performance Monitoring Library

    -

    V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)

    +

    V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my)

    This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.

    - - - - - - -
    Kindly note that the ADOdb home page has -moved to http://adodb.sourceforge.net/ -because of the persistent unreliability of http://php.weblogs.com. Please -change your links!

    Useful ADOdb links: Download   Other Docs

    diff --git a/phpgwapi/inc/adodb/docs/docs-session.htm b/phpgwapi/inc/adodb/docs/docs-session.htm index d51dbec557..7aeb05d80d 100644 --- a/phpgwapi/inc/adodb/docs/docs-session.htm +++ b/phpgwapi/inc/adodb/docs/docs-session.htm @@ -21,24 +21,11 @@ font-size: 8pt;

    ADODB Session Management Manual

    -V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my) +V4.65 22 July 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my)

    This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products. - - - - - - - - -
    Kindly note that the ADOdb home page has -moved to http://adodb.sourceforge.net/ -because of the persistent unreliability of http://php.weblogs.com. Please -change your links!
    -

    Useful ADOdb links: Download   Other Docs

    @@ -61,9 +48,12 @@ However if you have special needs such as you:
  • Need to do special processing of each session
  • Require notification when a session expires
  • -

    Then the ADOdb session handler provides you with the above +

    The ADOdb session handler provides you with the above additional capabilities by storing the session information as records in a database table that can be shared across multiple servers.

    +

    These records will be garbage collected based on the php.ini [session] timeout settings. +You can register a notification function to notify you when the record has expired and +is about to be freed by the garbage collector.

    Important Upgrade Notice: Since ADOdb 4.05, the session files have been moved to its own folder, adodb/session. This is a rewrite of the session code by Ross Smith. The old session code is in @@ -92,11 +82,40 @@ including adodb-cryptsession.inc.php instead of adodb-session.inc.php.

          include('adodb/adodb.inc.php');

    $ADODB_SESSION_DRIVER='mysql';
    $ADODB_SESSION_CONNECT='localhost';
    $ADODB_SESSION_USER ='scott';
    $ADODB_SESSION_PWD ='tiger';
    $ADODB_SESSION_DB ='sessiondb';


    include('adodb/session/adodb-session.php');
    session_start();

    #
    # Test session vars, the following should increment on refresh
    #
    $_SESSION['AVAR'] += 1;
    print "<p>\$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";
    -

    To force non-persistent connections, call adodb_session_open first before session_start():

    + +

    To force non-persistent connections, call adodb_session_open() first before session_start(): +

      
    include('adodb/adodb.inc.php');

    $ADODB_SESSION_DRIVER='mysql';
    $ADODB_SESSION_CONNECT='localhost';
    $ADODB_SESSION_USER ='scott';
    $ADODB_SESSION_PWD ='tiger';
    $ADODB_SESSION_DB ='sessiondb';


    include('adodb/session/adodb-session.php');
    adodb_sess_open(false,false,false);

    session_start();
    -

    To use a encrypted sessions, simply replace the file adodb-session.php:

    +

    The 3rd parameter to adodb_sess_open($path, $sessname, $connectMode) sets the connection method. You can pass in the following:

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    $connectModeConnection Method
    true

    PConnect( )

    falseConnect( )
    'N'NConnect( )
    'P'PConnect( )
    'C'Connect( )
    +

    To use a encrypted sessions, simply replace the file adodb-session.php:

     
    include('adodb/adodb.inc.php');

    $ADODB_SESSION_DRIVER='mysql';
    $ADODB_SESSION_CONNECT='localhost';
    $ADODB_SESSION_USER ='scott';
    $ADODB_SESSION_PWD ='tiger';
    $ADODB_SESSION_DB ='sessiondb';

    include('adodb/session/adodb-cryptsession.php');

    session_start();

    @@ -120,22 +139,35 @@ including adodb-cryptsession.inc.php instead of adodb-session.inc.php.

    When the session is created, $ADODB_SESS_CONN holds the connection object.

    3. Recommended is PHP 4.0.6 or later. There are documented session bugs in earlier versions of PHP.

    Notifications

    -

    If you want to receive notification when a session expires, then tag -the session record with a EXPIREREF tag (see -the definition of the sessions table above). Before any session record -is deleted, ADOdb will call a notification function, passing in the -EXPIREREF. -

    -

    When a session is first created, we check a global variable -$ADODB_SESSION_EXPIRE_NOTIFY. This is an array with 2 elements, the +

    You can receive notification when your session is cleaned up by the session garbage collector or +when you call session_destroy(). +

    PHP's session extension will automatically run a special garbage collection function based on +your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call +adodb's garbage collection function, which can be setup to do notification. +

    +

    +	PHP Session --> ADOdb Session  --> Find all recs  --> Send          --> Delete queued
    +	GC Function     GC Function        to be deleted      notification      records
    +	executed at     called by                             for all recs
    +	random time     Session Extension                     queued for deletion
    +
    +

    When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically +the userid of the session. Later when the session has expired, just before the record is deleted, +we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which +is the userid of the person being logged off. +

    ADOdb use a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session +start to store the notification configuratioin. +$ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the first being the name of the session variable you would like to store in the EXPIREREF field, and the 2nd is the notification function's name.

    -

    Suppose we want to be notified when a user's session has expired, -based on the userid. The user id in the global session variable -$USERID. The function name is 'NotifyFn'. So we define:

    +

    For example, suppose we want to be notified when a user's session has expired, +based on the userid. When the user logs in, we store the id in the global session variable +$USERID. The function name is 'NotifyFn'. +

    +So we define (before session_start() is called):

     
    $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
    -And when the NotifyFn is called (when the session expires), we pass the -$USERID as the first parameter, eg. NotifyFn($userid, $sesskey). The +And when the NotifyFn is called (when the session expires), the +$USERID is passed in as the first parameter, eg. NotifyFn($userid, $sesskey). The session key (which is the primary key of the record in the sessions table) is the 2nd parameter.

    Here is an example of a Notification function that deletes some @@ -173,6 +205,28 @@ compression schemes are supported. Currently, supported are:

    These are stackable. E.g.

    ADODB_Session::filter(new ADODB_Compress_Bzip2());
    ADODB_Session::filter(new ADODB_Encrypt_MD5());
    will compress and then encrypt the record in the database. +

    adodb_session_regenerate_id()

    +

    Dynamically change the current session id with a newly generated one and update database. Currently only +works with cookies. Useful to improve security by reducing the risk of session-hijacking. +See this article on Session Fixation for more info +on the theory behind this feature. Usage: +

    +	$ADODB_SESSION_DRIVER='mysql';
    +	$ADODB_SESSION_CONNECT='localhost';
    +	$ADODB_SESSION_USER ='root';
    +	$ADODB_SESSION_PWD ='abc';
    +	$ADODB_SESSION_DB ='phplens';
    +	
    +	include('path/to/adodb/session/adodb-session.php');
    +	
    +	session_start();
    +	# Every 10 page loads, reset cookie for safety.
    +	# This is extremely simplistic example, better 
    +	# to regenerate only when the user logs in or changes
    +	# user privilege levels.
    +	if ((rand()%10) == 0) adodb_session_regenerate_id(); 
    +

    This function calls session_regenerate_id() internally or simulates it if the function does not exist. +

    More Info

    Also see the core ADOdb documentation.

    diff --git a/phpgwapi/inc/adodb/docs/old-changelog.htm b/phpgwapi/inc/adodb/docs/old-changelog.htm index f43111ca17..284f3ad1d8 100644 --- a/phpgwapi/inc/adodb/docs/old-changelog.htm +++ b/phpgwapi/inc/adodb/docs/old-changelog.htm @@ -1,4 +1,126 @@ +Old Changelog: ADOdb

    Old Changelog

    + +

    3.92 22 Sept 2003 +

    Added GetAssoc and CacheGetAssoc to connection object. +

    Removed TextMax and CharMax functions from adodb.inc.php. +

    HasFailedTrans() returned false when trans failed. Fixed. +

    Moved perf driver classes into adodb/perf/*.php. +

    Misc improvements to performance monitoring, including UI(). +

    RETVAL in mssql Parameter(), we do not append @ now. +

    Added Param($name) to connection class, returns '?' or ":$name", for defining + bind parameters portably. +

    LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 + _stmt and _affectedrows() bugs. +

    Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT + stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also + added new $conn->datetime field to oci8, controls whether MetaType() returns + 'D' ($this->datetime==false) or 'T' ($this->datetime == true) for DATE type. +

    Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php. +

    Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL(). +

    Tuned include_once handling to reduce file-system checking overhead. +

    3.91 9 Sept 2003 +

    Only released to InterAkt +

    Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory + for driver instantiation. +

    Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com +

    Added portable substr support. +

    Now rs2html() has new parameter, $echo. Set to false to return $html instead + of echoing it. +

    3.90 5 Sept 2003 +

    First beta of performance monitoring released. +

    MySQL supports MetaTable() masking. +

    Fixed key_exists() bug in adodb-lib.inc.php +

    Added sp_executesql Prepare() support to mssql. +

    Added bind support to db2. +

    Added swedish language file - Christian Tiberg" christian#commsoft.nu +

    Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich. +

    Left join setting for oci8 was wrong. Thx to johnwilk#juno.com +

    3.80 27 Aug 2003 +

    Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility. +

    Added matching mask for MetaTables. Only for oci8, mssql and postgres currently. +

    Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano. +

    Added better debugging for Smart Transactions. +

    Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP. +

    ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define + it after including adodb.inc.php. +

    Added portugese (brazilian) to languages. Thx to "Levi Fukumori". +

    Removed arg3 parameter from Execute/SelectLimit/Cache* functions. +

    Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() + to note change in sql query counting with 2-d arrays. +

    Added MONEY to MetaType in PostgreSQL. +

    Added more debugging output to CacheFlush(). +

    3.72 9 Aug 2003 +

    Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes + and does the right thing... +

    Fixed CacheFlush() bug - Thx to martin#gmx.de +

    Walt Boring contributed MetaForeignKeys for postgres7. +

    _fetch() called _BlobDecode() wrongly in interbase. Fixed. +

    adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980 +

    3.71 4 Aug 2003 +

    The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner + == false. +

    Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru. +

    Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com. +

    Error handling in oci8 bugfix - if there was an error in Execute(), then when + calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but + the 2nd call would return no error. +

    Error handling in odbc bugfix. ODBC would always return the last error, even + if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to + 0 everytime before CacheExecute() and Execute(). +

    3.70 29 July 2003 +

    Added new SQLite driver. Tested on PHP 4.3 and PHP 5. +

    Added limited "sapdb" driver support - mainly date support. +

    The oci8 driver did not identify NUMBER with no defined precision correctly. +

    Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls + in GetInsertSQL/GetUpdateSQL. +

    DBDate() and DBTimeStamp() format for postgresql had problems. Fixed. +

    Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit. +

    Added charset support to postgresql. Thx to Julian Tarkhanov. +

    Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS) +

    Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn. +

    adodb-cryptsession.php includes wrong. Fixed. +

    Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8. +

    Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring. +

    adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking + in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn. +

    Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring. +

    Upgraded to adodb-xmlschema.inc.php 0.0.2. +

    NConnect for mysql now returns value. Thx to Dennis Verspuij. +

    ADODB_FETCH_BOTH support added to interbase/firebird. +

    Czech language file contributed by Kamil Jakubovic jake#host.sk. +

    PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec. +

    Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it +

    ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed. +

    3.60 16 June 2003 +

    We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with + mssql driver. +

    The property $emptyDate missing from connection class. Also changed 1903 to + constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn. +

    ADOdb speedup optimization - we now return all arrays by reference. +

    Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. + Suggested by vincent. +

    Added GetArray() to connection class. +

    Added not_null check in informix metacolumns(). +

    Connection parameters for postgresql did not work correctly when port was defined. +

    DB2 is now a tested driver, making adodb 100% compatible. Extensive changes + to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching + to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit() + fixes. +

    The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed. +

    Some bugs in adodb_backtrace() fixed. +

    Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql + properly. +

    MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions + to odbc MetaColumns() for vfp and db2 compat. +

    Added unsigned support to mysql datadict class. Thx to iamsure. +

    Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to + Josh R, Night_Wulfe#hotmail.com. +

    ChangeTableSQL contributed by Florian Buzin. +

    The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with + mssql driver. +

    +

    3.50 19 May 2003

    Fixed mssql compat with FreeTDS. FreeTDS does not implement mssql_fetch_assoc().

    Merged back connection and recordset code into adodb.inc.php. @@ -697,4 +819,4 @@ and Insert_ID. Added above functions to test.php.

    0.10 Sept 9 2000

    First release

    -

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

    ",$t,' ';var_dump($f->value); echo '

    '; + switch($t) { + case 135: // timestamp + if (!strlen((string)$f->value)) $this->fields[] = false; + else { + if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value); + else $val = $f->value; + $this->fields[] = adodb_date('Y-m-d H:i:s',$val); + } + break; + case 133:// A date value (yyyymmdd) + if ($val = $f->value) { + $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2); + } else + $this->fields[] = false; + break; + case 7: // adDate + if (!strlen((string)$f->value)) $this->fields[] = false; + else { + if (!is_numeric($f->value)) $val = variant_date_to_timestamp($f->value); + else $val = $f->value; + + if (($val % 86400) == 0) $this->fields[] = adodb_date('Y-m-d',$val); + else $this->fields[] = adodb_date('Y-m-d H:i:s',$val); + } + break; + case 1: // null + $this->fields[] = false; + break; + case 6: // currency is not supported properly; + ADOConnection::outp( ''.$f->Name.': currency type not supported by PHP'); + $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; + } + +} + +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-ado_access.inc.php b/phpgwapi/inc/adodb/drivers/adodb-ado_access.inc.php index c638c454ec..9b41a92465 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-ado_access.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-ado_access.inc.php @@ -1,6 +1,6 @@ = 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php"); + else include(ADODB_DIR."/drivers/adodb-ado.inc.php"); } class ADODB_ado_access extends ADODB_ado { @@ -33,6 +34,10 @@ class ADODB_ado_access extends ADODB_ado { } function BeginTrans() { return false;} + + function CommitTrans() { return false;} + + function RollbackTrans() { return false;} } diff --git a/phpgwapi/inc/adodb/drivers/adodb-ado_mssql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-ado_mssql.inc.php index 1ae1e40db2..d9c563f986 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-ado_mssql.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-ado_mssql.inc.php @@ -1,6 +1,6 @@ = 5) include(ADODB_DIR."/drivers/adodb-ado5.inc.php"); + else include(ADODB_DIR."/drivers/adodb-ado.inc.php"); } @@ -54,35 +55,36 @@ class ADODB_ado_mssql extends ADODB_ado { function MetaColumns($table) { - $table = strtoupper($table); - $arr= array(); - $dbc = $this->_connectionID; - - $osoptions = array(); - $osoptions[0] = null; - $osoptions[1] = null; - $osoptions[2] = $table; - $osoptions[3] = null; - - $adors=@$dbc->OpenSchema(4, $osoptions);//tables + $table = strtoupper($table); + $arr= array(); + $dbc = $this->_connectionID; + + $osoptions = array(); + $osoptions[0] = null; + $osoptions[1] = null; + $osoptions[2] = $table; + $osoptions[3] = null; + + $adors=@$dbc->OpenSchema(4, $osoptions);//tables + + if ($adors){ + while (!$adors->EOF){ + $fld = new ADOFieldObject(); + $c = $adors->Fields(3); + $fld->name = $c->Value; + $fld->type = 'CHAR'; // cannot discover type in ADO! + $fld->max_length = -1; + $arr[strtoupper($fld->name)]=$fld; + + $adors->MoveNext(); + } + $adors->Close(); + } + $false = false; + return empty($arr) ? $false : $arr; + } - if ($adors){ - while (!$adors->EOF){ - $fld = new ADOFieldObject(); - $c = $adors->Fields(3); - $fld->name = $c->Value; - $fld->type = 'CHAR'; // cannot discover type in ADO! - $fld->max_length = -1; - $arr[strtoupper($fld->name)]=$fld; - - $adors->MoveNext(); - } - $adors->Close(); - } - - return $arr; - } - } + } // end class class ADORecordSet_ado_mssql extends ADORecordSet_ado { diff --git a/phpgwapi/inc/adodb/drivers/adodb-borland_ibase.inc.php b/phpgwapi/inc/adodb/drivers/adodb-borland_ibase.inc.php index 6cea9d19cc..2a5125820e 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-borland_ibase.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-borland_ibase.inc.php @@ -1,6 +1,6 @@ GetOne($this->identitySQL); } - function RowLock($tables,$where) + function RowLock($tables,$where,$flds='1 as ignore') { if ($this->_autocommit) $this->BeginTrans(); - return $this->GetOne("select 1 as ignore from $tables where $where for update"); + return $this->GetOne("select $flds from $tables where $where for update"); } function &MetaTables($ttype=false,$showSchema=false, $qtable="%", $qschema="%") @@ -145,8 +145,10 @@ class ADODB_DB2 extends ADODB_odbc { $rs = new ADORecordSet_odbc($qid); $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; - + if (!$rs) { + $false = false; + return $false; + } $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; $arr =& $rs->GetArray(); @@ -175,7 +177,45 @@ class ADODB_DB2 extends ADODB_odbc { } return $arr2; } - + + function &MetaIndexes ($table, $primary = FALSE, $owner=false) + { + // save old fetch mode + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + $false = false; + // get index details + $table = strtoupper($table); + $SQL="SELECT NAME, UNIQUERULE, COLNAMES FROM SYSIBM.SYSINDEXES WHERE TBNAME='$table'"; + if ($primary) + $SQL.= " AND UNIQUERULE='P'"; + $rs = $this->Execute($SQL); + if (!is_object($rs)) { + if (isset($savem)) + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + return $false; + } + $indexes = array (); + // parse index data into array + while ($row = $rs->FetchRow()) { + $indexes[$row[0]] = array( + 'unique' => ($row[1] == 'U' || $row[1] == 'P'), + 'columns' => array() + ); + $cols = ltrim($row[2],'+'); + $indexes[$row[0]]['columns'] = explode('+', $cols); + } + if (isset($savem)) { + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + } + return $indexes; + } // Format date column in sql string given an input format that understands Y M D function SQLDate($fmt, $col=false) @@ -274,12 +314,14 @@ class ADORecordSet_db2 extends ADORecordSet_odbc { case 'VARCHAR': case 'CHAR': case 'CHARACTER': + case 'C': if ($len <= $this->blobSize) return 'C'; case 'LONGCHAR': case 'TEXT': case 'CLOB': case 'DBCLOB': // double-byte + case 'X': return 'X'; case 'BLOB': @@ -288,10 +330,12 @@ class ADORecordSet_db2 extends ADORecordSet_odbc { return 'B'; case 'DATE': + case 'D': return 'D'; case 'TIME': case 'TIMESTAMP': + case 'T': return 'T'; //case 'BOOLEAN': @@ -305,6 +349,7 @@ class ADORecordSet_db2 extends ADORecordSet_odbc { case 'INTEGER': case 'BIGINT': case 'SMALLINT': + case 'I': return 'I'; default: return 'N'; diff --git a/phpgwapi/inc/adodb/drivers/adodb-fbsql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-fbsql.inc.php index 55c00c8e00..2c76242813 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-fbsql.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-fbsql.inc.php @@ -1,6 +1,6 @@ fetchMode = FBSQL_NUM; break; - default: - case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break; case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break; + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = FBSQL_BOTH; break; } return $this->ADORecordSet($queryID); } diff --git a/phpgwapi/inc/adodb/drivers/adodb-firebird.inc.php b/phpgwapi/inc/adodb/drivers/adodb-firebird.inc.php index d45d147305..24cacb159c 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-firebird.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-firebird.inc.php @@ -1,6 +1,6 @@ _connectionID = $fn($argHostname,$argUsername,$argPassword, + if ($this->role) + $this->_connectionID = $fn($argHostname,$argUsername,$argPassword, + $this->charSet,$this->buffers,$this->dialect,$this->role); + else + $this->_connectionID = $fn($argHostname,$argUsername,$argPassword, $this->charSet,$this->buffers,$this->dialect); if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html @@ -186,7 +191,7 @@ class ADODB_ibase extends ADOConnection { { // save old fetch mode global $ADODB_FETCH_MODE; - + $false = false; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== FALSE) { @@ -207,7 +212,7 @@ class ADODB_ibase extends ADOConnection { $this->SetFetchMode($savem); } $ADODB_FETCH_MODE = $save; - return FALSE; + return $false; } $indexes = array (); @@ -475,61 +480,61 @@ class ADODB_ibase extends ADOConnection { { global $ADODB_FETCH_MODE; - if ($this->metaColumnsSQL) { - - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - - $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); - - $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; - - $retarr = array(); - //OPN STUFF start - $dialect3 = ($this->dialect==3 ? true : false); - //OPN STUFF end - while (!$rs->EOF) { //print_r($rs->fields); - $fld = new ADOFieldObject(); - $fld->name = trim($rs->fields[0]); - //OPN STUFF start - $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3); - if (isset($rs->fields[1]) && $rs->fields[1]) { - $fld->not_null = true; - } - if (isset($rs->fields[2])) { - - $fld->has_default = true; - $d = substr($rs->fields[2],strlen('default ')); - switch ($fld->type) - { - case 'smallint': - case 'integer': $fld->default_value = (int) $d; break; - case 'char': - case 'blob': - case 'text': - case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break; - case 'double': - case 'float': $fld->default_value = (float) $d; break; - default: $fld->default_value = $d; break; - } - // case 35:$tt = 'TIMESTAMP'; break; - } - if ((isset($rs->fields[5])) && ($fld->type == 'blob')) { - $fld->sub_type = $rs->fields[5]; - } else { - $fld->sub_type = null; - } - //OPN STUFF end - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; - - $rs->MoveNext(); - } - $rs->Close(); - return $retarr; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + + $ADODB_FETCH_MODE = $save; + $false = false; + if ($rs === false) { + return $false; } - return false; + + $retarr = array(); + //OPN STUFF start + $dialect3 = ($this->dialect==3 ? true : false); + //OPN STUFF end + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = trim($rs->fields[0]); + //OPN STUFF start + $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3); + if (isset($rs->fields[1]) && $rs->fields[1]) { + $fld->not_null = true; + } + if (isset($rs->fields[2])) { + + $fld->has_default = true; + $d = substr($rs->fields[2],strlen('default ')); + switch ($fld->type) + { + case 'smallint': + case 'integer': $fld->default_value = (int) $d; break; + case 'char': + case 'blob': + case 'text': + case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break; + case 'double': + case 'float': $fld->default_value = (float) $d; break; + default: $fld->default_value = $d; break; + } + // case 35:$tt = 'TIMESTAMP'; break; + } + if ((isset($rs->fields[5])) && ($fld->type == 'blob')) { + $fld->sub_type = $rs->fields[5]; + } else { + $fld->sub_type = null; + } + //OPN STUFF end + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + + $rs->MoveNext(); + } + $rs->Close(); + if ( empty($retarr)) return $false; + else return $retarr; } function BlobEncode( $blob ) diff --git a/phpgwapi/inc/adodb/drivers/adodb-informix.inc.php b/phpgwapi/inc/adodb/drivers/adodb-informix.inc.php index f8b0bec8f9..a19023885b 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-informix.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-informix.inc.php @@ -1,6 +1,6 @@ ADORecordset_informix72($id,$mode); diff --git a/phpgwapi/inc/adodb/drivers/adodb-informix72.inc.php b/phpgwapi/inc/adodb/drivers/adodb-informix72.inc.php index 36e579cafe..ca03cb6ba8 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-informix72.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-informix72.inc.php @@ -1,6 +1,6 @@ version)) return $this->version; $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1"); - $arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1"); + $arr['version'] = $this->GetOne("select DBINFO('version','major') || DBINFO('version','minor') from systables where tabid = 1"); $this->version = $arr; return $arr; } @@ -123,10 +123,10 @@ class ADODB_informix72 extends ADOConnection { return true; } - function RowLock($tables,$where) + function RowLock($tables,$where,$flds='1 as ignore') { if ($this->_autocommit) $this->BeginTrans(); - return $this->GetOne("select 1 as ignore from $tables where $where for update"); + return $this->GetOne("select $flds from $tables where $where for update"); } /* Returns: the last error message from previous database operation @@ -141,7 +141,7 @@ class ADODB_informix72 extends ADOConnection { function ErrorNo() { - preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS + preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; return 0; } @@ -151,6 +151,7 @@ class ADODB_informix72 extends ADOConnection { { global $ADODB_FETCH_MODE; + $false = false; if (!empty($this->metaColumnsSQL)) { $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; @@ -158,16 +159,27 @@ class ADODB_informix72 extends ADOConnection { $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; + if ($rs === false) return $false; $rspkey = $this->Execute(sprintf($this->metaPrimaryKeySQL,$table)); //Added to get primary key colno items $retarr = array(); while (!$rs->EOF) { //print_r($rs->fields); $fld = new ADOFieldObject(); $fld->name = $rs->fields[0]; +/* //!eos. + $rs->fields[1] is not the correct adodb type + $rs->fields[2] is not correct max_length, because can include not-null bit + $fld->type = $rs->fields[1]; $fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields); //Added to set primary key flag - $fld->max_length = $rs->fields[2]; + $fld->max_length = $rs->fields[2];*/ + $pr=ifx_props($rs->fields[1],$rs->fields[2]); //!eos + $fld->type = $pr[0] ;//!eos + $fld->primary_key=$rspkey->fields && array_search($rs->fields[4],$rspkey->fields); + $fld->max_length = $pr[1]; //!eos + $fld->precision = $pr[2] ;//!eos + $fld->not_null = $pr[3]=="N"; //!eos + if (trim($rs->fields[3]) != "AAAAAA 0") { $fld->has_default = 1; $fld->default_value = $rs->fields[3]; @@ -180,10 +192,11 @@ class ADODB_informix72 extends ADOConnection { } $rs->Close(); + $rspKey->Close(); //!eos return $retarr; } - return false; + return $false; } function &xMetaColumns($table) @@ -191,6 +204,38 @@ class ADODB_informix72 extends ADOConnection { return ADOConnection::MetaColumns($table,false); } + function MetaForeignKeys($table, $owner=false, $upper=false) //!Eos + { + $sql = " + select tr.tabname,updrule,delrule, + i.part1 o1,i2.part1 d1,i.part2 o2,i2.part2 d2,i.part3 o3,i2.part3 d3,i.part4 o4,i2.part4 d4, + i.part5 o5,i2.part5 d5,i.part6 o6,i2.part6 d6,i.part7 o7,i2.part7 d7,i.part8 o8,i2.part8 d8 + from systables t,sysconstraints s,sysindexes i, + sysreferences r,systables tr,sysconstraints s2,sysindexes i2 + where t.tabname='$table' + and s.tabid=t.tabid and s.constrtype='R' and r.constrid=s.constrid + and i.idxname=s.idxname and tr.tabid=r.ptabid + and s2.constrid=r.primary and i2.idxname=s2.idxname"; + + $rs = $this->Execute($sql); + if (!$rs || $rs->EOF) return false; + $arr =& $rs->GetArray(); + $a = array(); + foreach($arr as $v) { + $coldest=$this->metaColumnNames($v["tabname"]); + $colorig=$this->metaColumnNames($table); + $colnames=array(); + for($i=1;$i<=8 && $v["o$i"] ;$i++) { + $colnames[]=$coldest[$v["d$i"]-1]."=".$colorig[$v["o$i"]-1]; + } + if($upper) + $a[strtoupper($v["tabname"])] = $colnames; + else + $a[$v["tabname"]] = $colnames; + } + return $a; + } + function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB') { $type = ($blobtype == 'TEXT') ? 1 : 0; @@ -331,7 +376,8 @@ class ADORecordset_informix72 extends ADORecordSet { $o->not_null = $arr[4]=="N"; } } - return $this->_fieldprops[$fieldOffset]; + $ret = $this->_fieldprops[$fieldOffset]; + return $ret; } function _initrs() @@ -342,7 +388,7 @@ class ADORecordset_informix72 extends ADORecordSet { function _seek($row) { - return @ifx_fetch_row($this->_queryID, $row); + return @ifx_fetch_row($this->_queryID, (int) $row); } function MoveLast() @@ -401,4 +447,29 @@ class ADORecordset_informix72 extends ADORecordSet { } } +/** !Eos +* Auxiliar function to Parse coltype,collength. Used by Metacolumns +* return: array ($mtype,$length,$precision,$nullable) (similar to ifx_fieldpropierties) +*/ +function ifx_props($coltype,$collength){ + $itype=fmod($coltype+1,256); + $nullable=floor(($coltype+1) /256) ?"N":"Y"; + $mtype=substr(" CIIFFNNDN TBXCC ",$itype,1); + switch ($itype){ + case 2: + $length=4; + case 6: + case 9: + case 14: + $length=floor($collength/256); + $precision=fmod($collength,256); + break; + default: + $precision=0; + $length=$collength; + } + return array($mtype,$length,$precision,$nullable); +} + + ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-ldap.inc.php b/phpgwapi/inc/adodb/drivers/adodb-ldap.inc.php index 220ee9d0d5..1b676eefe3 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-ldap.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-ldap.inc.php @@ -1,11 +1,15 @@ _connectionID = ldap_connect( $conn_info[0], $conn_info[1] ) - or die( 'Could not connect to ' . $this->_connectionID ); - if ($username && $password) { - $bind = ldap_bind( $this->_connectionID, $username, $password ) - or die( 'Could not bind to ' . $this->_connectionID . ' with $username & $password'); - } else { - $bind = ldap_bind( $this->_connectionID ) - or die( 'Could not bind anonymously to ' . $this->_connectionID ); - } - return $this->_connectionID; - } + global $LDAP_CONNECT_OPTIONS; + + if ( !function_exists( 'ldap_connect' ) ) return null; + + $conn_info = array( $host,$this->port); + + if ( strstr( $host, ':' ) ) { + $conn_info = split( ':', $host ); + } + + $this->_connectionID = ldap_connect( $conn_info[0], $conn_info[1] ); + if (!$this->_connectionID) { + $e = 'Could not connect to ' . $conn_info[0]; + $this->_errorMsg = $e; + if ($this->debug) ADOConnection::outp($e); + return false; + } + if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) { + $this->_inject_bind_options( $LDAP_CONNECT_OPTIONS ); + } + + if ($username) { + $bind = ldap_bind( $this->_connectionID, $username, $password ); + } else { + $username = 'anonymous'; + $bind = ldap_bind( $this->_connectionID ); + } + + if (!$bind) { + $e = 'Could not bind to ' . $conn_info[0] . " as ".$username; + $this->_errorMsg = $e; + if ($this->debug) ADOConnection::outp($e); + return false; + } + $this->_errorMsg = ''; + $this->database = $ldapbase; + return $this->_connectionID; + } +/* + Valid Domain Values for LDAP Options: + + LDAP_OPT_DEREF (integer) + LDAP_OPT_SIZELIMIT (integer) + LDAP_OPT_TIMELIMIT (integer) + LDAP_OPT_PROTOCOL_VERSION (integer) + LDAP_OPT_ERROR_NUMBER (integer) + LDAP_OPT_REFERRALS (boolean) + LDAP_OPT_RESTART (boolean) + LDAP_OPT_HOST_NAME (string) + LDAP_OPT_ERROR_STRING (string) + LDAP_OPT_MATCHED_DN (string) + LDAP_OPT_SERVER_CONTROLS (array) + LDAP_OPT_CLIENT_CONTROLS (array) + + Make sure to set this BEFORE calling Connect() + + Example: + + $LDAP_CONNECT_OPTIONS = Array( + Array ( + "OPTION_NAME"=>LDAP_OPT_DEREF, + "OPTION_VALUE"=>2 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_SIZELIMIT, + "OPTION_VALUE"=>100 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_TIMELIMIT, + "OPTION_VALUE"=>30 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION, + "OPTION_VALUE"=>3 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER, + "OPTION_VALUE"=>13 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_REFERRALS, + "OPTION_VALUE"=>FALSE + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_RESTART, + "OPTION_VALUE"=>FALSE + ) + ); +*/ + + function _inject_bind_options( $options ) { + foreach( $options as $option ) { + ldap_set_option( $this->_connectionID, $option["OPTION_NAME"], $option["OPTION_VALUE"] ) + or die( "Unable to set server option: " . $option["OPTION_NAME"] ); + } + } /* returns _queryID or false */ function _query($sql,$inputarr) { - $rs = ldap_search( $this->_connectionID, $this->database, $sql ); - return $rs; - + $rs = ldap_search( $this->_connectionID, $this->database, $sql ); + $this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql; + return $rs; } /* closes the LDAP connection */ @@ -72,9 +161,14 @@ class ADODB_ldap extends ADOConnection { $this->_connectionID = false; } + function SelectDB($db) { + $this->database = $db; + return true; + } // SelectDB + function ServerInfo() { - if( is_array( $this->version ) ) return $this->version; + if( !empty( $this->version ) ) return $this->version; $version = array(); /* Determines how aliases are handled during search. @@ -160,8 +254,8 @@ class ADODB_ldap extends ADOConnection { } /* The host name (or list of hosts) for the primary LDAP server. */ ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); - ldap_get_option( $this->_connectionID, OPT_ERROR_NUMBER, $version['OPT_ERROR_NUMBER'] ); - ldap_get_option( $this->_connectionID, OPT_ERROR_STRING, $version['OPT_ERROR_STRING'] ); + ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_NUMBER, $version['LDAP_OPT_ERROR_NUMBER'] ); + ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_STRING, $version['LDAP_OPT_ERROR_STRING'] ); ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); return $this->version = $version; @@ -193,9 +287,9 @@ class ADORecordSet_ldap extends ADORecordSet{ case ADODB_FETCH_ASSOC: $this->fetchMode = LDAP_ASSOC; break; - default: case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH: + default: $this->fetchMode = LDAP_BOTH; break; } @@ -292,11 +386,12 @@ class ADORecordSet_ldap extends ADORecordSet{ break; case LDAP_NUM: - $this->fields = $this->GetRowNums(); + $this->fields = array_merge($this->GetRowNums(),$this->GetRowAssoc()); break; case LDAP_BOTH: default: + $this->fields = $this->GetRowNums(); break; } return ( is_array( $this->fields ) ); diff --git a/phpgwapi/inc/adodb/drivers/adodb-mssql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-mssql.inc.php index 12256a3e13..3996fe211a 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-mssql.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-mssql.inc.php @@ -1,6 +1,6 @@ _has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0); @@ -306,10 +305,51 @@ class ADODB_mssql extends ADOConnection { See http://www.swynk.com/friends/achigrik/SQL70Locks.asp */ - function RowLock($tables,$where) + function RowLock($tables,$where,$flds='top 1 null as ignore') { if (!$this->transCnt) $this->BeginTrans(); - return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where"); + return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where"); + } + + + function &MetaIndexes($table,$primary=false) + { + $table = $this->qstr($table); + + $sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno, + CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK, + CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique + FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id + INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid + INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid + WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table + ORDER BY O.name, I.Name, K.keyno"; + + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + + $rs = $this->Execute($sql); + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; + + if (!is_object($rs)) { + return FALSE; + } + + $indexes = array(); + while ($row = $rs->FetchRow()) { + if (!$primary && $row[5]) continue; + + $indexes[$row[0]]['unique'] = $row[6]; + $indexes[$row[0]]['columns'][] = $row[1]; + } + return $indexes; } function MetaForeignKeys($table, $owner=false, $upper=false) @@ -395,7 +435,8 @@ order by constraint_name, referenced_table_name, keyno"; $ADODB_FETCH_MODE = $savem; if ($a && sizeof($a)>0) return $a; - return false; + $false = false; + return $false; } @@ -413,46 +454,6 @@ order by constraint_name, referenced_table_name, keyno"; } return $ret; } - - function &MetaIndexes($table,$primary=false) - { - $table = $this->Quote($table); - - $sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno, - CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK, - CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique - FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id - INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid - INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid - WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table - ORDER BY O.name, I.Name, K.keyno"; - - global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } - - $rs = $this->Execute($sql); - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; - - if (!is_object($rs)) { - return FALSE; - } - - $indexes = array(); - while ($row = $rs->FetchRow()) { - if (!$primary && $row[5]) continue; - - $indexes[$row[0]]['unique'] = $row[6]; - $indexes[$row[0]]['columns'][] = $row[1]; - } - return $indexes; - } function SelectDB($dbName) { @@ -534,6 +535,30 @@ order by constraint_name, referenced_table_name, keyno"; return array($sql,$stmt); } + // returns concatenated string + // MSSQL requires integers to be cast as strings + // automatically cast every datatype to VARCHAR(255) + // @author David Rogers (introspectshun) + function Concat() + { + $s = ""; + $arr = func_get_args(); + + // Split single record on commas, if possible + if (sizeof($arr) == 1) { + foreach ($arr as $arg) { + $args = explode(',', $arg); + } + $arr = $args; + } + + array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";')); + $s = implode('+',$arr); + if (sizeof($arr) > 0) return "$s"; + + return ''; + } + /* Usage: $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group @@ -756,15 +781,17 @@ class ADORecordset_mssql extends ADORecordSet { fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fetchField() is retrieved. */ - function FetchField($fieldOffset = -1) + function &FetchField($fieldOffset = -1) { if ($fieldOffset != -1) { - return @mssql_fetch_field($this->_queryID, $fieldOffset); + $f = @mssql_fetch_field($this->_queryID, $fieldOffset); } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ - return @mssql_fetch_field($this->_queryID); + $f = @mssql_fetch_field($this->_queryID); } - return null; + $false = false; + if (empty($f)) return $false; + return $f; } function _seek($row) diff --git a/phpgwapi/inc/adodb/drivers/adodb-mssqlpo.inc.php b/phpgwapi/inc/adodb/drivers/adodb-mssqlpo.inc.php index a9f03e974a..723c49c1ac 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-mssqlpo.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-mssqlpo.inc.php @@ -1,6 +1,6 @@ fetchMode !== FALSE) { @@ -95,7 +96,7 @@ class ADODB_mysql extends ADOConnection { $ADODB_FETCH_MODE = $save; if (!is_object($rs)) { - return FALSE; + return $false; } $indexes = array (); @@ -148,7 +149,8 @@ class ADODB_mysql extends ADOConnection { function _insertid() { - return mysql_insert_id($this->_connectionID); + return ADOConnection::GetOne('SELECT LAST_INSERT_ID()'); + //return mysql_insert_id($this->_connectionID); } function GetOne($sql,$inputarr=false) @@ -302,7 +304,13 @@ class ADODB_mysql extends ADOConnection { $s .= '%p'; break; - + case 'w': + $s .= '%w'; + break; + + case 'l': + $s .= '%W'; + break; } } $s.="')"; @@ -333,6 +341,8 @@ class ADODB_mysql extends ADOConnection { // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { + if (!empty($this->port)) $argHostname .= ":".$this->port; + if (ADODB_PHPVER >= 0x4300) $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword, $this->forceNewConnect,$this->clientFlags); @@ -350,6 +360,8 @@ class ADODB_mysql extends ADOConnection { // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { + if (!empty($this->port)) $argHostname .= ":".$this->port; + if (ADODB_PHPVER >= 0x4300) $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags); else @@ -368,86 +380,86 @@ class ADODB_mysql extends ADOConnection { function &MetaColumns($table) { - - if ($this->metaColumnsSQL) { + $this->_findschema($table,$schema); + if ($schema) { + $dbName = $this->database; + $this->SelectDB($schema); + } global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + + if ($schema) { + $this->SelectDB($dbName); + } + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!is_object($rs)) { + $false = false; + return $false; + } - $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + $retarr = array(); + while (!$rs->EOF){ + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rs === false) return false; - - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $type = $rs->fields[1]; + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $arr = explode(",",$query_array[2]); + $fld->enums = $arr; + $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 + $fld->max_length = ($zlen > 0) ? $zlen : 1; + } else { + $fld->type = $type; + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); - - // split type into type(length): - $fld->scale = null; - if (preg_match('/^enum\((.+)\)$/',$type,$enum_vals)) { // convert enum to varchar - $fld->type = 'varchar'; - $fld->max_length = 1; - $enum_vals = explode(',',$enum_vals[1]); - foreach($enum_vals as $val) - { - if ($fld->max_length < strlen($val)-2) $fld->max_length = strlen($val)-2; - } - } elseif (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; - $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; - } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; } else { - $fld->max_length = -1; - $fld->type = $type; + $fld->has_default = false; } - /* - // split type into type(length): - if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; - } else { - $fld->max_length = -1; - $fld->type = $type; - }*/ - $fld->not_null = ($rs->fields[2] != 'YES'); - $fld->primary_key = ($rs->fields[3] == 'PRI'); - $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); - $fld->binary = (strpos($fld->type,'blob') !== false); - - if (!$fld->binary) { - $d = $rs->fields[4]; - if ($d != "" && $d != "NULL") { - $fld->has_default = true; - $fld->default_value = $d; - } else { - $fld->has_default = false; - } - } - if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; + } + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } $rs->MoveNext(); } + $rs->Close(); return $retarr; - } - return false; } // returns true or false function SelectDB($dbName) { - $this->databaseName = $dbName; + $this->database = $dbName; if ($this->_connectionID) { return @mysql_select_db($dbName,$this->_connectionID); } @@ -519,6 +531,42 @@ class ADODB_mysql extends ADOConnection { return 4294967295; } + // "Innox - Juan Carlos Gonzalez" + function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $asociative = FALSE ) + { + if ( !empty($owner) ) { + $table = "$owner.$table"; + } + $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table)); + $create_sql = $a_create_table[1]; + + $matches = array(); + $foreign_keys = array(); + if ( preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches) ) { + $num_keys = count($matches[0]); + for ( $i = 0; $i < $num_keys; $i ++ ) { + $my_field = explode('`, `', $matches[1][$i]); + $ref_table = $matches[2][$i]; + $ref_field = explode('`, `', $matches[3][$i]); + + if ( $upper ) { + $ref_table = strtoupper($ref_table); + } + + $foreign_keys[$ref_table] = array(); + $num_fields = count($my_field); + for ( $j = 0; $j < $num_fields; $j ++ ) { + if ( $asociative ) { + $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j]; + } else { + $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}"; + } + } + } + } + return $foreign_keys; + } + } /*-------------------------------------------------------------------------------------- @@ -541,11 +589,12 @@ class ADORecordSet_mysql extends ADORecordSet{ { case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; } - + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } @@ -608,7 +657,7 @@ class ADORecordSet_mysql extends ADORecordSet{ { //return adodb_movenext($this); //if (defined('ADODB_EXTENSION')) return adodb_movenext($this); - if (@$this->fields =& mysql_fetch_array($this->_queryID,$this->fetchMode)) { + if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) { $this->_currentRow += 1; return true; } @@ -676,7 +725,7 @@ class ADORecordSet_mysql extends ADORecordSet{ case 'MEDIUMINT': case 'SMALLINT': - if (is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->auto_increment) return 'R'; + if (!empty($fieldobj->primary_key)) return 'R'; else return 'I'; default: return 'N'; @@ -696,17 +745,18 @@ class ADORecordSet_ext_mysql extends ADORecordSet_mysql { { case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; } - - $this->ADORecordSet($queryID); + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); } function MoveNext() { - return adodb_movenext($this); + return @adodb_movenext($this); } } diff --git a/phpgwapi/inc/adodb/drivers/adodb-mysqli.inc.php b/phpgwapi/inc/adodb/drivers/adodb-mysqli.inc.php index 212ed194c3..22823a52c2 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-mysqli.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-mysqli.inc.php @@ -1,6 +1,6 @@ _connectionID = @mysqli_init(); if (is_null($this->_connectionID)) { @@ -67,29 +76,34 @@ class ADODB_mysqli extends ADOConnection { ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); return false; } - // Set connection options - // Not implemented now - // mysqli_options($this->_connection,,); - if (mysqli_real_connect($this->_connectionID, + /* + I suggest a simple fix which would enable adodb and mysqli driver to + read connection options from the standard mysql configuration file + /etc/my.cnf - "Bastien Duclaux" + */ + foreach($this->optionFlags as $arr) { + mysqli_options($this->_connectionID,$arr[0],$arr[1]); + } + + if (!empty($this->port)) $argHostname .= ":".$this->port; + $ok = mysqli_real_connect($this->_connectionID, $argHostname, $argUsername, $argPassword, $argDatabasename, $this->port, $this->socket, - $this->clientFlags)) - { - if ($argDatabasename) return $this->SelectDB($argDatabasename); - - - return true; - } - else { + $this->clientFlags); + + if ($ok) { + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } else { if ($this->debug) ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); return false; - } - } + } + } // returns true or false // How to force a persistent connection @@ -104,7 +118,7 @@ class ADODB_mysqli extends ADOConnection { function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { $this->forceNewConnect = true; - $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); } function IfNull( $field, $ifNull ) @@ -158,7 +172,7 @@ class ADODB_mysqli extends ADOConnection { // ensure that the variable is not quoted twice, once by qstr and once // by the magic_quotes_gpc. // - //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc()); + //Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc()); function qstr($s, $magic_quotes = false) { if (!$magic_quotes) { @@ -176,7 +190,6 @@ class ADODB_mysqli extends ADOConnection { function _insertid() { -// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); $result = @mysqli_insert_id($this->_connectionID); if ($result == -1){ if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg()); @@ -187,7 +200,6 @@ class ADODB_mysqli extends ADOConnection { // Only works for INSERT, UPDATE and DELETE query's function _affectedrows() { - // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); $result = @mysqli_affected_rows($this->_connectionID); if ($result == -1) { if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg()); @@ -235,62 +247,72 @@ class ADODB_mysqli extends ADOConnection { } function &MetaDatabases() - { - $query = "SHOW DATABASES"; - $ret =& $this->Execute($query); - return $ret; - } + { + $query = "SHOW DATABASES"; + $ret =& $this->Execute($query); + if ($ret && is_object($ret)){ + $arr = array(); + while (!$ret->EOF){ + $db = $ret->Fields('Database'); + if ($db != 'mysql') $arr[] = $db; + $ret->MoveNext(); + } + return $arr; + } + return $ret; + } function &MetaIndexes ($table, $primary = FALSE) { - // save old fetch mode - global $ADODB_FETCH_MODE; - - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } - - // get index details - $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table)); - - // restore fetchmode - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; - - if (!is_object($rs)) { - return FALSE; - } - - $indexes = array (); - - // parse index data into array - while ($row = $rs->FetchRow()) { - if ($primary == FALSE AND $row[2] == 'PRIMARY') { - continue; - } - - if (!isset($indexes[$row[2]])) { - $indexes[$row[2]] = array( - 'unique' => ($row[1] == 0), - 'columns' => array() - ); - } - - $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4]; - } - - // sort columns by order in the index - foreach ( array_keys ($indexes) as $index ) - { - ksort ($indexes[$index]['columns']); - } - - return $indexes; + // save old fetch mode + global $ADODB_FETCH_MODE; + + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + + // get index details + $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table)); + + // restore fetchmode + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; + + if (!is_object($rs)) { + return $false; + } + + $indexes = array (); + + // parse index data into array + while ($row = $rs->FetchRow()) { + if ($primary == FALSE AND $row[2] == 'PRIMARY') { + continue; + } + + if (!isset($indexes[$row[2]])) { + $indexes[$row[2]] = array( + 'unique' => ($row[1] == 0), + 'columns' => array() + ); + } + + $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4]; + } + + // sort columns by order in the index + foreach ( array_keys ($indexes) as $index ) + { + ksort ($indexes[$index]['columns']); + } + + return $indexes; } @@ -348,6 +370,14 @@ class ADODB_mysqli extends ADOConnection { case 'A': $s .= '%p'; break; + + case 'w': + $s .= '%w'; + break; + + case 'l': + $s .= '%W'; + break; default: @@ -385,112 +415,125 @@ class ADODB_mysqli extends ADOConnection { return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; } + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $save = $this->metaTablesSQL; + if ($showSchema && is_string($showSchema)) { + $this->metaTablesSQL .= " from $showSchema"; + } + + if ($mask) { + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + $this->metaTablesSQL = $save; + return $ret; + } + + // "Innox - Juan Carlos Gonzalez" + function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $asociative = FALSE ) + { + if ( !empty($owner) ) { + $table = "$owner.$table"; + } + $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table)); + $create_sql = $a_create_table[1]; + + $matches = array(); + $foreign_keys = array(); + if ( preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches) ) { + $num_keys = count($matches[0]); + for ( $i = 0; $i < $num_keys; $i ++ ) { + $my_field = explode('`, `', $matches[1][$i]); + $ref_table = $matches[2][$i]; + $ref_field = explode('`, `', $matches[3][$i]); + + if ( $upper ) { + $ref_table = strtoupper($ref_table); + } + + $foreign_keys[$ref_table] = array(); + $num_fields = count($my_field); + for ( $j = 0; $j < $num_fields; $j ++ ) { + if ( $asociative ) { + $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j]; + } else { + $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}"; + } + } + } + } + return $foreign_keys; + } function &MetaColumns($table) { - if ($this->metaColumnsSQL) { - global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $rs = false; - switch($ADODB_FETCH_MODE) - { - case ADODB_FETCH_NUM: - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $rs = $this->Execute(sprintf($this->metaColumnsSQL, - $table)); + $false = false; + if (!$this->metaColumnsSQL) + return $false; + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) + $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; - if ($rs === false) break; + if (!is_object($rs)) + return $false; + $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - // split type into type(length): - if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) - { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } - else - { - $fld->max_length = -1; - } - $fld->not_null = ($rs->fields[2] != 'YES'); - $fld->primary_key = ($rs->fields[3] == 'PRI'); - $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); - $fld->binary = (strpos($fld->type,'blob') !== false); - if (!$fld->binary) - { - $d = $rs->fields[4]; - $d = $rs->fields['Default']; - if ($d != "" && $d != "NULL") - { - $fld->has_default = true; - $fld->default_value = $d; - } - else - { - $fld->has_default = false; + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = max(array_map("strlen",explode(",",$query_array[2]))) - 2; // PHP >= 4.0.6 + $fld->max_length = ($fld->max_length == 0 ? 1 : $fld->max_length); + } else { + $fld->type = $type; + $fld->max_length = -1; } - } - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); - } - break; - case ADODB_FETCH_ASSOC: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - $rs = $this->Execute(sprintf($this->metaColumnsSQL, - $table)); - $ADODB_FETCH_MODE = $save; - if ($rs === false) break; - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields['Field']; - $fld->type = $rs->fields['Type']; - - // split type into type(length): - if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) - { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } - else - { - $fld->max_length = -1; - } - $fld->not_null = ($rs->fields['Null'] != 'YES'); - $fld->primary_key = ($rs->fields['Key'] == 'PRI'); - $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false); - $fld->binary = (strpos($fld->type,'blob') !== false); - if (!$fld->binary) - { - $d = $rs->fields['Default']; - if ($d != "" && $d != "NULL") - { - $fld->has_default = true; - $fld->default_value = $d; - } - else - { - $fld->has_default = false; + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); + + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } } - } - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } + $rs->MoveNext(); } - break; - default: - } - - if ($rs === false) return false; - $rs->Close(); - return $retarr; - } - return false; + + $rs->Close(); + return $retarr; } // returns true or false @@ -517,6 +560,7 @@ class ADODB_mysqli extends ADOConnection { $secs = 0) { $offsetStr = ($offset >= 0) ? "$offset," : ''; + if ($nrows < 0) $nrows = '18446744073709551615'; if ($secs) $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3); @@ -572,7 +616,7 @@ class ADODB_mysqli extends ADOConnection { function ErrorMsg() { if (empty($this->_connectionID)) - $this->_errorMsg = @mysqli_error(); + $this->_errorMsg = @mysqli_connect_error(); else $this->_errorMsg = @mysqli_error($this->_connectionID); return $this->_errorMsg; @@ -582,7 +626,7 @@ class ADODB_mysqli extends ADOConnection { function ErrorNo() { if (empty($this->_connectionID)) - return @mysqli_errno(); + return @mysqli_connect_errno(); else return @mysqli_errno($this->_connectionID); } @@ -644,7 +688,7 @@ class ADORecordSet_mysqli extends ADORecordSet{ $this->fetchMode = MYSQLI_BOTH; break; } - + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } @@ -710,7 +754,7 @@ class ADORecordSet_mysqli extends ADORecordSet{ { if ($this->EOF) return false; $this->_currentRow++; - $this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode); + $this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode); if (is_array($this->fields)) return true; $this->EOF = true; @@ -729,70 +773,132 @@ class ADORecordSet_mysqli extends ADORecordSet{ $this->_queryID = false; } +/* + +0 = MYSQLI_TYPE_DECIMAL +1 = MYSQLI_TYPE_CHAR +1 = MYSQLI_TYPE_TINY +2 = MYSQLI_TYPE_SHORT +3 = MYSQLI_TYPE_LONG +4 = MYSQLI_TYPE_FLOAT +5 = MYSQLI_TYPE_DOUBLE +6 = MYSQLI_TYPE_NULL +7 = MYSQLI_TYPE_TIMESTAMP +8 = MYSQLI_TYPE_LONGLONG +9 = MYSQLI_TYPE_INT24 +10 = MYSQLI_TYPE_DATE +11 = MYSQLI_TYPE_TIME +12 = MYSQLI_TYPE_DATETIME +13 = MYSQLI_TYPE_YEAR +14 = MYSQLI_TYPE_NEWDATE +247 = MYSQLI_TYPE_ENUM +248 = MYSQLI_TYPE_SET +249 = MYSQLI_TYPE_TINY_BLOB +250 = MYSQLI_TYPE_MEDIUM_BLOB +251 = MYSQLI_TYPE_LONG_BLOB +252 = MYSQLI_TYPE_BLOB +253 = MYSQLI_TYPE_VAR_STRING +254 = MYSQLI_TYPE_STRING +255 = MYSQLI_TYPE_GEOMETRY +*/ + function MetaType($t, $len = -1, $fieldobj = false) { - if (is_object($t)) - { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } - $len = -1; // mysql max_length is not accurate - switch (strtoupper($t)) { - case 'STRING': - case 'CHAR': - case 'VARCHAR': - case 'TINYBLOB': - case 'TINYTEXT': - case 'ENUM': - case 'SET': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - case 'LONGTEXT': - case 'MEDIUMTEXT': - return 'X'; - - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - return !empty($fieldobj->binary) ? 'B' : 'X'; - case 'YEAR': - case 'DATE': - return 'D'; - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': return 'T'; + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'TINYINT': - case 'MEDIUMINT': - case 'SMALLINT': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - // Added floating-point types - // Maybe not necessery. - case 'FLOAT': - case 'DOUBLE': - // case 'DOUBLE PRECISION': - case 'DECIMAL': - case 'DEC': - case 'FIXED': - default: - return 'N'; - } - } + case MYSQLI_TYPE_TINY_BLOB : + case MYSQLI_TYPE_CHAR : + case MYSQLI_TYPE_STRING : + case MYSQLI_TYPE_ENUM : + case MYSQLI_TYPE_SET : + case 253 : + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + + case MYSQLI_TYPE_BLOB : + case MYSQLI_TYPE_LONG_BLOB : + case MYSQLI_TYPE_MEDIUM_BLOB : + + return !empty($fieldobj->binary) ? 'B' : 'X'; + case 'YEAR': + case 'DATE': + case MYSQLI_TYPE_DATE : + case MYSQLI_TYPE_YEAR : + + return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': + + case MYSQLI_TYPE_DATETIME : + case MYSQLI_TYPE_NEWDATE : + case MYSQLI_TYPE_TIME : + case MYSQLI_TYPE_TIMESTAMP : + + return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + case MYSQLI_TYPE_INT24 : + case MYSQLI_TYPE_LONG : + case MYSQLI_TYPE_LONGLONG : + case MYSQLI_TYPE_SHORT : + case MYSQLI_TYPE_TINY : + + if (!empty($fieldobj->primary_key)) return 'R'; + + return 'I'; + + + // Added floating-point types + // Maybe not necessery. + case 'FLOAT': + case 'DOUBLE': + // case 'DOUBLE PRECISION': + case 'DECIMAL': + case 'DEC': + case 'FIXED': + default: + //if (!is_numeric($t)) echo "

    --- Error in type matching $t -----

    "; + return 'N'; + } + } // function -} +} // rs class } diff --git a/phpgwapi/inc/adodb/drivers/adodb-mysqlt.inc.php b/phpgwapi/inc/adodb/drivers/adodb-mysqlt.inc.php index 0d632df362..2f9cc4cc13 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-mysqlt.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-mysqlt.inc.php @@ -1,7 +1,7 @@ transCnt==0) $this->BeginTrans(); + return $this->GetOne("select $flds from $tables where $where for update"); + } + } class ADORecordSet_mysqlt extends ADORecordSet_mysql{ @@ -70,21 +76,24 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } + switch ($mode) { case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: + case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: $this->fetchMode = MYSQL_BOTH; break; } + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } function MoveNext() { - if (@$this->fields =& mysql_fetch_array($this->_queryID,$this->fetchMode)) { + if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) { $this->_currentRow += 1; return true; } @@ -98,7 +107,7 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt { - function ADORecordSet_ext_mysqli($queryID,$mode=false) + function ADORecordSet_ext_mysqlt($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -108,11 +117,13 @@ class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt { { case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: + case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; } - + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } diff --git a/phpgwapi/inc/adodb/drivers/adodb-netezza.inc.php b/phpgwapi/inc/adodb/drivers/adodb-netezza.inc.php index 56905e019f..5586a707fd 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-netezza.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-netezza.inc.php @@ -1,6 +1,6 @@ fetchMode = PGSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break; - default: + case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: $this->fetchMode = PGSQL_BOTH; break; } + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } diff --git a/phpgwapi/inc/adodb/drivers/adodb-oci8.inc.php b/phpgwapi/inc/adodb/drivers/adodb-oci8.inc.php index 020b988384..a9ec9047e5 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-oci8.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-oci8.inc.php @@ -1,7 +1,7 @@ fetchMode !== false) $savem = $this->SetFetchMode(false); @@ -107,7 +108,9 @@ class ADODB_oci8 extends ADOConnection { if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; - if (!$rs) return false; + if (!$rs) { + return $false; + } $retarr = array(); while (!$rs->EOF) { //print_r($rs->fields); $fld = new ADOFieldObject(); @@ -128,7 +131,10 @@ class ADODB_oci8 extends ADOConnection { $rs->MoveNext(); } $rs->Close(); - return $retarr; + if (empty($retarr)) + return $false; + else + return $retarr; } function Time() @@ -203,14 +209,25 @@ NATSOFT.DOMAIN = //if ($argHostname) print "

    Connect: 1st argument should be left blank for $this->databaseType

    "; if ($mode==1) { - $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename); + $this->_connectionID = ($this->charSet) ? + OCIPLogon($argUsername,$argPassword, $argDatabasename) + : + OCIPLogon($argUsername,$argPassword, $argDatabasename, $this->charSet) + ; if ($this->_connectionID && $this->autoRollback) OCIrollback($this->_connectionID); } else if ($mode==2) { - $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename); + $this->_connectionID = ($this->charSet) ? + OCINLogon($argUsername,$argPassword, $argDatabasename) + : + OCINLogon($argUsername,$argPassword, $argDatabasename, $this->charSet); + } else { - $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename); + $this->_connectionID = ($this->charSet) ? + OCILogon($argUsername,$argPassword, $argDatabasename) + : + OCILogon($argUsername,$argPassword, $argDatabasename,$this->charSet); } - if ($this->_connectionID === false) return false; + if (!$this->_connectionID) return false; if ($this->_initdate) { $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'"); } @@ -270,10 +287,10 @@ NATSOFT.DOMAIN = return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')"; } - function RowLock($tables,$where) + function RowLock($tables,$where,$flds='1 as ignore') { if ($this->autoCommit) $this->BeginTrans(); - return $this->GetOne("select 1 as ignore from $tables where $where for update"); + return $this->GetOne("select $flds from $tables where $where for update"); } function &MetaTables($ttype=false,$showSchema=false,$mask=false) @@ -291,6 +308,73 @@ NATSOFT.DOMAIN = return $ret; } + // Mark Newnham + function &MetaIndexes ($table, $primary = FALSE, $owner=false) + { + // save old fetch mode + global $ADODB_FETCH_MODE; + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + + // get index details + $table = strtoupper($table); + + // get Primary index + $primary_key = ''; + + $false = false; + $rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table)); + if ($row = $rs->FetchRow()) + $primary_key = $row[1]; //constraint_name + + if ($primary==TRUE && $primary_key=='') { + if (isset($savem)) + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + return $false; //There is no primary key + } + + $rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table)); + + + if (!is_object($rs)) { + if (isset($savem)) + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + return $false; + } + + $indexes = array (); + // parse index data into array + + while ($row = $rs->FetchRow()) { + if ($primary && $row[0] != $primary_key) continue; + if (!isset($indexes[$row[0]])) { + $indexes[$row[0]] = array( + 'unique' => ($row[1] == 'UNIQUE'), + 'columns' => array() + ); + } + $indexes[$row[0]]['columns'][$row[2] - 1] = $row[3]; + } + + // sort columns by order in the index + foreach ( array_keys ($indexes) as $index ) { + ksort ($indexes[$index]['columns']); + } + + if (isset($savem)) { + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + } + return $indexes; + } + function BeginTrans() { if ($this->transOff) return true; @@ -412,6 +496,14 @@ NATSOFT.DOMAIN = $s .= 'AM'; break; + case 'w': + $s .= 'D'; + break; + + case 'l': + $s .= 'DAY'; + break; + default: // handle escape characters... if ($ch == '\\') { @@ -457,9 +549,9 @@ NATSOFT.DOMAIN = if ($offset > 0) $nrows += $offset; //$inputarr['adodb_rownum'] = $nrows; if ($this->databaseType == 'oci8po') { - $sql = "select * from ($sql) where rownum <= ?"; + $sql = "select * from (".$sql.") where rownum <= ?"; } else { - $sql = "select * from ($sql) where rownum <= :adodb_offset"; + $sql = "select * from (".$sql.") where rownum <= :adodb_offset"; } $inputarr['adodb_offset'] = $nrows; $nrows = -1; @@ -473,10 +565,13 @@ NATSOFT.DOMAIN = // Algorithm by Tomas V V Cox, from PEAR DB oci8.php // Let Oracle return the name of the columns - $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL"; - if (!$stmt = OCIParse($this->_connectionID, $q_fields)) { - return false; - } + $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL"; + + $false = false; + if (! $stmt_arr = $this->Prepare($q_fields)) { + return $false; + } + $stmt = $stmt_arr[1]; if (is_array($inputarr)) { foreach($inputarr as $k => $v) { @@ -499,7 +594,7 @@ NATSOFT.DOMAIN = if (!OCIExecute($stmt, OCI_DEFAULT)) { OCIFreeStatement($stmt); - return false; + return $false; } $ncols = OCINumCols($stmt); @@ -614,6 +709,46 @@ NATSOFT.DOMAIN = return $rez; } + /** + * Execute SQL + * + * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) + * @param [inputarr] holds the input data to bind to. Null elements will be set to null. + * @return RecordSet or false + */ + function &Execute($sql,$inputarr=false) + { + if ($this->fnExecute) { + $fn = $this->fnExecute; + $ret =& $fn($this,$sql,$inputarr); + if (isset($ret)) return $ret; + } + if ($inputarr) { + #if (!is_array($inputarr)) $inputarr = array($inputarr); + + $element0 = reset($inputarr); + + # is_object check because oci8 descriptors can be passed in + if (is_array($element0) && !is_object(reset($element0))) { + if (is_string($sql)) + $stmt = $this->Prepare($sql); + else + $stmt = $sql; + + foreach($inputarr as $arr) { + $ret =& $this->_Execute($stmt,$arr); + if (!$ret) return $ret; + } + } else { + $ret =& $this->_Execute($sql,$inputarr); + } + + } else { + $ret =& $this->_Execute($sql,false); + } + + return $ret; + } /* Example of usage: @@ -633,14 +768,12 @@ NATSOFT.DOMAIN = $sttype = @OCIStatementType($stmt); if ($sttype == 'BEGIN' || $sttype == 'DECLARE') { return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false); - } - + } return array($sql,$stmt,0,$BINDNUM); } /* - Call an oracle stored procedure and return a cursor variable. - Convert the cursor variable into a recordset. + Call an oracle stored procedure and returns a cursor variable as a recordset. Concept by Robert Tuttle robert@ud.com Example: @@ -655,17 +788,24 @@ NATSOFT.DOMAIN = */ function &ExecuteCursor($sql,$cursorName='rs',$params=false) { - $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor - + if (is_array($sql)) $stmt = $sql; + else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor + if (is_array($stmt) && sizeof($stmt) >= 5) { + $hasref = true; $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR); if ($params) { foreach($params as $k => $v) { $this->Parameter($stmt,$params[$k], $k); } } - } - return $this->Execute($stmt); + } else + $hasref = false; + + $rs =& $this->Execute($stmt); + if ($rs->databaseType == 'array') OCIFreeCursor($stmt[4]); + else if ($hasref) $rs->_refcursor = $stmt[4]; + return $rs; } /* @@ -716,25 +856,26 @@ NATSOFT.DOMAIN = ADOConnection::outp("Bind: name = $name"); } //we have to create a new Descriptor here - $numlob = count($this -> _refLOBs); - $this -> _refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type)); - $this -> _refLOBs[$numlob]['TYPE'] = $isOutput; + $numlob = count($this->_refLOBs); + $this->_refLOBs[$numlob]['LOB'] = OCINewDescriptor($this->_connectionID, oci_lob_desc($type)); + $this->_refLOBs[$numlob]['TYPE'] = $isOutput; - $tmp = &$this -> _refLOBs[$numlob]['LOB']; + $tmp = &$this->_refLOBs[$numlob]['LOB']; $rez = OCIBindByName($stmt[1], ":".$name, $tmp, -1, $type); if ($this->debug) { - ADOConnection::outp("Bind: descriptor has been allocated, var binded"); + ADOConnection::outp("Bind: descriptor has been allocated, var (".$name.") binded"); } // if type is input then write data to lob now if ($isOutput == false) { - $var = $this -> BlobEncode($var); - $tmp -> WriteTemporary($var); + $var = $this->BlobEncode($var); + $tmp->WriteTemporary($var); + $this->_refLOBs[$numlob]['VAR'] = &$var; if ($this->debug) { ADOConnection::outp("Bind: LOB has been written to temp"); } } else { - $this -> _refLOBs[$numlob]['VAR'] = &$var; + $this->_refLOBs[$numlob]['VAR'] = &$var; } $rez = $tmp; } else { @@ -791,12 +932,11 @@ NATSOFT.DOMAIN = 3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3)); 4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)'); - $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); + $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); $db->execute($stmt); */ function _query($sql,$inputarr) { - if (is_array($sql)) { // is prepared sql $stmt = $sql[1]; @@ -812,7 +952,7 @@ NATSOFT.DOMAIN = $bindarr = array(); foreach($inputarr as $k => $v) { $bindarr[$k] = $v; - OCIBindByName($stmt,":$k",$bindarr[$k],4000); + OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000); } $this->_bind[$bindpos] = &$bindarr; } @@ -861,9 +1001,14 @@ NATSOFT.DOMAIN = } //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp; $this -> _refLOBs[$key]['VAR'] = $tmp; - } - $this -> _refLOBs[$key]['LOB'] -> free(); - unset($this -> _refLOBs[$key]); + } else { + $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']); + $this -> _refLOBs[$key]['LOB']->free(); + unset($this -> _refLOBs[$key]); + if ($this->debug) { + ADOConnection::outp("IN LOB: LOB has been saved.
    "); + } + } } } @@ -902,10 +1047,10 @@ NATSOFT.DOMAIN = if (!$this->_connectionID) return; if (!$this->autoCommit) OCIRollback($this->_connectionID); - if (count($this -> _refLOBs) > 0) { - foreach ($this -> _refLOBs as $key => $value) { - $this -> _refLOBs[$key] -> free(); - unset($this -> _refLOBs[$key]); + if (count($this->_refLOBs) > 0) { + foreach ($this ->_refLOBs as $key => $value) { + $this->_refLOBs[$key]['LOB']->free(); + unset($this->_refLOBs[$key]); } } OCILogoff($this->_connectionID); @@ -1040,6 +1185,7 @@ class ADORecordset_oci8 extends ADORecordSet { var $databaseType = 'oci8'; var $bind=false; var $_fieldobjs; + //var $_arr = false; function ADORecordset_oci8($queryID,$mode=false) @@ -1050,13 +1196,15 @@ class ADORecordset_oci8 extends ADORecordSet { } switch ($mode) { - default: - case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; + case ADODB_FETCH_NUM: + default: + $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; } - + + $this->adodbFetchMode = $mode; $this->_queryID = $queryID; } @@ -1160,6 +1308,39 @@ class ADORecordset_oci8 extends ADORecordSet { return false; } + /* + # does not work as first record is retrieved in _initrs(), so is not included in GetArray() + function &GetArray($nRows = -1) + { + global $ADODB_OCI8_GETARRAY; + + if (true || !empty($ADODB_OCI8_GETARRAY)) { + # does not support $ADODB_ANSI_PADDING_OFF + + //OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by OCIfetchstatement + switch($this->adodbFetchMode) { + case ADODB_FETCH_NUM: + + $ncols = @OCIfetchstatement($this->_queryID, $results, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM); + $results = array_merge(array($this->fields),$results); + return $results; + + case ADODB_FETCH_ASSOC: + if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break; + + $ncols = @OCIfetchstatement($this->_queryID, $assoc, 0, $nRows, OCI_FETCHSTATEMENT_BY_ROW); + $results =& array_merge(array($this->fields),$assoc); + return $results; + + default: + break; + } + } + + $results =& ADORecordSet::GetArray($nRows); + return $results; + + } */ /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */ function &GetArrayLimit($nrows,$offset=-1) @@ -1215,7 +1396,11 @@ class ADORecordset_oci8 extends ADORecordSet { function _close() { if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false; - OCIFreeStatement($this->_queryID); + if (!empty($this->_refcursor)) { + OCIFreeCursor($this->_refcursor); + $this->_refcursor = false; + } + @OCIFreeStatement($this->_queryID); $this->_queryID = false; } @@ -1274,13 +1459,13 @@ class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 { } switch ($mode) { - default: - case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; + case ADODB_FETCH_NUM: + default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; } - + $this->adodbFetchMode = $mode; $this->_queryID = $queryID; } diff --git a/phpgwapi/inc/adodb/drivers/adodb-oci805.inc.php b/phpgwapi/inc/adodb/drivers/adodb-oci805.inc.php index d7991d12ab..26c6cb3d4d 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-oci805.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-oci805.inc.php @@ -1,6 +1,6 @@ GetArray($nrows); + if ($offset <= 0) { + $arr = $this->GetArray($nrows); + return $arr; + } for ($i=1; $i < $offset; $i++) - if (!@OCIFetch($this->_queryID)) return array(); - - if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array(); + if (!@OCIFetch($this->_queryID)) { + $arr = array(); + return $arr; + } + if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) { + $arr = array(); + return $arr; + } if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); $results = array(); $cnt = 0; diff --git a/phpgwapi/inc/adodb/drivers/adodb-odbc.inc.php b/phpgwapi/inc/adodb/drivers/adodb-odbc.inc.php index 5872dd21c8..fc07584ad8 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-odbc.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-odbc.inc.php @@ -1,6 +1,6 @@ _has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200; } + // returns true or false + function _connect($argDSN, $argUsername, $argPassword, $argDatabasename) + { + global $php_errormsg; + + if (!function_exists('odbc_connect')) return null; + + if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') { + ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter."); + } + if (isset($php_errormsg)) $php_errormsg = ''; + if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); + else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode); + $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; + if (isset($this->connectStmt)) $this->Execute($this->connectStmt); + + return $this->_connectionID != false; + } + + // returns true or false + function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename) + { + global $php_errormsg; + + if (!function_exists('odbc_connect')) return null; + + if (isset($php_errormsg)) $php_errormsg = ''; + $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; + if ($this->debug && $argDatabasename) { + ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter."); + } + // print "dsn=$argDSN u=$argUsername p=$argPassword
    "; flush(); + if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); + else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode); + + $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; + if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID); + if (isset($this->connectStmt)) $this->Execute($this->connectStmt); + + return $this->_connectionID != false; + } + + function ServerInfo() { @@ -156,48 +199,6 @@ class ADODB_odbc extends ADOConnection { } - // returns true or false - function _connect($argDSN, $argUsername, $argPassword, $argDatabasename) - { - global $php_errormsg; - - if (!function_exists('odbc_connect')) return null; - - if ($this->debug && $argDatabasename && $this->databaseType != 'vfp') { - ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter."); - } - if (isset($php_errormsg)) $php_errormsg = ''; - if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); - else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode); - $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; - if (isset($this->connectStmt)) $this->Execute($this->connectStmt); - - //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true); - return $this->_connectionID != false; - } - - // returns true or false - function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename) - { - global $php_errormsg; - - if (!function_exists('odbc_connect')) return null; - - if (isset($php_errormsg)) $php_errormsg = ''; - $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; - if ($this->debug && $argDatabasename) { - ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter."); - } - // print "dsn=$argDSN u=$argUsername p=$argPassword
    "; flush(); - if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword); - else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode); - - $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : ''; - if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID); - if (isset($this->connectStmt)) $this->Execute($this->connectStmt); - - return $this->_connectionID != false; - } function BeginTrans() { @@ -274,8 +275,10 @@ class ADODB_odbc extends ADOConnection { $rs = new ADORecordSet_odbc($qid); $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; - + if (!$rs) { + $false = false; + return $false; + } $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; $arr =& $rs->GetArray(); @@ -300,6 +303,7 @@ class ADODB_odbc extends ADOConnection { } /* +See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp / SQL data type codes / #define SQL_UNKNOWN_TYPE 0 #define SQL_CHAR 1 @@ -315,6 +319,7 @@ class ADODB_odbc extends ADOConnection { #endif #define SQL_VARCHAR 12 + / One-parameter shortcuts for date/time data types / #if (ODBCVER >= 0x0300) #define SQL_TYPE_DATE 91 @@ -340,13 +345,16 @@ class ADODB_odbc extends ADOConnection { case -4: //image return 'B'; + case 9: case 91: - case 11: return 'D'; - + + case 10: + case 11: case 92: case 93: - case 9: return 'T'; + return 'T'; + case 4: case 5: case -6: @@ -366,6 +374,7 @@ class ADODB_odbc extends ADOConnection { { global $ADODB_FETCH_MODE; + $false = false; if ($this->uCaseTables) $table = strtoupper($table); $schema = ''; $this->_findschema($table,$schema); @@ -411,15 +420,15 @@ class ADODB_odbc extends ADOConnection { if (empty($qid)) $qid = odbc_columns($this->_connectionID); break; } - if (empty($qid)) return false; + if (empty($qid)) return $false; - $rs = new ADORecordSet_odbc($qid); + $rs =& new ADORecordSet_odbc($qid); $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; - + if (!$rs) return $false; $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change; $rs->_fetch(); + $retarr = array(); /* @@ -438,8 +447,8 @@ class ADODB_odbc extends ADOConnection { 11 REMARKS */ while (!$rs->EOF) { - //adodb_pr($rs->fields); - if (strtoupper($rs->fields[2]) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) { + // adodb_pr($rs->fields); + if (strtoupper(trim($rs->fields[2])) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) { $fld = new ADOFieldObject(); $fld->name = $rs->fields[3]; $fld->type = $this->ODBCTypes($rs->fields[4]); @@ -464,6 +473,7 @@ class ADODB_odbc extends ADOConnection { } $rs->Close(); //-- crashes 4.03pl1 -- why? + if (empty($retarr)) $retarr = false; return $retarr; } @@ -681,11 +691,13 @@ class ADORecordSet_odbc extends ADORecordSet { { if ($this->_numOfRows != 0 && !$this->EOF) { $this->_currentRow++; - $row = 0; + if ($this->_has_stupid_odbc_fetch_api_change) $rez = @odbc_fetch_into($this->_queryID,$this->fields); - else + else { + $row = 0; $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields); + } if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); @@ -700,12 +712,13 @@ class ADORecordSet_odbc extends ADORecordSet { function _fetch() { - $row = 0; + if ($this->_has_stupid_odbc_fetch_api_change) - $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row); - else + $rez = @odbc_fetch_into($this->_queryID,$this->fields); + else { + $row = 0; $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields); - + } if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); @@ -722,5 +735,4 @@ class ADORecordSet_odbc extends ADORecordSet { } } - ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-odbc_mssql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-odbc_mssql.inc.php index 50dd53fcd7..581e98982f 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-odbc_mssql.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-odbc_mssql.inc.php @@ -1,6 +1,6 @@ ADODB_odbc(); - $this->curmode = SQL_CUR_USE_ODBC; + //$this->curmode = SQL_CUR_USE_ODBC; } // crashes php... @@ -132,7 +132,8 @@ order by constraint_name, referenced_table_name, keyno"; function &MetaColumns($table) { - return ADOConnection::MetaColumns($table); + $arr = ADOConnection::MetaColumns($table); + return $arr; } function _query($sql,$inputarr) @@ -163,7 +164,8 @@ order by constraint_name, referenced_table_name, keyno"; $ADODB_FETCH_MODE = $savem; if ($a && sizeof($a)>0) return $a; - return false; + $false = false; + return $false; } function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) diff --git a/phpgwapi/inc/adodb/drivers/adodb-odbc_oracle.inc.php b/phpgwapi/inc/adodb/drivers/adodb-odbc_oracle.inc.php index 5359f65ea4..1e8bb63936 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-odbc_oracle.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-odbc_oracle.inc.php @@ -1,6 +1,6 @@ metaTablesSQL) { - $rs = $this->Execute($this->metaTablesSQL); - if ($rs === false) return false; - $arr = $rs->GetArray(); - $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { - $arr2[] = $arr[$i][0]; - } - $rs->Close(); - return $arr2; + $false = false; + $rs = $this->Execute($this->metaTablesSQL); + if ($rs === false) return $false; + $arr = $rs->GetArray(); + $arr2 = array(); + for ($i=0; $i < sizeof($arr); $i++) { + $arr2[] = $arr[$i][0]; } - return false; + $rs->Close(); + return $arr2; } function &MetaColumns($table) { - if (!empty($this->metaColumnsSQL)) { - $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); - if ($rs === false) return false; - - $retarr = array(); - while (!$rs->EOF) { //print_r($rs->fields); - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - $fld->max_length = $rs->fields[2]; - - - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; - - $rs->MoveNext(); - } - $rs->Close(); - return $retarr; + $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + if ($rs === false) { + $false = false; + return $false; } - return false; + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + $fld->max_length = $rs->fields[2]; + + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; } // returns true or false diff --git a/phpgwapi/inc/adodb/drivers/adodb-odbtp.inc.php b/phpgwapi/inc/adodb/drivers/adodb-odbtp.inc.php index ab60f87cc6..0429169d3d 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-odbtp.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-odbtp.inc.php @@ -1,6 +1,6 @@ odbc_driver == ODB_DRIVER_FOXPRO ) { + if( $this->odbc_driver == ODB_DRIVER_FOXPRO) { $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID ); //if using vfp dbc file if( !strcasecmp(strrchr($path, '.'), '.dbc') ) @@ -150,16 +150,31 @@ class ADODB_odbtp extends ADOConnection{ function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') { $this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase); - if ($this->_connectionID === false) - { + if ($this->_connectionID === false) { $this->_errorMsg = $this->ErrorMsg() ; return false; } + if ($this->_dontPoolDBC) { + if (function_exists('odbtp_dont_pool_dbc')) + @odbtp_dont_pool_dbc($this->_connectionID); + } + else { + $this->_dontPoolDBC = true; + } $this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID); + $dbms = strtolower(@odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID)); + $this->odbc_name = $dbms; + + // Account for inconsistent DBMS names + if( $this->odbc_driver == ODB_DRIVER_ORACLE ) + $dbms = 'oracle'; + else if( $this->odbc_driver == ODB_DRIVER_SYBASE ) + $dbms = 'sybase'; - // Set driver specific attributes - switch( $this->odbc_driver ) { - case ODB_DRIVER_MSSQL: + // Set DBMS specific attributes + switch( $dbms ) { + case 'microsoft sql server': + $this->databaseType = 'odbtp_mssql'; $this->fmtDate = "'Y-m-d'"; $this->fmtTimeStamp = "'Y-m-d h:i:sA'"; $this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)'; @@ -176,8 +191,10 @@ class ADODB_odbtp extends ADOConnection{ $this->length = 'len'; $this->identitySQL = 'select @@IDENTITY'; $this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'"; + $this->_canPrepareSP = true; break; - case ODB_DRIVER_JET: + case 'access': + $this->databaseType = 'odbtp_access'; $this->fmtDate = "#Y-m-d#"; $this->fmtTimeStamp = "#Y-m-d h:i:sA#"; $this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')"; @@ -185,24 +202,22 @@ class ADODB_odbtp extends ADOConnection{ $this->hasTop = 'top'; $this->hasTransactions = false; $this->_canPrepareSP = true; // For MS Access only. - - // Can't rebind ODB_CHAR to ODB_WCHAR if row cache enabled. - if ($this->_useUnicodeSQL) - odbtp_use_row_cache($this->_connectionID, FALSE, 0); break; - case ODB_DRIVER_FOXPRO: + case 'visual foxpro': + $this->databaseType = 'odbtp_vfp'; $this->fmtDate = "{^Y-m-d}"; $this->fmtTimeStamp = "{^Y-m-d, h:i:sA}"; $this->sysDate = 'date()'; $this->sysTimeStamp = 'datetime()'; $this->ansiOuter = true; $this->hasTop = 'top'; - $this->hasTransactions = false; + $this->hasTransactions = false; $this->replaceQuote = "'+chr(39)+'"; $this->true = '.T.'; $this->false = '.F.'; break; - case ODB_DRIVER_ORACLE: + case 'oracle': + $this->databaseType = 'odbtp_oci8'; $this->fmtDate = "'Y-m-d 00:00:00'"; $this->fmtTimeStamp = "'Y-m-d h:i:sA'"; $this->sysDate = 'TRUNC(SYSDATE)'; @@ -211,7 +226,8 @@ class ADODB_odbtp extends ADOConnection{ $this->_bindInputArray = true; $this->concat_operator = '||'; break; - case ODB_DRIVER_SYBASE: + case 'sybase': + $this->databaseType = 'odbtp_sybase'; $this->fmtDate = "'Y-m-d'"; $this->fmtTimeStamp = "'Y-m-d H:i:s'"; $this->sysDate = 'GetDate()'; @@ -223,22 +239,26 @@ class ADODB_odbtp extends ADOConnection{ $this->identitySQL = 'select @@IDENTITY'; break; default: + $this->databaseType = 'odbtp'; if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) ) - $this->hasTransactions = true; + $this->hasTransactions = true; else $this->hasTransactions = false; } @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID ); + if ($this->_useUnicodeSQL ) @odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID); + return true; } - + function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') { + $this->_dontPoolDBC = false; return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase); } - + function SelectDB($dbName) { if (!@odbtp_select_db($dbName, $this->_connectionID)) { @@ -254,7 +274,11 @@ class ADODB_odbtp extends ADOConnection{ $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false); + $arr =& $this->GetArray("||SQLTables||||$ttype"); + + if (isset($savefm)) $this->SetFetchMode($savefm); $ADODB_FETCH_MODE = $savem; $arr2 = array(); @@ -276,11 +300,17 @@ class ADODB_odbtp extends ADOConnection{ $savem = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false); + $rs = $this->Execute( "||SQLColumns||$schema|$table" ); + + if (isset($savefm)) $this->SetFetchMode($savefm); $ADODB_FETCH_MODE = $savem; - if (!$rs) return false; - + if (!$rs || $rs->EOF) { + $false = false; + return $false; + } while (!$rs->EOF) { //print_r($rs->fields); if (strtoupper($rs->fields[2]) == $table) { @@ -299,7 +329,7 @@ class ADODB_odbtp extends ADOConnection{ break; $rs->MoveNext(); } - $rs->Close(); + $rs->Close(); return $retarr; } @@ -335,8 +365,11 @@ class ADODB_odbtp extends ADOConnection{ //print_r($constr); $arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3]; } - if (!$arr) return false; - + if (!$arr) { + $false = false; + return $false; + } + $arr2 = array(); foreach($arr as $k => $v) { @@ -353,10 +386,14 @@ class ADODB_odbtp extends ADOConnection{ if (!$this->hasTransactions) return false; if ($this->transOff) return true; $this->transCnt += 1; - $this->_autocommit = false; - $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,ODB_TXN_READUNCOMMITTED,$this->_connectionID); + $this->autoCommit = false; + if (defined('ODB_TXN_DEFAULT')) + $txn = ODB_TXN_DEFAULT; + else + $txn = ODB_TXN_READUNCOMMITTED; + $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,$txn,$this->_connectionID); if(!$rs) return false; - else return true; + return true; } function CommitTrans($ok=true) @@ -364,8 +401,8 @@ class ADODB_odbtp extends ADOConnection{ if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; - $this->_autocommit = true; - if( ($ret = odbtp_commit($this->_connectionID)) ) + $this->autoCommit = true; + if( ($ret = @odbtp_commit($this->_connectionID)) ) $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off return $ret; } @@ -374,8 +411,8 @@ class ADODB_odbtp extends ADOConnection{ { if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; - $this->_autocommit = true; - if( ($ret = odbtp_rollback($this->_connectionID)) ) + $this->autoCommit = true; + if( ($ret = @odbtp_rollback($this->_connectionID)) ) $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off return $ret; } @@ -386,13 +423,14 @@ class ADODB_odbtp extends ADOConnection{ if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1'; } - return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $ret =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return $ret; } function Prepare($sql) { if (! $this->_bindInputArray) return $sql; // no binding - $stmt = odbtp_prepare($sql,$this->_connectionID); + $stmt = @odbtp_prepare($sql,$this->_connectionID); if (!$stmt) { // print "Prepare Error for ($sql) ".$this->ErrorMsg()."
    "; return $sql; @@ -404,7 +442,7 @@ class ADODB_odbtp extends ADOConnection{ { if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures - $stmt = odbtp_prepare_proc($sql,$this->_connectionID); + $stmt = @odbtp_prepare_proc($sql,$this->_connectionID); if (!$stmt) return false; return array($sql,$stmt); } @@ -441,7 +479,7 @@ class ADODB_odbtp extends ADOConnection{ else { $name = '@'.$name; } - return odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen); + return @odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen); } /* @@ -457,13 +495,13 @@ class ADODB_odbtp extends ADOConnection{ function UpdateBlob($table,$column,$val,$where,$blobtype='image') { $sql = "UPDATE $table SET $column = ? WHERE $where"; - if( !($stmt = odbtp_prepare($sql, $this->_connectionID)) ) + if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) ) return false; - if( !odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) ) + if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) ) return false; - if( !odbtp_set( $stmt, 1, $val ) ) + if( !@odbtp_set( $stmt, 1, $val ) ) return false; - return odbtp_execute( $stmt ) != false; + return @odbtp_execute( $stmt ) != false; } function IfNull( $field, $ifNull ) @@ -483,23 +521,23 @@ class ADODB_odbtp extends ADOConnection{ if (is_array($sql)) { $stmtid = $sql[1]; } else { - $stmtid = odbtp_prepare($sql,$this->_connectionID); + $stmtid = @odbtp_prepare($sql,$this->_connectionID); if ($stmtid == false) { $this->_errorMsg = $php_errormsg; return false; } } - $num_params = odbtp_num_params( $stmtid ); + $num_params = @odbtp_num_params( $stmtid ); for( $param = 1; $param <= $num_params; $param++ ) { @odbtp_input( $stmtid, $param ); @odbtp_set( $stmtid, $param, $inputarr[$param-1] ); } - if (! odbtp_execute($stmtid) ) { + if (!@odbtp_execute($stmtid) ) { return false; } } else if (is_array($sql)) { $stmtid = $sql[1]; - if (!odbtp_execute($stmtid)) { + if (!@odbtp_execute($stmtid)) { return false; } } else { @@ -540,6 +578,19 @@ class ADORecordSet_odbtp extends ADORecordSet { $this->_numOfFields = @odbtp_num_fields($this->_queryID); if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID))) $this->_numOfRows = -1; + + if (!$this->connection->_useUnicodeSQL) return; + + if ($this->connection->odbc_driver == ODB_DRIVER_JET) { + if (!@odbtp_get_attr(ODB_ATTR_MAPCHARTOWCHAR, + $this->connection->_connectionID)) + { + for ($f = 0; $f < $this->_numOfFields; $f++) { + if (@odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR) + @odbtp_bind_field($this->_queryID, $f, ODB_WCHAR); + } + } + } } function &FetchField($fieldOffset = 0) @@ -570,7 +621,7 @@ class ADORecordSet_odbtp extends ADORecordSet { $this->bind[strtoupper($name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } function _fetch_odbtp($type=0) @@ -597,18 +648,18 @@ class ADORecordSet_odbtp extends ADORecordSet { { if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false; $this->EOF = false; - $this->_currentRow = 0; - return true; + $this->_currentRow = 0; + return true; } - function MoveLast() - { + function MoveLast() + { if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false; $this->EOF = false; $this->_currentRow = $this->_numOfRows - 1; - return true; - } - + return true; + } + function NextRecordSet() { if (!@odbtp_next_result($this->_queryID)) return false; @@ -625,4 +676,53 @@ class ADORecordSet_odbtp extends ADORecordSet { } } -?> \ No newline at end of file +class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_mssql'; + + function ADORecordSet_odbtp_mssql($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_access extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_access'; + + function ADORecordSet_odbtp_access($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_vfp'; + + function ADORecordSet_odbtp_vfp($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_oci8'; + + function ADORecordSet_odbtp_oci8($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_sybase'; + + function ADORecordSet_odbtp_sybase($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} +?> diff --git a/phpgwapi/inc/adodb/drivers/adodb-odbtp_unicode.inc.php b/phpgwapi/inc/adodb/drivers/adodb-odbtp_unicode.inc.php index b2f524a460..25f040b971 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-odbtp_unicode.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-odbtp_unicode.inc.php @@ -1,6 +1,6 @@ ADODB_odbtp(); } } - -class ADORecordSet_odbtp_unicode extends ADORecordSet_odbtp { - var $databaseType = 'odbtp_unicode'; - - function ADORecordSet_odbtp_unicode($queryID,$mode=false) - { - $this->ADORecordSet_odbtp($queryID, $mode); - } - - function _initrs() - { - $this->_numOfFields = @odbtp_num_fields($this->_queryID); - if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID))) - $this->_numOfRows = -1; - - if ($this->connection->odbc_driver == ODB_DRIVER_JET) { - for ($f = 0; $f < $this->_numOfFields; $f++) { - if (odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR) - odbtp_bind_field($this->_queryID, $f, ODB_WCHAR); - } - } - } -} -?> \ No newline at end of file +?> diff --git a/phpgwapi/inc/adodb/drivers/adodb-oracle.inc.php b/phpgwapi/inc/adodb/drivers/adodb-oracle.inc.php index 30974dfc6a..4fc11ee904 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-oracle.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-oracle.inc.php @@ -1,6 +1,6 @@ name = ora_columnname($this->_queryID, $fieldOffset); diff --git a/phpgwapi/inc/adodb/drivers/adodb-pdo.inc.php b/phpgwapi/inc/adodb/drivers/adodb-pdo.inc.php index 6f0415175d..1a8e667c93 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-pdo.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-pdo.inc.php @@ -1,6 +1,6 @@ _bindInputArray = false; + #$parentDriver->_connectionID->setAttribute(PDO_MYSQL_ATTR_USE_BUFFERED_QUERY,true); + } + + function ServerInfo() + { + return ADOConnection::ServerInfo(); + } + + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + { + $ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return $ret; + } + + function MetaTables() + { + return false; + } + + function MetaColumns() + { + return false; + } +} + class ADODB_pdo extends ADOConnection { var $databaseType = "pdo"; @@ -30,17 +108,51 @@ class ADODB_pdo extends ADOConnection { var $_haserrorfunctions = true; var $_lastAffectedRows = 0; + var $_errormsg = false; + var $_errorno = false; + + var $dsnType = ''; var $stmt = false; - function ADODB_pdo() + function ADODB_pdo() { } - + function _UpdatePDO() + { + $d = &$this->_driver; + $this->fmtDate = $d->fmtDate; + $this->fmtTimeStamp = $d->fmtTimeStamp; + $this->replaceQuote = $d->replaceQuote; + $this->sysDate = $d->sysDate; + $this->sysTimeStamp = $d->sysTimeStamp; + $this->random = $d->random; + $this->concat_operator = $d->concat_operator; + + $d->_init($this); + } + + function Time() + { + return false; + } + // returns true or false function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false) { - $this->_connectionID = new PDO($argDSN, $argUsername, $argPassword); + $at = strpos($argDSN,':'); + $this->dsnType = substr($argDSN,0,$at); + + try { + $this->_connectionID = new PDO($argDSN, $argUsername, $argPassword); + } catch (Exception $e) { + $this->_connectionID = false; + $this->_errorno = -1; + //var_dump($e); + $this->_errormsg = 'Connection attempt failed: '.$e->getMessage(); + return false; + } + if ($this->_connectionID) { switch(ADODB_ASSOC_CASE){ case 0: $m = PDO_CASE_LOWER; break; @@ -52,10 +164,25 @@ class ADODB_pdo extends ADOConnection { //$this->_connectionID->setAttribute(PDO_ATTR_ERRMODE,PDO_ERRMODE_SILENT ); $this->_connectionID->setAttribute(PDO_ATTR_CASE,$m); + $class = 'ADODB_pdo_'.$this->dsnType; //$this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true); + switch($this->dsnType) { + case 'oci': + case 'mysql': + case 'pgsql': + include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php'); + break; + } + if (class_exists($class)) + $this->_driver = new $class(); + else + $this->_driver = new ADODB_pdo_base(); + $this->_driver->_connectionID = $this->_connectionID; + $this->_UpdatePDO(); return true; } + $this->_driver = new ADODB_pdo_base(); return false; } @@ -65,15 +192,32 @@ class ADODB_pdo extends ADOConnection { return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true); } - function ErrorMsg() + /*------------------------------------------------------------------------------*/ + + + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + { + $save = $this->_driver->fetchMode; + $this->_driver->fetchMode = $this->fetchMode; + $ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $this->_driver->fetchMode = $save; + return $ret; + } + + + function ServerInfo() { - if ($this->_stmt) $arr = $this->_stmt->errorInfo(); - else $arr = $this->_connectionID->errorInfo(); - - if ($arr) { - if ($arr[0]) return $arr[2]; - else return ''; - } else return '-1'; + return $this->_driver->ServerInfo(); + } + + function MetaTables($ttype=false,$showSchema=false,$mask=false) + { + return $this->_driver->MetaTables($ttype,$showSchema,$mask); + } + + function MetaColumns($table,$normalize=true) + { + return $this->_driver->MetaColumns($table,$normalize); } function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) @@ -83,11 +227,36 @@ class ADODB_pdo extends ADOConnection { else $obj->bindParam($name, $var); } + + function ErrorMsg() + { + if ($this->_errormsg !== false) return $this->_errormsg; + if (!empty($this->_stmt)) $arr = $this->_stmt->errorInfo(); + else if (!empty($this->_connectionID)) $arr = $this->_connectionID->errorInfo(); + else return 'No Connection Established'; + + + if ($arr) { + if (sizeof($arr)<2) return ''; + if ((integer)$arr[1]) return $arr[2]; + else return ''; + } else return '-1'; + } + + function ErrorNo() { - - if ($this->_stmt) return $this->_stmt->errorCode(); - else return $this->_connectionID->errorInfo(); + if ($this->_errorno !== false) return $this->_errorno; + if (!empty($this->_stmt)) $err = $this->_stmt->errorCode(); + else if (!empty($this->_connectionID)) { + $arr = $this->_connectionID->errorInfo(); + if (isset($arr[0])) $err = $arr[0]; + else $err = -1; + } else + return 0; + + if ($err == '00000') return 0; // allows empty check + return $err; } function BeginTrans() @@ -102,6 +271,7 @@ class ADODB_pdo extends ADOConnection { function CommitTrans($ok=true) { + if (!$this->hasTransactions) return false; if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; @@ -114,6 +284,7 @@ class ADODB_pdo extends ADOConnection { function RollbackTrans() { + if (!$this->hasTransactions) return false; if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; @@ -145,14 +316,36 @@ class ADODB_pdo extends ADOConnection { if (is_array($sql)) { $stmt = $sql[1]; } else { - $stmt = $this->_connectionID->prepare($sql); + $stmt = $this->_connectionID->prepare($sql); } + if ($stmt) { - if ($inputarr) $stmt->execute($inputarr); - else $stmt->execute(); + if ($inputarr) $ok = $stmt->execute($inputarr); + else $ok = $stmt->execute(); + } + + + $this->_errormsg = false; + $this->_errorno = false; + + if ($ok) { + $this->_stmt = $stmt; + return $stmt; } - $this->_stmt = $stmt; - return $stmt; + + if ($stmt) { + + $arr = $stmt->errorinfo(); + if ((integer)$arr[1]) { + $this->_errormsg = $arr[2]; + $this->_errorno = $arr[1]; + } + + } else { + $this->_errormsg = false; + $this->_errorno = false; + } + return false; } // returns true or false @@ -210,13 +403,18 @@ class ADOPDOStatement { { if ($this->_stmt) $arr = $this->_stmt->errorInfo(); else $arr = $this->_connectionID->errorInfo(); - print_r($arr); - if ($arr) { - if ($arr[0]) return $arr[2]; + + if (is_array($arr)) { + if ((integer) $arr[0] && isset($arr[2])) return $arr[2]; else return ''; } else return '-1'; } + function NumCols() + { + return ($this->_stmt) ? $this->_stmt->columnCount() : 0; + } + function ErrorNo() { if ($this->_stmt) return $this->_stmt->errorCode(); @@ -240,11 +438,13 @@ class ADORecordSet_pdo extends ADORecordSet { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } + $this->adodbFetchMode = $mode; switch($mode) { - default: - case ADODB_FETCH_BOTH: $mode = PDO_FETCH_BOTH; break; case ADODB_FETCH_NUM: $mode = PDO_FETCH_NUM; break; case ADODB_FETCH_ASSOC: $mode = PDO_FETCH_ASSOC; break; + + case ADODB_FETCH_BOTH: + default: $mode = PDO_FETCH_BOTH; break; } $this->fetchMode = $mode; @@ -252,21 +452,6 @@ class ADORecordSet_pdo extends ADORecordSet { $this->ADORecordSet($id); } - - // returns the field object - function &FetchField($fieldOffset = -1) - { - - $off=$fieldOffset+1; // offsets begin at 1 - - $o= new ADOFieldObject(); - $o->name = @odbc_field_name($this->_queryID,$off); - $o->type = @odbc_field_type($this->_queryID,$off); - $o->max_length = @odbc_field_len($this->_queryID,$off); - if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); - else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); - return $o; - } function Init() { @@ -282,21 +467,46 @@ class ADORecordSet_pdo extends ADORecordSet { if ($this->EOF = ($this->_fetch() === false)) { $this->_numOfRows = 0; // _numOfRows could be -1 } - $this->_numOfFields = sizeof($this->fields); } else { $this->EOF = true; } } - function _initrs() { global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1; if (!$this->_numOfRows) $this->_numOfRows = -1; - $this->_numOfFields =0; - } + $this->_numOfFields = $this->_queryID->columnCount(); + } + + // returns the field object + function &FetchField($fieldOffset = -1) + { + $off=$fieldOffset+1; // offsets begin at 1 + + $o= new ADOFieldObject(); + $arr = @$this->_queryID->getColumnMeta($fieldOffset); + if (!$arr) { + $o->name = 'bad getColumnMeta()'; + $o->max_length = -1; + $o->type = 'VARCHAR'; + $o->precision = 0; + # $false = false; + return $o; + } + //adodb_pr($arr); + $o->name = $arr['name']; + if (isset($arr['native_type'])) $o->type = $arr['native_type']; + else $o->type = adodb_pdo_type($arr['pdo_type']); + $o->max_length = $arr['len']; + $o->precision = $arr['precision']; + + if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); + else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); + return $o; + } function _seek($row) { @@ -305,6 +515,8 @@ class ADORecordSet_pdo extends ADORecordSet { function _fetch() { + if (!$this->_queryID) return false; + $this->fields = $this->_queryID->fetch($this->fetchMode); return !empty($this->fields); } @@ -313,6 +525,20 @@ class ADORecordSet_pdo extends ADORecordSet { { $this->_queryID = false; } + + function Fields($colname) + { + if ($this->adodbFetchMode != ADODB_FETCH_NUM) return @$this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } } diff --git a/phpgwapi/inc/adodb/drivers/adodb-pdo_mysql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-pdo_mysql.inc.php new file mode 100644 index 0000000000..6e5315dc52 --- /dev/null +++ b/phpgwapi/inc/adodb/drivers/adodb-pdo_mysql.inc.php @@ -0,0 +1,145 @@ +hasTransactions = false; + $parentDriver->_bindInputArray = false; + $parentDriver->_connectionID->setAttribute(PDO_MYSQL_ATTR_USE_BUFFERED_QUERY,true); + } + + function ServerInfo() + { + $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $save = $this->metaTablesSQL; + if ($showSchema && is_string($showSchema)) { + $this->metaTablesSQL .= " from $showSchema"; + } + + if ($mask) { + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + $this->metaTablesSQL = $save; + return $ret; + } + + function &MetaColumns($table) + { + $this->_findschema($table,$schema); + if ($schema) { + $dbName = $this->database; + $this->SelectDB($schema); + } + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + + if ($schema) { + $this->SelectDB($dbName); + } + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!is_object($rs)) { + $false = false; + return $false; + } + + $retarr = array(); + while (!$rs->EOF){ + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $arr = explode(",",$query_array[2]); + $fld->enums = $arr; + $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 + $fld->max_length = ($zlen > 0) ? $zlen : 1; + } else { + $fld->type = $type; + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); + + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } + $rs->MoveNext(); + } + + $rs->Close(); + return $retarr; + } + + + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) + { + $offsetStr =($offset>=0) ? "$offset," : ''; + // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220 + if ($nrows < 0) $nrows = '18446744073709551615'; + + if ($secs) + $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr); + else + $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr); + return $rs; + } +} +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-pdo_oci.inc.php b/phpgwapi/inc/adodb/drivers/adodb-pdo_oci.inc.php new file mode 100644 index 0000000000..bb73470aad --- /dev/null +++ b/phpgwapi/inc/adodb/drivers/adodb-pdo_oci.inc.php @@ -0,0 +1,92 @@ +_bindInputArray = false; + + if ($this->_initdate) { + $parentDriver->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'"); + } + } + + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + if ($mask) { + $save = $this->metaTablesSQL; + $mask = $this->qstr(strtoupper($mask)); + $this->metaTablesSQL .= " AND table_name like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + if ($mask) { + $this->metaTablesSQL = $save; + } + return $ret; + } + + function &MetaColumns($table) + { + global $ADODB_FETCH_MODE; + + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!$rs) { + return $false; + } + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + $fld->max_length = $rs->fields[2]; + $fld->scale = $rs->fields[3]; + if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) { + $fld->type ='INT'; + $fld->max_length = $rs->fields[4]; + } + $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0); + $fld->binary = (strpos($fld->type,'BLOB') !== false); + $fld->default_value = $rs->fields[6]; + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + if (empty($retarr)) + return $false; + else + return $retarr; + } +} + +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-pdo_pgsql.inc.php b/phpgwapi/inc/adodb/drivers/adodb-pdo_pgsql.inc.php new file mode 100644 index 0000000000..4a3e8ebe09 --- /dev/null +++ b/phpgwapi/inc/adodb/drivers/adodb-pdo_pgsql.inc.php @@ -0,0 +1,228 @@ + 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; + + // used when schema defined + var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum +FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n +WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) + and c.relnamespace=n.oid and n.nspname='%s' + and a.attname not like '....%%' AND a.attnum > 0 + AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; + + // get primary key etc -- from Freek Dijkstra + var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key + FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'"; + + var $hasAffectedRows = true; + var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + // below suggested by Freek Dijkstra + var $true = 't'; // string that represents TRUE for a database + var $false = 'f'; // string that represents FALSE for a database + var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt. + var $hasMoveFirst = true; + var $hasGenID = true; + var $_genIDSQL = "SELECT NEXTVAL('%s')"; + var $_genSeqSQL = "CREATE SEQUENCE %s START %s"; + var $_dropSeqSQL = "DROP SEQUENCE %s"; + var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum"; + var $random = 'random()'; /// random function + var $concat_operator='||'; + + function _init($parentDriver) + { + + $parentDriver->hasTransactions = false; + } + + function ServerInfo() + { + $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + { + $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; + $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ''; + if ($secs2cache) + $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); + else + $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr); + + return $rs; + } + + function &MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $info = $this->ServerInfo(); + if ($info['version'] >= 7.3) { + $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' + and schemaname not in ( 'pg_catalog','information_schema') + union + select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') "; + } + if ($mask) { + $save = $this->metaTablesSQL; + $mask = $this->qstr(strtolower($mask)); + if ($info['version']>=7.3) + $this->metaTablesSQL = " +select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema') + union +select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') "; + else + $this->metaTablesSQL = " +select tablename,'T' from pg_tables where tablename like $mask + union +select viewname,'V' from pg_views where viewname like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + if ($mask) { + $this->metaTablesSQL = $save; + } + return $ret; + } + + function &MetaColumns($table,$normalize=true) + { + global $ADODB_FETCH_MODE; + + $schema = false; + $this->_findschema($table,$schema); + + if ($normalize) $table = strtolower($table); + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema)); + else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rs === false) { + $false = false; + return $false; + } + if (!empty($this->metaKeySQL)) { + // If we want the primary keys, we have to issue a separate query + // Of course, a modified version of the metaColumnsSQL query using a + // LEFT JOIN would have been much more elegant, but postgres does + // not support OUTER JOINS. So here is the clumsy way. + + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + + $rskey = $this->Execute(sprintf($this->metaKeySQL,($table))); + // fetch all result in once for performance. + $keys =& $rskey->GetArray(); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + $rskey->Close(); + unset($rskey); + } + + $rsdefa = array(); + if (!empty($this->metaDefaultsSQL)) { + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $sql = sprintf($this->metaDefaultsSQL, ($table)); + $rsdef = $this->Execute($sql); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rsdef) { + while (!$rsdef->EOF) { + $num = $rsdef->fields['num']; + $s = $rsdef->fields['def']; + if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */ + $s = substr($s, 1); + $s = substr($s, 0, strlen($s) - 1); + } + + $rsdefa[$num] = $s; + $rsdef->MoveNext(); + } + } else { + ADOConnection::outp( "==> SQL => " . $sql); + } + unset($rsdef); + } + + $retarr = array(); + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + $fld->max_length = $rs->fields[2]; + if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4; + if ($fld->max_length <= 0) $fld->max_length = -1; + if ($fld->type == 'numeric') { + $fld->scale = $fld->max_length & 0xFFFF; + $fld->max_length >>= 16; + } + // dannym + // 5 hasdefault; 6 num-of-column + $fld->has_default = ($rs->fields[5] == 't'); + if ($fld->has_default) { + $fld->default_value = $rsdefa[$rs->fields[6]]; + } + + //Freek + if ($rs->fields[4] == $this->true) { + $fld->not_null = true; + } + + // Freek + if (is_array($keys)) { + foreach($keys as $key) { + if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) + $fld->primary_key = true; + if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) + $fld->unique = true; // What name is more compatible? + } + } + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld; + + $rs->MoveNext(); + } + $rs->Close(); + if (empty($retarr)) { + $false = false; + return $false; + } else return $retarr; + + } + +} + +?> diff --git a/phpgwapi/inc/adodb/drivers/adodb-postgres.inc.php b/phpgwapi/inc/adodb/drivers/adodb-postgres.inc.php index 8ceebdc360..fd2a0f0ee6 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-postgres.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-postgres.inc.php @@ -1,6 +1,6 @@ 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; + // used when schema defined var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n -WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) +WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and c.relnamespace=n.oid and n.nspname='%s' and a.attname not like '....%%' AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; @@ -90,8 +91,8 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) var $hasAffectedRows = true; var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 // below suggested by Freek Dijkstra - var $true = 't'; // string that represents TRUE for a database - var $false = 'f'; // string that represents FALSE for a database + var $true = 'TRUE'; // string that represents TRUE for a database + var $false = 'FALSE'; // string that represents FALSE for a database var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt. var $hasMoveFirst = true; @@ -101,10 +102,11 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) var $_dropSeqSQL = "DROP SEQUENCE %s"; var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum"; var $random = 'random()'; /// random function - var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4 + var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4 // http://bugs.php.net/bug.php?id=25404 var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database + var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance. // The last (fmtTimeStamp is not entirely correct: // PostgreSQL also has support for time zones, @@ -128,12 +130,12 @@ WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) $this->version = $arr; return $arr; } -/* + function IfNull( $field, $ifNull ) { - return " NULLIF($field, $ifNull) "; // if PGSQL + return " coalesce($field, $ifNull) "; } -*/ + // get the last id - never tested function pg_insert_id($tablename,$fieldname) { @@ -175,10 +177,10 @@ a different OID if a database must be reloaded. */ return @pg_Exec($this->_connectionID, "begin"); } - function RowLock($tables,$where) + function RowLock($tables,$where,$flds='1 as ignore') { if (!$this->transCnt) $this->BeginTrans(); - return $this->GetOne("select 1 as ignore from $tables where $where for update"); + return $this->GetOne("select $flds from $tables where $where for update"); } // returns true/false. @@ -200,12 +202,26 @@ a different OID if a database must be reloaded. */ } function &MetaTables($ttype=false,$showSchema=false,$mask=false) - { + { + $info = $this->ServerInfo(); + if ($info['version'] >= 7.3) { + $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' + and schemaname not in ( 'pg_catalog','information_schema') + union + select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') "; + } if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(strtolower($mask)); - $this->metaTablesSQL = " -select tablename,'T' from pg_tables where tablename like $mask union + if ($info['version']>=7.3) + $this->metaTablesSQL = " +select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema') + union +select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') "; + else + $this->metaTablesSQL = " +select tablename,'T' from pg_tables where tablename like $mask + union select viewname,'V' from pg_views where viewname like $mask"; } $ret =& ADOConnection::MetaTables($ttype,$showSchema); @@ -289,6 +305,14 @@ select viewname,'V' from pg_views where viewname like $mask"; $s .= 'AM'; break; + case 'w': + $s .= 'D'; + break; + + case 'l': + $s .= 'DAY'; + break; + default: // handle escape characters... if ($ch == '\\') { @@ -333,6 +357,15 @@ select viewname,'V' from pg_views where viewname like $mask"; return $rez; } + /* + Hueristic - not guaranteed to work. + */ + function GuessOID($oid) + { + if (strlen($oid)>16) return false; + return is_numeric($oid); + } + /* * If an OID is detected, then we use pg_lo_* to open the oid file and read the * real blob from the db using the oid supplied as a parameter. If you are storing @@ -341,20 +374,24 @@ select viewname,'V' from pg_views where viewname like $mask"; * contributed by Mattia Rossi mattia@technologist.com * * see http://www.postgresql.org/idocs/index.php?largeobjects.html + * + * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also + * added maxsize parameter, which defaults to $db->maxblobsize if not defined. */ - function BlobDecode( $blob) - { - if (strlen($blob) > 24) return $blob; + function BlobDecode($blob,$maxsize=false,$hastrans=true) + { + if (!$this->GuessOID($blob)) return $blob; - @pg_exec($this->_connectionID,"begin"); + if ($hastrans) @pg_exec($this->_connectionID,"begin"); $fd = @pg_lo_open($this->_connectionID,$blob,"r"); if ($fd === false) { - @pg_exec($this->_connectionID,"commit"); + if ($hastrans) @pg_exec($this->_connectionID,"commit"); return $blob; } - $realblob = @pg_loreadall($fd); + if (!$maxsize) $maxsize = $this->maxblobsize; + $realblob = @pg_loread($fd,$maxsize); @pg_loclose($fd); - @pg_exec($this->_connectionID,"commit"); + if ($hastrans) @pg_exec($this->_connectionID,"commit"); return $realblob; } @@ -377,8 +414,13 @@ select viewname,'V' from pg_views where viewname like $mask"; // note that there is a pg_escape_bytea function only for php 4.2.0 or later } + // assumes bytea for blob, and varchar for clob function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') { + + if ($blobtype == 'CLOB') { + return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where"); + } // do not use bind params which uses qstr(), as blobencode() already quotes data return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where"); } @@ -397,6 +439,7 @@ select viewname,'V' from pg_views where viewname like $mask"; global $ADODB_FETCH_MODE; $schema = false; + $false = false; $this->_findschema($table,$schema); if ($normalize) $table = strtolower($table); @@ -410,8 +453,9 @@ select viewname,'V' from pg_views where viewname like $mask"; if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; - + if ($rs === false) { + return $false; + } if (!empty($this->metaKeySQL)) { // If we want the primary keys, we have to issue a separate query // Of course, a modified version of the metaColumnsSQL query using a @@ -443,8 +487,10 @@ select viewname,'V' from pg_views where viewname like $mask"; $num = $rsdef->fields['num']; $s = $rsdef->fields['def']; if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */ - $s = substr($s, 1,-1); + $s = substr($s, 1); + $s = substr($s, 0, strlen($s) - 1); } + $rsdefa[$num] = $s; $rsdef->MoveNext(); } @@ -455,7 +501,7 @@ select viewname,'V' from pg_views where viewname like $mask"; } $retarr = array(); - while (!$rs->EOF) { + while (!$rs->EOF) { $fld = new ADOFieldObject(); $fld->name = $rs->fields[0]; $fld->type = $rs->fields[1]; @@ -474,16 +520,16 @@ select viewname,'V' from pg_views where viewname like $mask"; } //Freek - if ($rs->fields[4] == $this->true) { + if ($rs->fields[4] == 't') { $fld->not_null = true; } // Freek if (is_array($keys)) { foreach($keys as $key) { - if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) + if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't') $fld->primary_key = true; - if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) + if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't') $fld->unique = true; // What name is more compatible? } } @@ -494,7 +540,10 @@ select viewname,'V' from pg_views where viewname like $mask"; $rs->MoveNext(); } $rs->Close(); - return $retarr; + if (empty($retarr)) + return $false; + else + return $retarr; } @@ -539,7 +588,8 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')'; $ADODB_FETCH_MODE = $save; if (!is_object($rs)) { - return FALSE; + $false = false; + return $false; } $col_names = $this->MetaColumnNames($table,true); @@ -580,6 +630,7 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')'; if ($host[0]) $str = "host=".adodb_addslashes($host[0]); else $str = 'host=localhost'; if (isset($host[1])) $str .= " port=$host[1]"; + else if (!empty($this->port)) $str .= " port=".$this->port; } if ($user) $str .= " user=".$user; if ($pwd) $str .= " password=".$pwd; @@ -714,7 +765,7 @@ WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')'; if (!empty($this->_connectionID)) { $this->_errorMsg = @pg_last_error($this->_connectionID); - } else $this->_errorMsg = DB_ERROR_CONNECT_FAILED; + } else $this->_errorMsg = @pg_last_error(); } else { if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage(); else $this->_errorMsg = @pg_errormessage($this->_connectionID); @@ -782,10 +833,12 @@ class ADORecordSet_postgres64 extends ADORecordSet{ { case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break; case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break; - default: + case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break; + case ADODB_FETCH_BOTH: + default: $this->fetchMode = PGSQL_BOTH; break; } + $this->adodbFetchMode = $mode; $this->ADORecordSet($queryID); } @@ -804,6 +857,8 @@ class ADORecordSet_postgres64 extends ADORecordSet{ $this->_numOfFields = @pg_numfields($qid); // cache types for blob decode check + // apparently pg_fieldtype actually performs an sql query on the database to get the type. + if (empty($this->connection->noBlobs)) for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { if (pg_fieldtype($qid,$i) == 'bytea') { $this->_blobArr[$i] = pg_fieldname($qid,$i); @@ -888,7 +943,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{ $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); + if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); return (is_array($this->fields)); } @@ -914,6 +969,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{ case 'NAME': case 'BPCHAR': case '_VARCHAR': + case 'INET': if ($len <= $this->blobSize) return 'C'; case 'TEXT': @@ -945,8 +1001,8 @@ class ADORecordSet_postgres64 extends ADORecordSet{ case 'INT8': case 'INT4': case 'INT2': - if (!is_object($fieldobj) || !$fieldobj->primary_key || !$fieldobj->unique || - !$fieldobj->has_default || substr($fieldobj->default_value,0,8) != 'nextval(') return 'I'; + if (isset($fieldobj) && + empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I'; case 'OID': case 'SERIAL': @@ -958,4 +1014,4 @@ class ADORecordSet_postgres64 extends ADORecordSet{ } } -?> +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-postgres7.inc.php b/phpgwapi/inc/adodb/drivers/adodb-postgres7.inc.php index 10d7ff94aa..0474040efd 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-postgres7.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-postgres7.inc.php @@ -1,6 +1,6 @@ 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 diff --git a/phpgwapi/inc/adodb/drivers/adodb-postgres8.inc.php b/phpgwapi/inc/adodb/drivers/adodb-postgres8.inc.php new file mode 100644 index 0000000000..85115be3ba --- /dev/null +++ b/phpgwapi/inc/adodb/drivers/adodb-postgres8.inc.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-proxy.inc.php b/phpgwapi/inc/adodb/drivers/adodb-proxy.inc.php index 6bc1d3f486..fa35b006de 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-proxy.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-proxy.inc.php @@ -1,6 +1,6 @@ curmode = SQL_CUR_USE_ODBC; @@ -181,4 +181,4 @@ class ADORecordSet_sapdb extends ADORecordSet_odbc { } } //define -?> +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-sqlanywhere.inc.php b/phpgwapi/inc/adodb/drivers/adodb-sqlanywhere.inc.php index e81cb3de87..4949cb1b72 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-sqlanywhere.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-sqlanywhere.inc.php @@ -1,6 +1,6 @@ Execute("select * from $tab limit 1"); - if (!$rs) return false; + if (!$rs) { + $false = false; + return $false; + } $arr = array(); for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) { $fld =& $rs->FetchField($i); @@ -131,6 +134,7 @@ class ADODB_sqlite extends ADOConnection { function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sqlite_open')) return null; + if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; $this->_connectionID = sqlite_open($argHostname); if ($this->_connectionID === false) return false; @@ -142,6 +146,7 @@ class ADODB_sqlite extends ADOConnection { function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sqlite_open')) return null; + if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; $this->_connectionID = sqlite_popen($argHostname); if ($this->_connectionID === false) return false; @@ -187,7 +192,7 @@ class ADODB_sqlite extends ADOConnection { $MAXLOOPS = 100; //$this->debug=1; while (--$MAXLOOPS>=0) { - $num = $this->GetOne("select id from $seq"); + @($num = $this->GetOne("select id from $seq")); if ($num === false) { $this->Execute(sprintf($this->_genSeqSQL ,$seq)); $start -= 1; @@ -231,6 +236,51 @@ class ADODB_sqlite extends ADOConnection { return @sqlite_close($this->_connectionID); } + function &MetaIndexes ($table, $primary = FALSE, $owner=false) + { + $false = false; + // save old fetch mode + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table)); + $rs = $this->Execute($SQL); + if (!is_object($rs)) { + if (isset($savem)) + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + return $false; + } + + $indexes = array (); + while ($row = $rs->FetchRow()) { + if ($primary && preg_match("/primary/i",$row[1]) == 0) continue; + if (!isset($indexes[$row[0]])) { + + $indexes[$row[0]] = array( + 'unique' => preg_match("/unique/i",$row[1]), + 'columns' => array()); + } + /** + * There must be a more elegant way of doing this, + * the index elements appear in the SQL statement + * in cols[1] between parentheses + * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) + */ + $cols = explode("(",$row[1]); + $cols = explode(")",$cols[1]); + array_pop($cols); + $indexes[$row[0]]['columns'] = $cols; + } + if (isset($savem)) { + $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + } + return $indexes; + } } @@ -255,6 +305,7 @@ class ADORecordset_sqlite extends ADORecordSet { case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break; default: $this->fetchMode = SQLITE_BOTH; break; } + $this->adodbFetchMode = $mode; $this->_queryID = $queryID; diff --git a/phpgwapi/inc/adodb/drivers/adodb-sqlitepo.inc.php b/phpgwapi/inc/adodb/drivers/adodb-sqlitepo.inc.php index 30b89f63a0..28271e3778 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-sqlitepo.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-sqlitepo.inc.php @@ -1,6 +1,6 @@ _hastrans) $this->BeginTrans(); $tables = str_replace(',',' HOLDLOCK,',$tables); - return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where"); + return $this->GetOne("select $flds from $tables HOLDLOCK where $where"); } - function SelectDB($dbName) { + function SelectDB($dbName) + { $this->databaseName = $dbName; if ($this->_connectionID) { return @sybase_select_db($dbName); @@ -105,10 +106,14 @@ class ADODB_sybase extends ADOConnection { /* Returns: the last error message from previous database operation Note: This function is NOT available for Microsoft SQL Server. */ - function ErrorMsg() + + function ErrorMsg() { if ($this->_logsql) return $this->_errorMsg; - $this->_errorMsg = sybase_get_last_message(); + if (function_exists('sybase_get_last_message')) + $this->_errorMsg = sybase_get_last_message(); + else + $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : 'SYBASE error messages not supported on this platform'; return $this->_errorMsg; } @@ -151,12 +156,12 @@ class ADODB_sybase extends ADOConnection { $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $rs; } - $cnt = ($nrows > 0) ? $nrows : 0; + $cnt = ($nrows >= 0) ? $nrows : 999999999; if ($offset > 0 && $cnt) $cnt += $offset; $this->Execute("set rowcount $cnt"); $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0); - $this->Execute("set rowcount 0"); + $this->Execute("set rowcount 0"); return $rs; } @@ -283,7 +288,7 @@ class ADORecordset_sybase extends ADORecordSet { } if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC; else $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + $this->ADORecordSet($id,$mode); } /* Returns: an object containing field information. diff --git a/phpgwapi/inc/adodb/drivers/adodb-sybase_ase.inc.php b/phpgwapi/inc/adodb/drivers/adodb-sybase_ase.inc.php new file mode 100644 index 0000000000..4f4b0e0a41 --- /dev/null +++ b/phpgwapi/inc/adodb/drivers/adodb-sybase_ase.inc.php @@ -0,0 +1,115 @@ +metaTablesSQL) { + // complicated state saving by the need for backward compat + + if ($ttype == 'VIEWS'){ + $sql = str_replace('U', 'V', $this->metaTablesSQL); + }elseif (false === $ttype){ + $sql = str_replace('U',"U' OR type='V", $this->metaTablesSQL); + }else{ // TABLES OR ANY OTHER + $sql = $this->metaTablesSQL; + } + $rs = $this->Execute($sql); + + if ($rs === false || !method_exists($rs, 'GetArray')){ + return $false; + } + $arr =& $rs->GetArray(); + + $arr2 = array(); + foreach($arr as $key=>$value){ + $arr2[] = trim($value['name']); + } + return $arr2; + } + return $false; + } + + function MetaDatabases() + { + $arr = array(); + if ($this->metaDatabasesSQL!='') { + $rs = $this->Execute($this->metaDatabasesSQL); + if ($rs && !$rs->EOF){ + while (!$rs->EOF){ + $arr[] = $rs->Fields('name'); + $rs->MoveNext(); + } + return $arr; + } + } + return false; + } + + // fix a bug which prevent the metaColumns query to be executed for Sybase ASE + function &MetaColumns($table,$upper=false) + { + $false = false; + if (!empty($this->metaColumnsSQL)) { + + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + if ($rs === false) return $false; + + $retarr = array(); + while (!$rs->EOF) { + $fld =& new ADOFieldObject(); + $fld->name = $rs->Fields('field_name'); + $fld->type = $rs->Fields('type'); + $fld->max_length = $rs->Fields('width'); + $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; + } + return $false; + } + + function getProcedureList($schema) + { + return false; + } + + function ErrorMsg() + { + if (!function_exists('sybase_connect')){ + return 'Your PHP doesn\'t contain the Sybase connection module!'; + } + return parent::ErrorMsg(); + } +} + +class adorecordset_sybase_ase extends ADORecordset_sybase { +var $databaseType = "sybase_ase"; +function ADORecordset_sybase_ase($id,$mode=false) + { + $this->ADORecordSet_sybase($id,$mode); + } + +} +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/drivers/adodb-vfp.inc.php b/phpgwapi/inc/adodb/drivers/adodb-vfp.inc.php index 63279a577f..34d2d2ccbd 100644 --- a/phpgwapi/inc/adodb/drivers/adodb-vfp.inc.php +++ b/phpgwapi/inc/adodb/drivers/adodb-vfp.inc.php @@ -1,6 +1,6 @@ hasTop = preg_match('/ORDER[ \t\r\n]+BY/is',$sql) ? 'top' : false; - return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + $ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return $ret; } diff --git a/phpgwapi/inc/adodb/lang/adodb-ar.inc.php b/phpgwapi/inc/adodb/lang/adodb-ar.inc.php new file mode 100644 index 0000000000..701d024776 --- /dev/null +++ b/phpgwapi/inc/adodb/lang/adodb-ar.inc.php @@ -0,0 +1,34 @@ + +$ADODB_LANG_ARRAY = array ( + 'LANG' => 'ar', + DB_ERROR => 'ÎØà ÛíÑ ãÍÏÏ', + DB_ERROR_ALREADY_EXISTS => 'ãæÌæÏ ãÓÈÞÇ', + DB_ERROR_CANNOT_CREATE => 'áÇ íãßä ÅäÔÇÁ', + DB_ERROR_CANNOT_DELETE => 'áÇ íãßä ÍÐÝ', + DB_ERROR_CANNOT_DROP => 'áÇ íãßä ÍÐÝ', + DB_ERROR_CONSTRAINT => 'ÚãáíÉ ÅÏÎÇá ããäæÚÉ', + DB_ERROR_DIVZERO => 'ÚãáíÉ ÇáÊÞÓíã Úáì ÕÝÑ', + DB_ERROR_INVALID => 'ÛíÑ ÕÍíÍ', + DB_ERROR_INVALID_DATE => 'ÕíÛÉ æÞÊ Ãæ ÊÇÑíÎ ÛíÑ ÕÍíÍÉ', + DB_ERROR_INVALID_NUMBER => 'ÕíÛÉ ÑÞã ÛíÑ ÕÍíÍÉ', + DB_ERROR_MISMATCH => 'ÛíÑ ãÊØÇÈÞ', + DB_ERROR_NODBSELECTED => 'áã íÊã ÅÎÊíÇÑ ÞÇÚÏÉ ÇáÈíÇäÇÊ ÈÚÏ', + DB_ERROR_NOSUCHFIELD => 'áíÓ åäÇáß ÍÞá ÈåÐÇ ÇáÇÓã', + DB_ERROR_NOSUCHTABLE => 'áíÓ åäÇáß ÌÏæá ÈåÐÇ ÇáÇÓã', + DB_ERROR_NOT_CAPABLE => 'ÞÇÚÏÉ ÇáÈíÇäÇÊ ÇáãÑÊÈØ ÈåÇ ÛíÑ ÞÇÏÑÉ', + DB_ERROR_NOT_FOUND => 'áã íÊã ÅíÌÇÏå', + DB_ERROR_NOT_LOCKED => 'ÛíÑ ãÞÝæá', + DB_ERROR_SYNTAX => 'ÎØà Ýí ÇáÕíÛÉ', + DB_ERROR_UNSUPPORTED => 'ÛíÑ ãÏÚæã', + DB_ERROR_VALUE_COUNT_ON_ROW => 'ÚÏÏ ÇáÞíã Ýí ÇáÓÌá', + DB_ERROR_INVALID_DSN => 'DNS ÛíÑ ÕÍíÍ', + DB_ERROR_CONNECT_FAILED => 'ÝÔá ÚãáíÉ ÇáÅÊÕÇá', + 0 => 'áíÓ åäÇáß ÃÎØÇÁ', // DB_OK + DB_ERROR_NEED_MORE_DATA => 'ÇáÈíÇäÇÊ ÇáãÒæÏÉ ÛíÑ ßÇÝíÉ', + DB_ERROR_EXTENSION_NOT_FOUND=> 'áã íÊã ÅíÌÇÏ ÇáÅÖÇÝÉ ÇáãÊÚáÞÉ', + DB_ERROR_NOSUCHDB => 'áíÓ åäÇáß ÞÇÚÏÉ ÈíÇäÇÊ ÈåÐÇ ÇáÇÓã', + DB_ERROR_ACCESS_VIOLATION => 'ÓãÇÍíÇÊ ÛíÑ ßÇÝíÉ' +); +?> + diff --git a/phpgwapi/inc/adodb/lang/adodb-da.inc.php b/phpgwapi/inc/adodb/lang/adodb-da.inc.php new file mode 100644 index 0000000000..ca0e72d614 --- /dev/null +++ b/phpgwapi/inc/adodb/lang/adodb-da.inc.php @@ -0,0 +1,33 @@ + 'da', + DB_ERROR => 'ukendt fejl', + DB_ERROR_ALREADY_EXISTS => 'eksisterer allerede', + DB_ERROR_CANNOT_CREATE => 'kan ikke oprette', + DB_ERROR_CANNOT_DELETE => 'kan ikke slette', + DB_ERROR_CANNOT_DROP => 'kan ikke droppe', + DB_ERROR_CONSTRAINT => 'begrænsning krænket', + DB_ERROR_DIVZERO => 'division med nul', + DB_ERROR_INVALID => 'ugyldig', + DB_ERROR_INVALID_DATE => 'ugyldig dato eller klokkeslet', + DB_ERROR_INVALID_NUMBER => 'ugyldigt tal', + DB_ERROR_MISMATCH => 'mismatch', + DB_ERROR_NODBSELECTED => 'ingen database valgt', + DB_ERROR_NOSUCHFIELD => 'felt findes ikke', + DB_ERROR_NOSUCHTABLE => 'tabel findes ikke', + DB_ERROR_NOT_CAPABLE => 'DB backend opgav', + DB_ERROR_NOT_FOUND => 'ikke fundet', + DB_ERROR_NOT_LOCKED => 'ikke låst', + DB_ERROR_SYNTAX => 'syntaksfejl', + DB_ERROR_UNSUPPORTED => 'ikke understøttet', + DB_ERROR_VALUE_COUNT_ON_ROW => 'resulterende antal felter svarer ikke til forespørgslens antal felter', + DB_ERROR_INVALID_DSN => 'ugyldig DSN', + DB_ERROR_CONNECT_FAILED => 'tilslutning mislykkedes', + 0 => 'ingen fejl', // DB_OK + DB_ERROR_NEED_MORE_DATA => 'utilstrækkelige data angivet', + DB_ERROR_EXTENSION_NOT_FOUND=> 'udvidelse ikke fundet', + DB_ERROR_NOSUCHDB => 'database ikke fundet', + DB_ERROR_ACCESS_VIOLATION => 'utilstrækkelige rettigheder' +); +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/lang/adodb-es.inc.php b/phpgwapi/inc/adodb/lang/adodb-es.inc.php index 2ab413cfb0..1e0afbb40d 100644 --- a/phpgwapi/inc/adodb/lang/adodb-es.inc.php +++ b/phpgwapi/inc/adodb/lang/adodb-es.inc.php @@ -22,8 +22,7 @@ $ADODB_LANG_ARRAY = array ( DB_ERROR_SYNTAX => 'error de sintaxis', DB_ERROR_UNSUPPORTED => 'no soportado', DB_ERROR_VALUE_COUNT_ON_ROW => 'la cantidad de columnas no corresponden a la cantidad de valores', - DB_ERROR_INVALID_DSN - => 'DSN invalido', + DB_ERROR_INVALID_DSN => 'DSN invalido', DB_ERROR_CONNECT_FAILED => 'fallo la conexion', 0 => 'sin error', // DB_OK DB_ERROR_NEED_MORE_DATA => 'insuficientes datos', diff --git a/phpgwapi/inc/adodb/lang/adodb-esperanto.inc.php b/phpgwapi/inc/adodb/lang/adodb-esperanto.inc.php new file mode 100644 index 0000000000..16ca00e2fa --- /dev/null +++ b/phpgwapi/inc/adodb/lang/adodb-esperanto.inc.php @@ -0,0 +1,35 @@ + 'eo', + DB_ERROR => 'nekonata eraro', + DB_ERROR_ALREADY_EXISTS => 'jam ekzistas', + DB_ERROR_CANNOT_CREATE => 'maleblas krei', + DB_ERROR_CANNOT_DELETE => 'maleblas elimini', + DB_ERROR_CANNOT_DROP => 'maleblas elimini (drop)', + DB_ERROR_CONSTRAINT => 'rompo de kondicxoj de provo', + DB_ERROR_DIVZERO => 'divido per 0 (nul)', + DB_ERROR_INVALID => 'malregule', + DB_ERROR_INVALID_DATE => 'malregula dato kaj tempo', + DB_ERROR_INVALID_NUMBER => 'malregula nombro', + DB_ERROR_MISMATCH => 'eraro', + DB_ERROR_NODBSELECTED => 'datumbazo ne elektita', + DB_ERROR_NOSUCHFIELD => 'ne ekzistas kampo', + DB_ERROR_NOSUCHTABLE => 'ne ekzistas tabelo', + DB_ERROR_NOT_CAPABLE => 'DBMS ne povas', + DB_ERROR_NOT_FOUND => 'ne trovita', + DB_ERROR_NOT_LOCKED => 'ne blokita', + DB_ERROR_SYNTAX => 'sintaksa eraro', + DB_ERROR_UNSUPPORTED => 'ne apogata', + DB_ERROR_VALUE_COUNT_ON_ROW => 'nombrilo de valoroj en linio', + DB_ERROR_INVALID_DSN => 'malregula DSN-o', + DB_ERROR_CONNECT_FAILED => 'konekto malsukcesa', + 0 => 'cxio bone', // DB_OK + DB_ERROR_NEED_MORE_DATA => 'ne suficxe da datumo', + DB_ERROR_EXTENSION_NOT_FOUND=> 'etendo ne trovita', + DB_ERROR_NOSUCHDB => 'datumbazo ne ekzistas', + DB_ERROR_ACCESS_VIOLATION => 'ne suficxe da rajto por atingo' +); +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/lang/adodb-hu.inc.php b/phpgwapi/inc/adodb/lang/adodb-hu.inc.php new file mode 100644 index 0000000000..d6f0ef82da --- /dev/null +++ b/phpgwapi/inc/adodb/lang/adodb-hu.inc.php @@ -0,0 +1,34 @@ + +$ADODB_LANG_ARRAY = array ( + 'LANG' => 'hu', + DB_ERROR => 'ismeretlen hiba', + DB_ERROR_ALREADY_EXISTS => 'már létezik', + DB_ERROR_CANNOT_CREATE => 'nem sikerült létrehozni', + DB_ERROR_CANNOT_DELETE => 'nem sikerült törölni', + DB_ERROR_CANNOT_DROP => 'nem sikerült eldobni', + DB_ERROR_CONSTRAINT => 'szabályok megszegése', + DB_ERROR_DIVZERO => 'osztás nullával', + DB_ERROR_INVALID => 'érvénytelen', + DB_ERROR_INVALID_DATE => 'érvénytelen dátum vagy idõ', + DB_ERROR_INVALID_NUMBER => 'érvénytelen szám', + DB_ERROR_MISMATCH => 'nem megfelelõ', + DB_ERROR_NODBSELECTED => 'nincs kiválasztott adatbázis', + DB_ERROR_NOSUCHFIELD => 'nincs ilyen mezõ', + DB_ERROR_NOSUCHTABLE => 'nincs ilyen tábla', + DB_ERROR_NOT_CAPABLE => 'DB backend nem támogatja', + DB_ERROR_NOT_FOUND => 'nem található', + DB_ERROR_NOT_LOCKED => 'nincs lezárva', + DB_ERROR_SYNTAX => 'szintaktikai hiba', + DB_ERROR_UNSUPPORTED => 'nem támogatott', + DB_ERROR_VALUE_COUNT_ON_ROW => 'soron végzett érték számlálás', + DB_ERROR_INVALID_DSN => 'hibás DSN', + DB_ERROR_CONNECT_FAILED => 'sikertelen csatlakozás', + 0 => 'nincs hiba', // DB_OK + DB_ERROR_NEED_MORE_DATA => 'túl kevés az adat', + DB_ERROR_EXTENSION_NOT_FOUND=> 'bõvítmény nem található', + DB_ERROR_NOSUCHDB => 'nincs ilyen adatbázis', + DB_ERROR_ACCESS_VIOLATION => 'nincs jogosultság' +); +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/lang/adodb-uk1251.inc.php b/phpgwapi/inc/adodb/lang/adodb-uk1251.inc.php new file mode 100644 index 0000000000..9fa32ed5b4 --- /dev/null +++ b/phpgwapi/inc/adodb/lang/adodb-uk1251.inc.php @@ -0,0 +1,35 @@ + 'uk1251', + DB_ERROR => 'íåâ³äîìà ïîìèëêà', + DB_ERROR_ALREADY_EXISTS => 'âæå ³ñíóº', + DB_ERROR_CANNOT_CREATE => 'íåìîæëèâî ñòâîðèòè', + DB_ERROR_CANNOT_DELETE => 'íåìîæëèâî âèäàëèòè', + DB_ERROR_CANNOT_DROP => 'íåìîæëèâî çíèùèòè (drop)', + DB_ERROR_CONSTRAINT => 'ïîðóøåííÿ óìîâ ïåðåâ³ðêè', + DB_ERROR_DIVZERO => 'ä³ëåííÿ íà 0', + DB_ERROR_INVALID => 'íåïðàâèëüíî', + DB_ERROR_INVALID_DATE => 'íåïðàâèëüíà äàòà ÷è ÷àñ', + DB_ERROR_INVALID_NUMBER => 'íåïðàâèëüíå ÷èñëî', + DB_ERROR_MISMATCH => 'ïîìèëêà', + DB_ERROR_NODBSELECTED => 'íå âèáðàíî ÁÄ', + DB_ERROR_NOSUCHFIELD => 'íå ³ñíóº ïîëå', + DB_ERROR_NOSUCHTABLE => 'íå ³ñíóº òàáëèöÿ', + DB_ERROR_NOT_CAPABLE => 'ÑÓÁÄ íå â ñòàí³', + DB_ERROR_NOT_FOUND => 'íå çíàéäåíî', + DB_ERROR_NOT_LOCKED => 'íå çàáëîêîâàíî', + DB_ERROR_SYNTAX => 'ñèíòàêñè÷íà ïîìèëêà', + DB_ERROR_UNSUPPORTED => 'íå ï³äòðèìóºòüñÿ', + DB_ERROR_VALUE_COUNT_ON_ROW => 'ðàõ³âíèê çíà÷åíü â ñòð³÷ö³', + DB_ERROR_INVALID_DSN => 'íåïðàâèëüíà DSN', + DB_ERROR_CONNECT_FAILED => 'ç\'ºäíàííÿ íåóñï³øíå', + 0 => 'âñå ãàðàçä', // DB_OK + DB_ERROR_NEED_MORE_DATA => 'íàäàíî íåäîñòàòíüî äàíèõ', + DB_ERROR_EXTENSION_NOT_FOUND=> 'ðîçøèðåííÿ íå çíàéäåíî', + DB_ERROR_NOSUCHDB => 'íå ³ñíóº ÁÄ', + DB_ERROR_ACCESS_VIOLATION => 'íåäîñòàòíüî ïðàâ äîñòóïà' +); +?> diff --git a/phpgwapi/inc/adodb/pear/Auth/Container/ADOdb.php b/phpgwapi/inc/adodb/pear/Auth/Container/ADOdb.php index e4ab3eb711..d73433ae40 100644 --- a/phpgwapi/inc/adodb/pear/Auth/Container/ADOdb.php +++ b/phpgwapi/inc/adodb/pear/Auth/Container/ADOdb.php @@ -82,7 +82,6 @@ class Auth_Container_ADOdb extends Auth_Container } else { // Extract db_type from dsn string. $this->options['dsn'] = $dsn; - $this->_parseDsn( $dsn ); } } @@ -100,22 +99,12 @@ class Auth_Container_ADOdb extends Auth_Container { if (is_string($dsn) || is_array($dsn)) { if(!$this->db) { - $this->db = &ADONewConnection($this->options['db_type']); - + $this->db = &ADONewConnection($dsn); if( $err = ADODB_Pear_error() ) { return PEAR::raiseError($err); } } - $dbconnected = $this->db->Connect( - $this->options['db_host'], - $this->options['db_user'], - $this->options['db_pass'], - $this->options['db_name'] ); - if( !$dbconnected ) { - PEAR::raiseError('Unable to connect to database' ); - } - } else { return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, 41, @@ -410,23 +399,11 @@ class Auth_Container_ADOdb extends Auth_Container } // }}} - - function _parseDsn( $dsn ) - { - if( is_string( $dsn )) { - preg_match( '/^(\w*):\/\/(\w*)(:(\w*))?@(\w*)\/(\w*)$/', $dsn, $match ); - - $this->options['db_type'] = $match[1]; - $this->options['db_user'] = $match[2]; - $this->options['db_pass'] = $match[3]; - $this->options['db_host'] = $match[5]; - $this->options['db_name'] = $match[6]; - } - } } function showDbg( $string ) { - print "

    $string

    "; + print " +-- $string

    "; } function dump( $var, $str, $vardump = false ) { print "

    $str

    ";
    diff --git a/phpgwapi/inc/adodb/perf/perf-db2.inc.php b/phpgwapi/inc/adodb/perf/perf-db2.inc.php
    index 1b7d93ae34..2ba22149f7 100644
    --- a/phpgwapi/inc/adodb/perf/perf-db2.inc.php
    +++ b/phpgwapi/inc/adodb/perf/perf-db2.inc.php
    @@ -1,6 +1,6 @@
     conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
    +		
     		$rs = $this->conn->Execute('show status');
    +		
    +		if (isset($savem)) $this->conn->SetFetchMode($savem);
     		$ADODB_FETCH_MODE = $save;
     		
     		if (!$rs) return 0;
    @@ -157,7 +161,11 @@ class perf_mysql extends adodb_perf{
     	global $ADODB_FETCH_MODE;
     		$save = $ADODB_FETCH_MODE;
     		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
    +		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
    +		
     		$rs = $this->conn->Execute('show status');
    +		
    +		if (isset($savem)) $this->conn->SetFetchMode($savem);
     		$ADODB_FETCH_MODE = $save;
     		
     		if (!$rs) return 0;
    @@ -185,7 +193,17 @@ class perf_mysql extends adodb_perf{
     	{
     		// first find out type of table
     		//$this->conn->debug=1;
    +		
    +		global $ADODB_FETCH_MODE;
    +		$save = $ADODB_FETCH_MODE;
    +		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
    +		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
    +		
     		$rs = $this->conn->Execute('show table status');
    +		
    +		if (isset($savem)) $this->conn->SetFetchMode($savem);
    +		$ADODB_FETCH_MODE = $save;
    +		
     		if (!$rs) return '';
     		$type = strtoupper($rs->fields[1]);
     		$rs->Close();
    @@ -209,7 +227,7 @@ class perf_mysql extends adodb_perf{
     		$total += $this->_DBParameter(array("show status","Qcache_not_cached"));
     		
     		$total += $hits;
    -		if ($total) return ($hits*100)/$total;
    +		if ($total) return round(($hits*100)/$total,2);
     		return 0;
     	}
     	
    @@ -227,9 +245,17 @@ class perf_mysql extends adodb_perf{
     	*/
     	function GetInnoDBHitRatio()
     	{
    -	global $HTTP_SESSION_VARS;
    +	global $ADODB_FETCH_MODE;
     	
    +		$save = $ADODB_FETCH_MODE;
    +		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
    +		if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
    +		
     		$rs = $this->conn->Execute('show innodb status');
    +		
    +		if (isset($savem)) $this->conn->SetFetchMode($savem);
    +		$ADODB_FETCH_MODE = $save;
    +		
     		if (!$rs || $rs->EOF) return 0;
     		$stat = $rs->fields[0];
     		$rs->Close();
    @@ -237,10 +263,10 @@ class perf_mysql extends adodb_perf{
     		$stat = substr($stat,$at,200);
     		if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {
     			$val = 100*$arr[1]/$arr[2];
    -			$HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;
    -			return $val;
    +			$_SESSION['INNODB_HIT_PCT'] = $val;
    +			return round($val,2);
     		} else {
    -			if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];
    +			if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
     			return 0;
     		}
     		return 0;
    @@ -252,8 +278,38 @@ class perf_mysql extends adodb_perf{
     		$reqs = $this->_DBParameter(array("show status","Key_reads"));
     		if ($reqs == 0) return 0;
     		
    -		return ($hits/($reqs+$hits))*100;
    +		return round(($hits/($reqs+$hits))*100,2);
     	}
     	
    +    // start hack 
    +    var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK';
    +    var $optimizeTableHigh = 'OPTIMIZE TABLE %s';
    +    
    +    /** 
    +     * @see adodb_perf#optimizeTable
    +     */
    +     function optimizeTable( $table, $mode = ADODB_OPT_LOW) 
    +     {
    +        if ( !is_string( $table)) return false;
    +        
    +        $conn = $this->conn;
    +        if ( !$conn) return false;
    +        
    +        $sql = '';
    +        switch( $mode) {
    +            case ADODB_OPT_LOW : $sql = $this->optimizeTableLow; break;
    +            case ADODB_OPT_HIGH : $sql = $this->optimizeTableHigh; break;
    +            default : 
    +            {
    +                // May dont use __FUNCTION__ constant for BC (__FUNCTION__ Added in PHP 4.3.0)
    +                ADOConnection::outp( sprintf( "

    %s: '%s' using of undefined mode '%s'

    ", __CLASS__, __FUNCTION__, $mode)); + return false; + } + } + $sql = sprintf( $sql, $table); + + return $conn->Execute( $sql) !== false; + } + // end hack } ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/perf/perf-oci8.inc.php b/phpgwapi/inc/adodb/perf/perf-oci8.inc.php index d2bebe9cd0..3c0170efd4 100644 --- a/phpgwapi/inc/adodb/perf/perf-oci8.inc.php +++ b/phpgwapi/inc/adodb/perf/perf-oci8.inc.php @@ -1,6 +1,6 @@ conn->BeginTrans(); $id = "ADODB ".microtime(); + $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql"); $m = $this->conn->ErrorMsg(); if ($m) { @@ -271,7 +272,7 @@ CREATE TABLE PLAN_TABLE ( $s .= "

    $m

    "; return $s; } - $rs = $this->conn->Execute(" + $rs =& $this->conn->Execute(" select '
    '||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'
    ' as Operation, object_name,COST,CARDINALITY,bytes @@ -345,7 +346,7 @@ select a.size_for_estimate as cache_mb_estimate, $check = $rs->fields[0].'::'.$rs->fields[1]; } else $sql .= $rs->fields[2]; - + if (substr($sql,strlen($sql)-1) == "\0") $sql = substr($sql,0,strlen($sql)-1); $rs->MoveNext(); } $rs->Close(); @@ -402,28 +403,33 @@ where order by 1 desc, s.address, p.piece"; - global $ADODB_CACHE_MODE,$HTTP_GET_VARS; - if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) { - $partial = empty($HTTP_GET_VARS['part']); - echo "".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n"; + global $ADODB_CACHE_MODE; + if (isset($_GET['expsixora']) && isset($_GET['sql'])) { + $partial = empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; } - if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL(); + if (isset($_GET['sql'])) return $this->_SuspiciousSQL($numsql); + + $s = ''; + $s .= $this->_SuspiciousSQL($numsql); + $s .= '

    '; $save = $ADODB_CACHE_MODE; $ADODB_CACHE_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + $savelog = $this->conn->LogSQL(false); $rs =& $this->conn->SelectLimit($sql); $this->conn->LogSQL($savelog); + + if (isset($savem)) $this->conn->SetFetchMode($savem); $ADODB_CACHE_MODE = $save; if ($rs) { - $s = "\n

    Ixora Suspicious SQL

    "; + $s .= "\n

    Ixora Suspicious SQL

    "; $s .= $this->tohtml($rs,'expsixora'); - } else - $s = ''; + } - if ($s) $s .= '

    '; - $s .= $this->_SuspiciousSQL(); return $s; } @@ -467,31 +473,35 @@ where order by 1 desc, s.address, p.piece "; - global $ADODB_CACHE_MODE,$HTTP_GET_VARS; - if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) { - $partial = empty($HTTP_GET_VARS['part']); - echo "".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n"; + global $ADODB_CACHE_MODE; + if (isset($_GET['expeixora']) && isset($_GET['sql'])) { + $partial = empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; } - - if (isset($HTTP_GET_VARS['sql'])) { - $var =& $this->_ExpensiveSQL(); + if (isset($_GET['sql'])) { + $var = $this->_ExpensiveSQL($numsql); return $var; } + + $s = ''; + $s .= $this->_ExpensiveSQL($numsql); + $s .= '

    '; $save = $ADODB_CACHE_MODE; $ADODB_CACHE_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + $savelog = $this->conn->LogSQL(false); $rs =& $this->conn->Execute($sql); $this->conn->LogSQL($savelog); + + if (isset($savem)) $this->conn->SetFetchMode($savem); $ADODB_CACHE_MODE = $save; + if ($rs) { - $s = "\n

    Ixora Expensive SQL

    "; + $s .= "\n

    Ixora Expensive SQL

    "; $s .= $this->tohtml($rs,'expeixora'); - } else - $s = ''; - - - if ($s) $s .= '

    '; - $s .= $this->_ExpensiveSQL(); + } + return $s; } diff --git a/phpgwapi/inc/adodb/perf/perf-postgres.inc.php b/phpgwapi/inc/adodb/perf/perf-postgres.inc.php index b4d2e9e0ba..123c0f73ce 100644 --- a/phpgwapi/inc/adodb/perf/perf-postgres.inc.php +++ b/phpgwapi/inc/adodb/perf/perf-postgres.inc.php @@ -1,7 +1,7 @@ stats_start_collector,stats_row_level and stats_block_level must be set to true in postgresql.conf)'), 'data cache hit ratio' => array('RATIO', - "select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'", + "select case when blks_hit=0 then 0 else round( ((1-blks_read::float/blks_hit)*100)::numeric, 2) end from pg_stat_database where datname='\$DATABASE'", '=WarnCacheRatio'), 'IO', 'data reads' => array('IO', 'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables', ), 'data writes' => array('IO', - 'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables', + 'select round((sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16)::numeric,2) from pg_stat_user_tables', 'Count of inserts/updates/deletes * coef'), 'Data Cache', @@ -66,8 +66,9 @@ class perf_postgres extends adodb_perf{ "select setting::integer*8192 from pg_settings where name='effective_cache_size'", '(effective cache size)' ), 'Memory Usage', - 'sort buffer size' => array('CACHE', - "select setting::integer*1024 from pg_settings where name='sort_mem'", + # Postgres 7.5 changelog: Rename server parameters SortMem and VacuumMem to work_mem and maintenance_work_mem; + 'sort/work buffer size' => array('CACHE', + "select setting::integer*1024 from pg_settings where name='sort_mem' or name = 'work_mem' order by name", 'Size of sort buffer (per query)' ), 'Connections', 'current connections' => array('SESS', diff --git a/phpgwapi/inc/adodb/pivottable.inc.php b/phpgwapi/inc/adodb/pivottable.inc.php index 16b4cc7a48..e67f8df54a 100644 --- a/phpgwapi/inc/adodb/pivottable.inc.php +++ b/phpgwapi/inc/adodb/pivottable.inc.php @@ -1,6 +1,6 @@ databaseType,'access') !== false; + // note - vfp still doesn' work even with IIF enabled || $db->databaseType == 'vfp'; //$hidecnt = false; @@ -47,20 +49,39 @@ $sel = "$rowfields, "; if (is_array($colfield)) { foreach ($colfield as $k => $v) { - if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", "; - if ($aggfield) - $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", "; + $k = trim($k); + if (!$hidecnt) { + $sel .= $iif ? + "\n\t$aggfn(IIF($v,1,0)) AS \"$k\", " + : + "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", "; + } + if ($aggfield) { + $sel .= $iif ? + "\n\t$aggfn(IIF($v,$aggfield,0)) AS \"$sumlabel$k\", " + : + "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", "; + } } } else { foreach ($colarr as $v) { if (!is_numeric($v)) $vq = $db->qstr($v); else $vq = $v; + $v = trim($v); if (strlen($v) == 0 ) $v = 'null'; - if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", "; + if (!$hidecnt) { + $sel .= $iif ? + "\n\t$aggfn(IIF($colfield=$vq,1,0)) AS \"$v\", " + : + "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", "; + } if ($aggfield) { if ($hidecnt) $label = $v; else $label = "{$v}_$aggfield"; - $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", "; + $sel .= $iif ? + "\n\t$aggfn(IIF($colfield=$vq,$aggfield,0)) AS \"$label\", " + : + "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", "; } } } @@ -123,7 +144,7 @@ GROUP BY CompanyName,QuantityPerUnit # # Query the main "product" table # Set the rows to CompanyName and QuantityPerUnit -# and the columns to the UnitsInStock for different ranges +# and the columns to the UnitsInStock for diiferent ranges # and define the joins to link to lookup tables # "categories" and "suppliers" # diff --git a/phpgwapi/inc/adodb/rsfilter.inc.php b/phpgwapi/inc/adodb/rsfilter.inc.php index f444cbfd8f..25e1d75404 100644 --- a/phpgwapi/inc/adodb/rsfilter.inc.php +++ b/phpgwapi/inc/adodb/rsfilter.inc.php @@ -1,6 +1,6 @@ RecordCount(); for ($i=0; $i < $rows; $i++) { - $fn($rs->_array[$i],$rs); + if (is_array ($fn)) { + $obj = $fn[0]; + $method = $fn[1]; + $obj->$method ($rs->_array[$i],$rs); + } else { + $fn($rs->_array[$i],$rs); + } + } if (!$rs->EOF) { $rs->_currentRow = 0; diff --git a/phpgwapi/inc/adodb/server.php b/phpgwapi/inc/adodb/server.php index baf6f22a99..bc29b48a14 100644 --- a/phpgwapi/inc/adodb/server.php +++ b/phpgwapi/inc/adodb/server.php @@ -1,7 +1,7 @@ Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg()); -$sql = undomq($HTTP_GET_VARS['sql']); +$sql = undomq($_GET['sql']); -if (isset($HTTP_GET_VARS['fetch'])) - $ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch']; +if (isset($_GET['fetch'])) + $ADODB_FETCH_MODE = $_GET['fetch']; -if (isset($HTTP_GET_VARS['nrows'])) { - $nrows = $HTTP_GET_VARS['nrows']; - $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1; +if (isset($_GET['nrows'])) { + $nrows = $_GET['nrows']; + $offset = isset($_GET['offset']) ? $_GET['offset'] : -1; $rs = $conn->SelectLimit($sql,$nrows,$offset); } else $rs = $conn->Execute($sql); diff --git a/phpgwapi/inc/adodb/session/adodb-compress-bzip2.php b/phpgwapi/inc/adodb/session/adodb-compress-bzip2.php index 3e413b708a..9caceca9c9 100644 --- a/phpgwapi/inc/adodb/session/adodb-compress-bzip2.php +++ b/phpgwapi/inc/adodb/session/adodb-compress-bzip2.php @@ -1,7 +1,7 @@ Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id)); + + /* it is possible that the update statement fails due to a collision */ + if (!$ok) { + session_id($old_id); + if (empty($ck)) $ck = session_get_cookie_params(); + setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']); + return false; + } + + return true; +} + +/* + Generate database table for session data + @see http://phplens.com/lens/lensforum/msgs.php?id=12280 + @return 0 if failure, 1 if errors, 2 if successful. + @author Markus Staab http://www.public-4u.de +*/ +function adodb_session_create_table($schemaFile=null,$conn = null) +{ + // set default values + if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema.xml'; + if ($conn===null) $conn =& ADODB_Session::_conn(); + + if (!$conn) return 0; + + $schema = new adoSchema($conn); + $schema->ParseSchema($schemaFile); + return $schema->ExecuteSchema(); +} + /*! \static */ @@ -40,7 +111,17 @@ class ADODB_Session { ///////////////////// // getter/setter methods ///////////////////// - + + /* + + function Lock($lock=null) + { + static $_lock = false; + + if (!is_null($lock)) $_lock = $lock; + return $lock; + } + */ /*! */ function driver($driver = null) { @@ -138,7 +219,8 @@ class ADODB_Session { /*! */ - function persist($persist = null) { + function persist($persist = null) + { static $_persist = true; if (!is_null($persist)) { @@ -431,7 +513,6 @@ class ADODB_Session { $user = ADODB_Session::user(); if (!is_null($persist)) { - $persist = (bool) $persist; ADODB_Session::persist($persist); } else { $persist = ADODB_Session::persist(); @@ -443,7 +524,7 @@ class ADODB_Session { # assert('$host'); // cannot use =& below - do not know why... - $conn = ADONewConnection($driver); + $conn =& ADONewConnection($driver); if ($debug) { $conn->debug = true; @@ -451,7 +532,12 @@ class ADODB_Session { } if ($persist) { - $ok = $conn->PConnect($host, $user, $password, $database); + switch($persist) { + default: + case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break; + case 'C': $ok = $conn->Connect($host, $user, $password, $database); break; + case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break; + } } else { $ok = $conn->Connect($host, $user, $password, $database); } @@ -468,12 +554,10 @@ class ADODB_Session { Close the connection */ function close() { +/* $conn =& ADODB_Session::_conn(); - - if ($conn) { - $conn->Close(); - } - + if ($conn) $conn->Close(); +*/ return true; } @@ -494,9 +578,16 @@ class ADODB_Session { $qkey = $conn->quote($key); $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; - + $sql = "SELECT $data FROM $table WHERE $binary sesskey = $qkey AND expiry >= " . time(); - $rs =& $conn->Execute($sql); + /* Lock code does not work as it needs to hold transaction within whole page, and we don't know if + developer has commited elsewhere... :( + */ + #if (ADODB_Session::Lock()) + # $rs =& $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), $data); + #else + + $rs =& $conn->Execute($sql); //ADODB_Session::_dumprs($rs); if ($rs) { if ($rs->EOF) { @@ -537,16 +628,16 @@ class ADODB_Session { $filter = ADODB_Session::filter(); $lifetime = ADODB_Session::lifetime(); $table = ADODB_Session::table(); - + if (!$conn) { return false; } - + $qkey = $conn->qstr($key); + assert('$table'); $expiry = time() + $lifetime; - $qkey = $conn->quote($key); $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; // crc32 optimization since adodb 2.1 @@ -555,8 +646,8 @@ class ADODB_Session { if ($debug) { echo '

    Session: Only updating date - crc32 not changed

    '; } - $sql = "UPDATE $table SET expiry = $expiry WHERE $binary sesskey = $qkey AND expiry >= " . time(); - $rs =& $conn->Execute($sql); + $sql = "UPDATE $table SET expiry = ".$conn->Param('0')." WHERE $binary sesskey = ".$conn->Param('1')." AND expiry >= ".$conn->Param('2'); + $rs =& $conn->Execute($sql,array($expiry,$key,time())); ADODB_Session::_dumprs($rs); if ($rs) { $rs->Close(); @@ -599,7 +690,7 @@ class ADODB_Session { $lob_value = 'null'; break; } - + // do we insert or update? => as for sesskey $rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = $qkey"); ADODB_Session::_dumprs($rs); @@ -646,7 +737,10 @@ class ADODB_Session { $rs->Close(); } } - } + }/* + if (ADODB_Session::Lock()) { + $conn->CommitTrans(); + }*/ return $rs ? true : false; } @@ -783,10 +877,9 @@ class ADODB_Session { $t = time(); if (abs($dbt - $t) >= $sync_seconds) { - global $HTTP_SERVER_VARS; $msg = __FILE__ . - ": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: " . - " database=$dbt ($dbts), webserver=$t (diff=". (abs($dbt - $t) / 3600) . ' hours)'; + ": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: " . + " database=$dbt ($dbts), webserver=$t (diff=". (abs($dbt - $t) / 60) . ' minutes)'; error_log($msg); if ($debug) { ADOConnection::outp("

    $msg

    "); @@ -797,7 +890,6 @@ class ADODB_Session { return true; } - } ADODB_Session::_init(); diff --git a/phpgwapi/inc/adodb/session/adodb-sessions.oracle.clob.sql b/phpgwapi/inc/adodb/session/adodb-sessions.oracle.clob.sql new file mode 100644 index 0000000000..c5c4f2d070 --- /dev/null +++ b/phpgwapi/inc/adodb/session/adodb-sessions.oracle.clob.sql @@ -0,0 +1,15 @@ +-- $CVSHeader$ + +DROP TABLE adodb_sessions; + +CREATE TABLE sessions ( + sesskey CHAR(32) DEFAULT '' NOT NULL, + expiry INT DEFAULT 0 NOT NULL, + expireref VARCHAR(64) DEFAULT '', + data CLOB DEFAULT '', + PRIMARY KEY (sesskey) +); + +CREATE INDEX ix_expiry ON sessions (expiry); + +QUIT; diff --git a/phpgwapi/inc/adodb/session/adodb-sessions.oracle.sql b/phpgwapi/inc/adodb/session/adodb-sessions.oracle.sql new file mode 100644 index 0000000000..8fd5a34232 --- /dev/null +++ b/phpgwapi/inc/adodb/session/adodb-sessions.oracle.sql @@ -0,0 +1,16 @@ +-- $CVSHeader$ + +DROP TABLE adodb_sessions; + +CREATE TABLE sessions ( + sesskey CHAR(32) DEFAULT '' NOT NULL, + expiry INT DEFAULT 0 NOT NULL, + expireref VARCHAR(64) DEFAULT '', + data VARCHAR(4000) DEFAULT '', + PRIMARY KEY (sesskey), + INDEX expiry (expiry) +); + +CREATE INDEX ix_expiry ON sessions (expiry); + +QUIT; diff --git a/phpgwapi/inc/adodb/session/old/adodb-cryptsession.php b/phpgwapi/inc/adodb/session/old/adodb-cryptsession.php index 2ac7d024c5..d28712a5fd 100644 --- a/phpgwapi/inc/adodb/session/old/adodb-cryptsession.php +++ b/phpgwapi/inc/adodb/session/old/adodb-cryptsession.php @@ -1,6 +1,6 @@ \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; Installation @@ -192,7 +192,8 @@ $Crypt = new MD5Crypt; 'sesskey',$autoQuote = true); if (!$rs) { - ADOConnection::outp( '

    Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'

    ',false); + ADOConnection::outp( ' +-- Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'

    ',false); } else { // bug in access driver (could be odbc?) means that info is not commited // properly unless select statement executed in Win2000 @@ -286,11 +287,11 @@ function adodb_sess_gc($maxlifetime) { $dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts); $t = time(); if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) { - global $HTTP_SERVER_VARS; $msg = - __FILE__.": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; + __FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; error_log($msg); - if ($ADODB_SESS_DEBUG) ADOConnection::outp("

    $msg

    "); + if ($ADODB_SESS_DEBUG) ADOConnection::outp(" +-- $msg

    "); } } @@ -310,12 +311,12 @@ session_set_save_handler( /* TEST SCRIPT -- UNCOMMENT */ /* if (0) { -GLOBAL $HTTP_SESSION_VARS; session_start(); session_register('AVAR'); - $HTTP_SESSION_VARS['AVAR'] += 1; - print "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; } */ ?> diff --git a/phpgwapi/inc/adodb/session/old/adodb-session-clob.php b/phpgwapi/inc/adodb/session/old/adodb-session-clob.php index 2d02a8107a..a143a4e365 100644 --- a/phpgwapi/inc/adodb/session/old/adodb-session-clob.php +++ b/phpgwapi/inc/adodb/session/old/adodb-session-clob.php @@ -1,6 +1,6 @@ \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; To force non-persistent connections, call adodb_session_open first before session_start(): - GLOBAL $HTTP_SESSION_VARS; include('adodb.inc.php'); include('adodb-session.php'); adodb_session_open(false,false,false); session_start(); session_register('AVAR'); - $HTTP_SESSION_VARS['AVAR'] += 1; - print "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; Installation @@ -57,7 +57,7 @@ To force non-persistent connections, call adodb_session_open first before sessio $ADODB_SESSION_TBL = 'sessions' $ADODB_SESSION_USE_LOBS = false; (or, if you wanna use CLOBS (= 'CLOB') or ( = 'BLOB') - 3. Recommended is PHP 4.0.6 or later. There are documented + 3. Recommended is PHP 4.1.0 or later. There are documented session bugs in earlier versions of PHP. 4. If you want to receive notifications when a session expires, then @@ -191,7 +191,8 @@ GLOBAL $ADODB_SESSION_CONNECT, else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT, $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB); - if (!$ok) ADOConnection::outp( "

    Session: connection failed

    ",false); + if (!$ok) ADOConnection::outp( " +-- Session: connection failed

    ",false); } /****************************************************************************************\ @@ -252,7 +253,8 @@ function adodb_sess_write($key, $val) // crc32 optimization since adodb 2.1 // now we only update expiry date, thx to sebastian thom in adodb 2.32 if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) { - if ($ADODB_SESS_DEBUG) echo "

    Session: Only updating date - crc32 not changed

    "; + if ($ADODB_SESS_DEBUG) echo " +-- Session: Only updating date - crc32 not changed

    "; $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); $rs = $ADODB_SESS_CONN->Execute($qry); return true; @@ -311,7 +313,8 @@ function adodb_sess_write($key, $val) } if (!$rs) { - ADOConnection::outp( '

    Session Replace: '.nl2br($err).'

    ',false); + ADOConnection::outp( ' +-- Session Replace: '.nl2br($err).'

    ',false); } else { // bug in access driver (could be odbc?) means that info is not commited // properly unless select statement executed in Win2000 @@ -378,7 +381,8 @@ function adodb_sess_gc($maxlifetime) } else { $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time()); - if ($ADODB_SESS_DEBUG) ADOConnection::outp("

    Garbage Collection: $qry

    "); + if ($ADODB_SESS_DEBUG) ADOConnection::outp(" +-- Garbage Collection: $qry

    "); } // suggested by Cameron, "GaM3R" if (defined('ADODB_SESSION_OPTIMIZE')) { @@ -409,11 +413,11 @@ function adodb_sess_gc($maxlifetime) $dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts); $t = time(); if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) { - global $HTTP_SERVER_VARS; $msg = - __FILE__.": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; + __FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; error_log($msg); - if ($ADODB_SESS_DEBUG) ADOConnection::outp("

    $msg

    "); + if ($ADODB_SESS_DEBUG) ADOConnection::outp(" +-- $msg

    "); } } @@ -433,12 +437,12 @@ session_set_save_handler( /* TEST SCRIPT -- UNCOMMENT */ if (0) { -GLOBAL $HTTP_SESSION_VARS; session_start(); session_register('AVAR'); - $HTTP_SESSION_VARS['AVAR'] += 1; - ADOConnection::outp( "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    ",false); + $_SESSION['AVAR'] += 1; + ADOConnection::outp( " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    ",false); } ?> diff --git a/phpgwapi/inc/adodb/session/old/adodb-session.php b/phpgwapi/inc/adodb/session/old/adodb-session.php index 3996458802..d1e057ab55 100644 --- a/phpgwapi/inc/adodb/session/old/adodb-session.php +++ b/phpgwapi/inc/adodb/session/old/adodb-session.php @@ -1,6 +1,6 @@ \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; To force non-persistent connections, call adodb_session_open first before session_start(): - GLOBAL $HTTP_SESSION_VARS; include('adodb.inc.php'); include('adodb-session.php'); adodb_sess_open(false,false,false); session_start(); session_register('AVAR'); - $HTTP_SESSION_VARS['AVAR'] += 1; - print "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + $_SESSION['AVAR'] += 1; + print " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; Installation @@ -67,7 +67,7 @@ To force non-persistent connections, call adodb_session_open first before sessio $ADODB_SESSION_DB ='database'; $ADODB_SESSION_TBL = 'sessions' - 3. Recommended is PHP 4.0.6 or later. There are documented + 3. Recommended is PHP 4.1.0 or later. There are documented session bugs in earlier versions of PHP. 4. If you want to receive notifications when a session expires, then @@ -107,6 +107,37 @@ if (!defined('ADODB_SESSION')) { /* if database time and system time is difference is greater than this, then give warning */ define('ADODB_SESSION_SYNCH_SECS',60); + /* + Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1 +*/ +function adodb_session_regenerate_id() +{ + $conn =& ADODB_Session::_conn(); + if (!$conn) return false; + + $old_id = session_id(); + if (function_exists('session_regenerate_id')) { + session_regenerate_id(); + } else { + session_id(md5(uniqid(rand(), true))); + $ck = session_get_cookie_params(); + setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']); + //@session_start(); + } + $new_id = session_id(); + $ok =& $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id)); + + /* it is possible that the update statement fails due to a collision */ + if (!$ok) { + session_id($old_id); + if (empty($ck)) $ck = session_get_cookie_params(); + setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']); + return false; + } + + return true; +} + /****************************************************************************************\ Global definitions \****************************************************************************************/ @@ -193,7 +224,8 @@ GLOBAL $ADODB_SESSION_CONNECT, else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT, $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB); - if (!$ok) ADOConnection::outp( "

    Session: connection failed

    ",false); + if (!$ok) ADOConnection::outp( " +-- Session: connection failed

    ",false); } /****************************************************************************************\ @@ -252,7 +284,8 @@ function adodb_sess_write($key, $val) // crc32 optimization since adodb 2.1 // now we only update expiry date, thx to sebastian thom in adodb 2.32 if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) { - if ($ADODB_SESS_DEBUG) echo "

    Session: Only updating date - crc32 not changed

    "; + if ($ADODB_SESS_DEBUG) echo " +-- Session: Only updating date - crc32 not changed

    "; $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); $rs = $ADODB_SESS_CONN->Execute($qry); return true; @@ -269,7 +302,8 @@ function adodb_sess_write($key, $val) 'sesskey',$autoQuote = true); if (!$rs) { - ADOConnection::outp( '

    Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'

    ',false); + ADOConnection::outp( ' +-- Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'

    ',false); } else { // bug in access driver (could be odbc?) means that info is not commited // properly unless select statement executed in Win2000 @@ -336,7 +370,8 @@ function adodb_sess_gc($maxlifetime) $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time(); $ADODB_SESS_CONN->Execute($qry); - if ($ADODB_SESS_DEBUG) ADOConnection::outp("

    Garbage Collection: $qry

    "); + if ($ADODB_SESS_DEBUG) ADOConnection::outp(" +-- Garbage Collection: $qry

    "); } // suggested by Cameron, "GaM3R" if (defined('ADODB_SESSION_OPTIMIZE')) { @@ -368,11 +403,12 @@ function adodb_sess_gc($maxlifetime) $t = time(); if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) { - global $HTTP_SERVER_VARS; + $msg = - __FILE__.": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; + __FILE__.": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)"; error_log($msg); - if ($ADODB_SESS_DEBUG) ADOConnection::outp("

    $msg

    "); + if ($ADODB_SESS_DEBUG) ADOConnection::outp(" +-- $msg

    "); } } @@ -392,12 +428,12 @@ session_set_save_handler( /* TEST SCRIPT -- UNCOMMENT */ if (0) { -GLOBAL $HTTP_SESSION_VARS; session_start(); session_register('AVAR'); - $HTTP_SESSION_VARS['AVAR'] += 1; - ADOConnection::outp( "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    ",false); + $_SESSION['AVAR'] += 1; + ADOConnection::outp( " +-- \$_SESSION['AVAR']={$_SESSION['AVAR']}

    ",false); } ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/session/session_schema.xml b/phpgwapi/inc/adodb/session/session_schema.xml new file mode 100644 index 0000000000..3c61ff645a --- /dev/null +++ b/phpgwapi/inc/adodb/session/session_schema.xml @@ -0,0 +1,26 @@ + + + + table for ADOdb session-management + + + session key + + + + + + + + + + + + + + + + + +
    +
    diff --git a/phpgwapi/inc/adodb/tests/benchmark.php b/phpgwapi/inc/adodb/tests/benchmark.php index f76cdbbe20..61b39a000f 100644 --- a/phpgwapi/inc/adodb/tests/benchmark.php +++ b/phpgwapi/inc/adodb/tests/benchmark.php @@ -8,7 +8,7 @@ Connect($connstr,$u,$p) || die("CONNECT FAILED"); + + + echo "$connstr: Execute\n"; + + //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $rs = $DB->Execute("select * from ADOXYZ where id<3"); + echo "*** e=".$DB->ErrorNo() . " ".($DB->ErrorMsg())."\n"; + + + //print_r(get_class_methods($DB->_stmt)); + + if (!$rs) die("NO RS"); + + echo "Meta\n"; + for ($i=0; $i < $rs->NumCols(); $i++) { + var_dump($rs->FetchField($i)); + echo "
    "; + } + + echo "FETCH\n"; + $cnt = 0; + while (!$rs->EOF) { + adodb_pr($rs->fields); + $rs->MoveNext(); + if ($cnt++ > 1000) break; + } + + echo "
    --------------------------------------------------------
    \n\n\n"; + + $stmt = $DB->PrepareStmt("select * from ADOXYZ"); + + $rs = $stmt->Execute(); + $cols = $stmt->NumCols(); // execute required + + echo "COLS = $cols"; + for($i=1;$i<=$cols;$i++) { + $v = $stmt->_stmt->getColumnMeta($i); + var_dump($v); + } + + echo "e=".$stmt->ErrorNo() . " ".($stmt->ErrorMsg())."\n"; + while ($arr = $rs->FetchRow()) { + adodb_pr($arr); + } + die("DONE\n"); - -echo "New Connection\n"; -$DB = NewADOConnection('pdo'); -echo "Connect\n"; -$pdo_connection_string = 'odbc:nwind'; -$DB->Connect($pdo_connection_string,'','') || die("CONNECT FAILED"); -echo "Execute\n"; - - - -//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; -$rs = $DB->Execute("select * from products where productid<3"); -echo "e=".$DB->ErrorNo() . " ".($DB->ErrorMsg())."\n"; - - -//print_r(get_class_methods($DB->_stmt)); - -if (!$rs) die("NO RS"); -echo "FETCH\n"; -$cnt = 0; -while (!$rs->EOF) { - print_r($rs->fields); - $rs->MoveNext(); - if ($cnt++ > 1000) break; +} catch (exception $e) { + echo "
    ";
    +	echo $e;
    +	echo "
    "; } -echo "
    --------------------------------------------------------
    \n\n\n"; - -$stmt = $DB->PrepareStmt("select * from products"); -$rs = $stmt->Execute(); -echo "e=".$stmt->ErrorNo() . " ".($stmt->ErrorMsg())."\n"; -while ($arr = $rs->FetchRow()) { - print_r($arr); -} -die("DONE\n"); - ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/test-datadict.php b/phpgwapi/inc/adodb/tests/test-datadict.php index d2e6111243..ff83762dc9 100644 --- a/phpgwapi/inc/adodb/tests/test-datadict.php +++ b/phpgwapi/inc/adodb/tests/test-datadict.php @@ -1,7 +1,7 @@ $dbType

    "; $db = NewADOConnection($dbType); $dict = NewDataDictionary($db); @@ -60,37 +60,51 @@ TS T DEFTIMESTAMP"; $dict->SetSchema('KUTU'); $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts)); - $sqla =& array_merge($sqla,$sqli); + $sqla = array_merge($sqla,$sqli); $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH')); - $sqla =& array_merge($sqla,$sqli); + $sqla = array_merge($sqla,$sqli); $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED')); - $sqla =& array_merge($sqla,$sqli); + $sqla = array_merge($sqla,$sqli); $addflds = array(array('height', 'F'),array('weight','F')); $sqli = $dict->AddColumnSQL('testtable',$addflds); - $sqla =& array_merge($sqla,$sqli); + $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); + $sqla = array_merge($sqla,$sqli); printsqla($dbType,$sqla); if (file_exists('d:\inetpub\wwwroot\php\phplens\adodb\adodb.inc.php')) - if ($dbType == 'mysql') { + if ($dbType == 'mysqlt') { $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"); + if ($dbType == 'postgres') { + if (@$db->Connect('localhost', "tester", "test", "test")); $dict->SetSchema(''); $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds); if ($sqla2) printsqla($dbType,$sqla2); } + if ($dbType == 'odbc_mssql') { + $dsn = $dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=localhost;Database=northwind;"; + if (@$db->Connect($dsn, "sa", "natsoft", "test")); + $dict->SetSchema(''); + $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds); + if ($sqla2) printsqla($dbType,$sqla2); + } + + + + adodb_pr($dict->databaseType); + printsqla($dbType, $dict->DropColumnSQL('table',array('my col','`col2_with_Quotes`','A_col3','col3(10)'))); + printsqla($dbType, $dict->ChangeTableSQL('adoxyz','LASTNAME varchar(32)')); + } function printsqla($dbType,$sqla) @@ -224,6 +238,7 @@ ALTER TABLE KUTU.testtable ALTER COLUMN weight REAL NOT NULL; -------------------------------------------------------------------------------- */ + echo "

    Test XML Schema

    "; $ff = file('xmlschema.xml'); echo "
    ";
    diff --git a/phpgwapi/inc/adodb/tests/test-php5.php b/phpgwapi/inc/adodb/tests/test-php5.php
    index 18a7e58e15..5b073ba8f6 100644
    --- a/phpgwapi/inc/adodb/tests/test-php5.php
    +++ b/phpgwapi/inc/adodb/tests/test-php5.php
    @@ -1,6 +1,6 @@
     PHP ".PHP_VERSION."\n";
     try {
     
    -$dbt = 'oci8po';
    +$dbt = 'mysql';
     
    +try {
     switch($dbt) {
     case 'oci8po':
     	$db = NewADOConnection("oci8po");
    +	
     	$db->Connect('','scott','natsoft');
     	break;
     default:
     case 'mysql':
     	$db = NewADOConnection("mysql");
    -	$db->Connect('localhost','root','','test');
    +	$db->Connect('localhost','roots','','northwind');
     	break;
     	
     case 'mysqli':
    -	$db = NewADOConnection("mysqli://root:@localhost/test");
    +	$db = NewADOConnection("mysqli://root:@localhost/northwind");
     	//$db->Connect('localhost','root','','test');
     	break;
     }
    +} catch (exception $e){
    +	echo "Connect Failed";
    +	adodb_pr($e);
    +	die();
    +}
     
     $db->debug=1;
     
    @@ -44,16 +51,19 @@ $stmt = $db->Prepare("select * from adoxyz where ?ErrorMsg(),"\n";
     $rs = $db->Execute($stmt,array(10,20));
     
    +echo  "
    Foreach Iterator Test (rand=".rand().")
    "; $i = 0; -foreach($rs as $v) { +foreach($rs as $v) { $i += 1; - echo "rec $i: "; adodb_pr($v); adodb_pr($rs->fields); + echo "rec $i: "; $s1 = adodb_pr($v,true); $s2 = adodb_pr($rs->fields,true); + if ($s1 != $s2 && !empty($v)) {adodb_pr($s1); adodb_pr($s2);} + else echo "passed
    "; flush(); } if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n"); - +else echo "Count $i is correct
    "; $rs = $db->Execute("select bad from badder"); diff --git a/phpgwapi/inc/adodb/tests/test-xmlschema.php b/phpgwapi/inc/adodb/tests/test-xmlschema.php index 34886f2a0d..807aefe504 100644 --- a/phpgwapi/inc/adodb/tests/test-xmlschema.php +++ b/phpgwapi/inc/adodb/tests/test-xmlschema.php @@ -3,8 +3,8 @@ // V4.50 6 July 2004 error_reporting(E_ALL); - -require( "../adodb-xmlschema.inc.php" ); +include_once( "../adodb.inc.php" ); +include_once( "../adodb-xmlschema.inc.php" ); // To build the schema, start by creating a normal ADOdb connection: $db = ADONewConnection( 'mysql' ); @@ -33,14 +33,14 @@ print "
    \n"; //$schema->Destroy(); -$db2 = ADONewConnection('mssql'); -$db2->Connect('localhost','sa','natsoft','northwind') || die("Fail 2"); - -$db2->Execute("drop table simple_table"); - print "SQL to build xmlschema-mssql.xml:\n
    ";
     
    +$db2 = ADONewConnection('mssql');
    +$db2->Connect('','adodb','natsoft','northwind') || die("Fail 2");
    +
    +$db2->Execute("drop table simple_table");
    +
     $schema = new adoSchema( $db2 );
     $sql = $schema->ParseSchema( "xmlschema-mssql.xml" );
     
    @@ -49,5 +49,6 @@ print "
    \n"; $db2->debug=1; -$db2->Execute($sql[0]); +foreach ($sql as $s) +$db2->Execute($s); ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/test.php b/phpgwapi/inc/adodb/tests/test.php index 6b240a53c0..cf49c94415 100644 --- a/phpgwapi/inc/adodb/tests/test.php +++ b/phpgwapi/inc/adodb/tests/test.php @@ -1,6 +1,6 @@ $v) { - $arr[$k] = strtolower($v); + if (is_object($v)) $arr[$k] = adodb_pr($v,true); + else $arr[$k] = strtolower($v); } } @@ -63,7 +73,7 @@ global $CACHED; $CACHED++; 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; +GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE,$ADODB_COUNTRECS; ?>

    @@ -112,6 +122,8 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to else $ext = ''; print "

    ADODB Version: $ADODB_vers Host: $db->host   Database: $db->database   PHP: $phpv $ext

    "; flush(); + + $arr = $db->ServerInfo(); print_r($arr); echo "
    "; @@ -122,7 +134,7 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to if ($tt == 0) echo '
    $db->Time failed'; else echo "
    db->Time: ".date('d-m-Y H:i:s',$tt); echo '
    '; - + echo "Date=",$db->UserDate('2002-04-07'),'
    '; print "date1 (1969-02-20) = ".$db->DBDate('1969-2-20'); print "
    date1 (1999-02-20) = ".$db->DBDate('1999-2-20'); @@ -154,14 +166,9 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to //$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) { @@ -169,12 +176,17 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to print "Please create the following table for testing:

    $createtab

    "; return; } else { - $db->debug = 1; + $db->debug = 99; $e = error_reporting(E_ALL-E_WARNING); $db->Execute($createtab); error_reporting($e); } } + + echo "

    Testing Metatypes

    "; + $t = $db->MetaType('varchar'); + if ($t != 'C') Err("Bad Metatype for varchar"); + $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete if ($rs) { if(! $rs->EOF) print "Error: RecordSet returned by Execute('delete...') should show EOF

    "; @@ -184,11 +196,11 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to print "

    Test select on empty table, FetchField when EOF, and GetInsertSQL

    "; $rs = &$db->Execute("select id,firstname from ADOXYZ where id=9999"); if ($rs && !$rs->EOF) print "Error: RecordSet returned by Execute(select...') on empty table should show EOF

    "; - if ($rs->EOF && ($o = $rs->FetchField(0))) { + if ($rs->EOF && (($ox = $rs->FetchField(0)) && !empty($ox->name))) { $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"); + if (strtoupper($sql) != strtoupper("INSERT INTO ADOXYZ ( id, firstname ) VALUES ( 99, 'John' )")) Err("GetInsertSQL does not work on empty table: $sql"); } else { Err("FetchField does not work on empty recordset, meaning GetInsertSQL will fail..."); } @@ -277,6 +289,12 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to print '

    '; } + $db->debug=0; + $rez = $db->MetaColumns("NOSUCHTABLEHERE"); + if ($rez !== false) { + Err("MetaColumns error handling failed"); + var_dump($rez); + } $db->debug=1; $a = $db->MetaColumns('ADOXYZ'); if ($a===false) print "MetaColumns not supported

    "; @@ -306,6 +324,15 @@ FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_to switch ($db->databaseType) { + case 'vfp': + + if (0) { + // memo test + $rs = $db->Execute("select data from memo"); + rs2html($rs); + } + break; + case 'postgres7': case 'postgres64': case 'postgres': @@ -352,11 +379,24 @@ WHERE OD.OrderID = O.OrderID GROUP BY ProductName ORDER BY ProductName GO + + +CREATE PROCEDURE ADODBTestSP +@a nvarchar(25) +AS +SELECT GETDATE() AS T, @a AS A +GO */ print "

    Testing Stored Procedures for mssql

    "; $saved = $db->debug; $db->debug=true; + $cmd = $db->PrepareSP('ADODBTestSP'); + $ss = "You should see me in the output."; + $db->InParameter($cmd,$ss,'a'); + $rs = $db->Execute($cmd); + echo $rs->fields['T']." --- ".$rs->fields['A']."---
    "; + $cat = 'Dairy Products'; $yr = '1998'; @@ -376,7 +416,7 @@ GO rs2html($rs); /* - Test out params - works in 4.2.3 and 4.3.3 but not 4.3.0: + Test out params - works in PHP 4.2.3 and 4.3.3 and 4.3.8 but not 4.3.0: CREATE PROCEDURE at_date_interval @days INTEGER, @@ -398,7 +438,7 @@ GO $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)) { + if (empty($begin_date) or empty($end_date) or $begin_date == $end_date) { Err("MSSQL SP Test for OUT Failed"); print "begin=$begin_date end=$end_date

    "; } else print "(Today +10days) = (begin=$begin_date end=$end_date)

    "; @@ -407,9 +447,26 @@ GO break; case 'oci8': case 'oci8po': + + if (0) { + $t = getmicrotime(); + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $arr = $db->GetArray('select * from abalone_tree'); + $arr = $db->GetArray('select * from abalone_tree'); + $arr = $db->GetArray('select * from abalone_tree'); + echo "

    t = ",getmicrotime() - $t,"

    "; + die(); + } + + # cleanup + $db->Execute("delete from photos where id=99 or id=1"); + $db->Execute("insert into photos (id) values(1)"); + $db->Execute("update photos set photo=null,descclob=null where id=1"); + $saved = $db->debug; $db->debug=true; + /* CREATE TABLE PHOTOS @@ -427,7 +484,25 @@ GO $s .= '1234567890'; } + $sql = "INSERT INTO photos ( ID, photo) ". + "VALUES ( :id, empty_blob() )". + " RETURNING photo INTO :xx"; + + $blob_data = $s; + $id = 99; + + $stmt = $db->PrepareSP($sql); + $db->InParameter($stmt, $id, 'id'); + $blob = $db->InParameter($stmt, $s, 'xx',-1, OCI_B_BLOB); + $db->StartTrans(); + $result = $db->Execute($stmt); + $db->CompleteTrans(); + + $s2= $db->GetOne("select photo from photos where id=99"); + echo "
    ---$s2"; + if ($s !== $s2) Err("insert blob does not match"); + print "

    Testing Blob: size=".strlen($s)."

    "; $ok = $db->Updateblob('photos','photo',$s,'id=1'); if (!$ok) Err("Blob failed 1"); @@ -448,19 +523,20 @@ GO $s = ''; $s2 = ''; print "

    Testing Foreign Keys

    "; - $arr = $db->MetaForeignKeys('emp'); + $arr = $db->MetaForeignKeys('emp','scott'); print_r($arr); if (!$arr) Err("Bad MetaForeignKeys"); - print "

    Testing Cursor Variables

    "; /* -- TEST PACKAGE +-- "Set scan off" turns off substitution variables. +Set scan off; 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 open_tab2 (tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) ; PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR); - +PROCEDURE data_in(input IN VARCHAR); PROCEDURE myproc (p1 IN NUMBER, p2 OUT NUMBER); END Adodb; / @@ -477,11 +553,17 @@ PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames; tablenames := 'TEST'; END open_tab2; - + PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS BEGIN output := 'Cinta Hati '||input; END; + +PROCEDURE data_in(input IN VARCHAR) IS + ignore varchar(1000); + BEGIN + ignore := input; + END; PROCEDURE myproc (p1 IN NUMBER, p2 OUT NUMBER) AS BEGIN @@ -490,8 +572,9 @@ END; END Adodb; / - */ + + print "

    Testing Cursor Variables

    "; $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:zz,'A%'); END;",'zz'); if ($rs && !$rs->EOF) { @@ -501,6 +584,7 @@ END Adodb; } else { print "Error in using Cursor Variables 1

    "; } + $rs->Close(); print "

    Testing Stored Procedures for oci8

    "; @@ -517,7 +601,6 @@ END Adodb; print "Error in using Stored Procedure IN/Out Variables

    "; } - $tname = 'A%'; $stmt = $db->PrepareSP('select * from tab where tname like :tablename'); @@ -525,6 +608,10 @@ END Adodb; $rs = $db->Execute($stmt); rs2html($rs); + $stmt = $db->PrepareSP("begin adodb.data_in(:a1); end;"); + $db->InParameter($stmt,$a1,'a1'); + $db->Execute($stmt); + $db->debug = $saved; break; @@ -536,7 +623,7 @@ END Adodb; array(2,'John','Lim'), array(3,'Wai Hun','See') ); - $db->debug=1; + //$db->debug=1; print "

    Testing Bulk Insert of 3 rows

    "; $sql = "insert into ADOXYZ (id,firstname,lastname) values (".$db->Param('0').",".$db->Param('1').",".$db->Param('2').")"; @@ -544,7 +631,7 @@ END Adodb; $db->Execute($sql,$arr); $db->CompleteTrans(); $rs = $db->Execute('select * from ADOXYZ order by id'); - if ($rs->RecordCount() != 3) Err("Bad bulk insert"); + if (!$rs || $rs->RecordCount() != 3) Err("Bad bulk insert"); rs2html($rs); @@ -555,7 +642,7 @@ END Adodb; for ($i = 0; $i < 5; $i++) { $time = $db->DBDate(time()); - if (empty($HTTP_GET_VARS['hide'])) $db->debug = true; + if (empty($_GET['hide'])) $db->debug = true; switch($db->databaseType){ case 'mssqlpo': case 'mssql': @@ -577,7 +664,8 @@ END Adodb; $arr = array(0=>'Caroline',1=>'Miranda'); $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)"; break; - + case 'mysqli': + case 'mysqlt': case 'mysql': $sqlt = "CREATE TABLE `mytable` ( `row1` int(11) NOT NULL auto_increment, @@ -645,8 +733,9 @@ END Adodb; else print "

    Affected_Rows() passed

    "; } + /*if ($db->dataProvider == 'oci8') */ $array = array('zid'=>1,'zdate'=>date('Y-m-d',time())); + /*else $array=array(1,date('Y-m-d',time()));*/ - $array = array('zid'=>1,'zdate'=>date('Y-m-d',time())); $id = $db->GetOne("select id from ADOXYZ where id=".$db->Param('zid')." and created>=".$db->Param('ZDATE')."", $array); @@ -654,7 +743,6 @@ END Adodb; else echo "
    Bind date/integer passed"; $db->debug = false; - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; ////////////////////////////////////////////////////////////////////////////////////////// @@ -668,7 +756,8 @@ END Adodb; $rs = &$db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id"); if ($rs) { if ($rs->RecordCount() != 50) { - print "

    RecordCount returns ".$rs->RecordCount()."

    "; + print "

    RecordCount returns ".$rs->RecordCount().", should be 50

    "; + adodb_pr($rs->GetArray()); $poc = $rs->PO_RecordCount('ADOXYZ'); if ($poc == 50) print "

        PO_RecordCount passed

    "; else print "

    PO_RecordCount returns wrong value: $poc

    "; @@ -678,7 +767,7 @@ END Adodb; Err( '

    The fields columns cannot be indexed by column name.

    '); print_r($rs->fields); } - if (empty($HTTP_GET_VARS['hide'])) rs2html($rs); + if (empty($_GET['hide'])) rs2html($rs); } else print "

    Error in Execute of SELECT with random

    "; } @@ -695,22 +784,25 @@ END Adodb; } print "

    FetchObject/FetchNextObject Test

    "; - $rs = &$db->Execute('select * from ADOXYZ'); - - if (empty($rs->connection)) print "Connection object missing from recordset
    "; - - while ($o = $rs->FetchNextObject()) { // calls FetchObject internally - if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) { - print_r($o); - print "

    Firstname is not string

    "; - break; + $rs = $db->Execute('select * from ADOXYZ'); + if ($rs) { + if (empty($rs->connection)) print "Connection object missing from recordset
    "; + + while ($o = $rs->FetchNextObject()) { // calls FetchObject internally + if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) { + print_r($o); + print "

    Firstname is not string

    "; + break; + } } + } else { + print "

    Failed rs

    "; + die("

    ADOXYZ table cannot be read - die()"); } - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; print "

    FetchObject/FetchNextObject Test 2

    "; - - $rs = &$db->Execute('select * from ADOXYZ'); + #$db->debug=99; + $rs = $db->Execute('select * from ADOXYZ'); if (empty($rs->connection)) print "Connection object missing from recordset
    "; print_r($rs->fields); while ($o = $rs->FetchNextObject()) { // calls FetchObject internally @@ -728,6 +820,7 @@ END Adodb; print "

    CacheSelectLimit Test

    "; $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"); @@ -735,6 +828,7 @@ END Adodb; } 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(); @@ -805,9 +899,8 @@ END Adodb; if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong"); $db->debug = true; - print "

    SelectLimit Distinct Test 1: Should see Caroline, John and Mary

    "; - $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3); + echo "

    Date Update Test

    "; $zdate = date('Y-m-d',time()+3600*24); $zdate = $db->DBDate($zdate); @@ -815,18 +908,19 @@ END Adodb; $row = $db->GetRow("select created,firstname from ADOXYZ where id=1"); print_r($row); echo "
    "; - //$zdate = date('Y-m-d',time()+3600*24); - //$db->Execute("update ADOXYZ set created=? where id=2",$zdate); - //$zdate = $db->GetOne("select created from ADOXYZ where id=2"); - //echo "tomorrow=",$zdate,"
    "; - $db->debug=false; + + + print "

    SelectLimit Distinct Test 1: Should see Caroline, John and Mary

    "; + $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3); + if ($rs && !$rs->EOF) { - if (trim($rs->fields[1]) != 'Caroline') Err("Error 1"); + if (trim($rs->fields[1]) != 'Caroline') Err("Error 1 (exp Caroline), ".$rs->fields[1]); $rs->MoveNext(); - if (trim($rs->fields[1]) != 'John') Err("Error 2"); + + if (trim($rs->fields[1]) != 'John') Err("Error 2 (exp John), ".$rs->fields[1]); $rs->MoveNext(); - if (trim($rs->fields[1]) != 'Mary') Err("Error 3"); + if (trim($rs->fields[1]) != 'Mary') Err("Error 3 (exp Mary),".$rs->fields[1]); $rs->MoveNext(); if (! $rs->EOF) Err("Error EOF"); //rs2html($rs); @@ -835,16 +929,16 @@ END Adodb; print "

    SelectLimit Test 2: Should see Mary, George and Mr. Alan

    "; $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2); if ($rs && !$rs->EOF) { - if (trim($rs->fields[1]) != 'Mary') Err("Error 1"); + if (trim($rs->fields[1]) != 'Mary') Err("Error 1 - No Mary, instead: ".$rs->fields[1]); $rs->MoveNext(); - if (trim($rs->fields[1]) != 'George')Err("Error 2"); + if (trim($rs->fields[1]) != 'George')Err("Error 2 - No George, instead: ".$rs->fields[1]); $rs->MoveNext(); - if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3"); + if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3 - No Mr. Alan, instead: ".$rs->fields[1]); $rs->MoveNext(); if (! $rs->EOF) Err("Error EOF"); // rs2html($rs); } - else Err("Failed SelectLimit Test 2"); + else Err("Failed SelectLimit Test 2 ". ($rs ? 'EOF':'no RS')); print "

    SelectLimit Test 3: Should see Wai Hun and Steven

    "; $db->debug=1; @@ -931,7 +1025,7 @@ END Adodb; $rs = &$db->Execute($sql); } if ($rs) { - if (empty($HTTP_GET_VARS['hide'])) rs2html($rs); + if (empty($_GET['hide'])) rs2html($rs); } else { Err( "Failed Concat:".$sql); } @@ -991,12 +1085,19 @@ END Adodb; } // Comment this out to test countrecs = false $ADODB_COUNTRECS = $savecrecs; + $db->debug=1; + $query = $db->Prepare("select count(*) from ADOXYZ"); + $rs = $db->CacheExecute(10,$query); + if (reset($rs->fields) != 50) echo Err("$cnt wrong for Prepare/CacheGetOne"); for ($loop=0; $loop < 1; $loop++) { print "Testing GetMenu() and CacheExecute
    "; $db->debug = true; $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ"); + + + if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'
    '; else print " Fail
    "; $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ"); @@ -1016,17 +1117,33 @@ END Adodb; } else print " Fail
    "; print '


    '; + print "Testing GetMenu3()
    "; + $rs = $db->Execute("select ".$db->Concat('firstname',"'-'",'id').",id, lastname from ADOXYZ order by lastname,id"); + print "Grouped Menu: ".$rs->GetMenu3('name'); + print "
    "; + print "Testing GetMenu2()
    "; $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ"); if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'
    '; else print " Fail
    "; - $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ"); + $rs = &$db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ"); if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'
    '; else print " Fail
    "; } + echo "

    CacheEXecute

    "; + + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $rs = &$db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ"); + print_r($rs->fields); echo $rs->fetchMode;echo "
    "; + echo $rs->Fields('firstname'); + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $rs = &$db->CacheExecute(6,"select distinct firstname,lastname from ADOXYZ"); + print_r($rs->fields);echo "
    "; + echo $rs->Fields('firstname'); $db->debug = false; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; // phplens $sql = 'select * from ADOXYZ where 0=1'; @@ -1181,7 +1298,6 @@ END Adodb; } //print " CacheFlush "; //$db->CacheFlush(); - $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A'); $sql = "SELECT $date from ADOXYZ"; print "

    Test SQLDate: ".htmlspecialchars($sql)."

    "; @@ -1196,8 +1312,10 @@ END Adodb; $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:
    act:$d
    sql:".$rs->fields[0]); + if (!$rs) { + Err("SQLDate query returned no recordset"); + echo $db->ErrorMsg(),'
    '; + } else if ($d != $rs->fields[0]) Err("SQLDate 2 failed expected:
    act:$d
    sql:".$rs->fields[0]); print "

    Test Filter

    "; @@ -1255,13 +1373,13 @@ END Adodb; print "

    rs2rs Test

    "; - $rs = $db->Execute('select * from adoxyz order by id'); + $rs = $db->Execute('select * from adoxyz where id>= 1 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"); + if (reset($rs->fields) != 1) err("rs2rs does not move to first row: id=".reset($rs->fields)); ///////////////////////////////////////////////////////////// include_once('../pivottable.inc.php'); @@ -1282,12 +1400,14 @@ END Adodb; if ($rs) rs2html($rs); else Err("Pivot sql error"); + $pear = true; //true; $db->debug=false; - include_once "PEAR.php"; + if ($pear) { // PEAR TESTS BELOW $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $pear = true; + + include_once "PEAR.php"; $rs = $db->query('select * from adoxyz where id>0 and id<10 order by id'); $i = 0; @@ -1332,8 +1452,10 @@ END Adodb; print "

    PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)

    "; $pear = false; } - + } if ($pear) print "

    PEAR DB emulation passed.

    "; + flush(); + $rs = $db->SelectLimit("select ".$db->sysDate." from adoxyz",1); $date = $rs->fields[0]; @@ -1361,6 +1483,8 @@ END Adodb; if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2"); else echo "Passed UserTimeStamp 2: $ds

    "; } + flush(); + if ($db->hasTransactions) { //$db->debug=1; echo "

    Testing StartTrans CompleteTrans

    "; @@ -1394,7 +1518,7 @@ END Adodb; else echo "

    -- Passed StartTrans test2 - commiting

    "; } } - + flush(); $saved = $db->debug; $db->debug=1; $cnt = _adodb_getcount($db, 'select * from ADOXYZ where firstname in (select firstname from ADOXYZ)'); @@ -1423,10 +1547,11 @@ END Adodb; if ($debugerr) print " $rs=false"; $rs = false; + flush(); + print "

    SetFetchMode() tests

    "; $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; @@ -1439,20 +1564,29 @@ END Adodb; $rs = $db->SelectLimit('select firstname from adoxyz',1); if (!isset($rs->fields[0])) Err("BAD FETCH NUM"); + flush(); + print "

    Test MetaTables again with SetFetchMode()

    "; $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $db->SetFetchMode(ADODB_FETCH_ASSOC); print_r($db->MetaTables()); print "

    "; + //////////////////////////////////////////////////////////////////// - $conn = NewADOConnection($db->databaseType); - $conn->raiseErrorFn = 'adodb_test_err'; - @$conn->PConnect('abc'); - if ($TESTERRS == 2) print "raiseErrorFn tests passed
    "; - else print "raiseErrorFn tests failed ($TESTERRS)
    "; - + print "

    Testing Bad Connection

    "; + flush(); + if (true || PHP_VERSION < 5) { + if ($db->dataProvider == 'odbtp') $db->databaseType = 'odbtp'; + $conn = NewADOConnection($db->databaseType); + $conn->raiseErrorFn = 'adodb_test_err'; + if (1) $conn->PConnect('abc','baduser','badpassword'); + if ($TESTERRS == 2) print "raiseErrorFn tests passed
    "; + else print "raiseErrorFn tests failed ($TESTERRS)
    "; + + flush(); + } //////////////////////////////////////////////////////////////////// global $nocountrecs; @@ -1460,7 +1594,7 @@ END Adodb; if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set"); if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set"); - + flush(); ?>

     
    @@ -1476,6 +1610,7 @@ END Adodb; printf("

    Total queries=%d; total cached=%d

    ",$EXECS+$CACHED, $CACHED); + flush(); } function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false) @@ -1500,10 +1635,10 @@ include("../rsfilter.inc.php"); if (isset($_SERVER['argv'][1])) { //print_r($_SERVER['argv']); - $HTTP_GET_VARS[$_SERVER['argv'][1]] = 1; + $_GET[$_SERVER['argv'][1]] = 1; } -if (@$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') { +if (@$_SERVER['COMPUTERNAME'] == 'TIGRESS') { CheckWS('mysqlt'); CheckWS('postgres'); CheckWS('oci8po'); @@ -1528,10 +1663,10 @@ if (@$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') { CheckWS('fbsql'); print "White Space Check complete

    "; } -if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true; +if (sizeof($_GET) == 0) $testmysql = true; -foreach($HTTP_GET_VARS as $k=>$v) { +foreach($_GET as $k=>$v) { //global $$k; $$k = $v; } @@ -1561,8 +1696,9 @@ echo "
    vers=",ADOConnection::Version(); include_once('../adodb-time.inc.php'); -if (!isset($_GET['nd'])) adodb_date_test(); +if (isset($_GET['time'])) adodb_date_test(); + ?> -

    ADODB Database Library (c) 2000-2004 John Lim. All rights reserved. Released under BSD and LGPL.

    +

    ADODB Database Library (c) 2000-2005 John Lim. All rights reserved. Released under BSD and LGPL, PHP .

    diff --git a/phpgwapi/inc/adodb/tests/test2.php b/phpgwapi/inc/adodb/tests/test2.php index f23b4c906d..169aa0cc62 100644 --- a/phpgwapi/inc/adodb/tests/test2.php +++ b/phpgwapi/inc/adodb/tests/test2.php @@ -1,41 +1,26 @@ - - - - - Untitled - - - 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()."
    ";
    -//$rs->_array = false;
    -//$rs->connection = false;
    -//print_r($rs);
    -rs2html($rs);
    -?>
    -
    -
    -
    -
    +	$db = &ADONewConnection("ado_access");
    +	$db->debug=1;
    +	$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
    +	$myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
    +		. 'DATA SOURCE=' . $access . ';';
    +		
    +	echo "

    PHP ",PHP_VERSION,"

    "; + + $db->Connect($myDSN) || die('fail'); + + print_r($db->ServerInfo()); + + try { + $rs = $db->Execute("select $db->sysTimeStamp,* from adoxyz where id>02xx"); + print_r($rs->fields); + } catch(exception $e) { + print_r($e); + echo "

    Date m/d/Y =",$db->UserDate($rs->fields[4],'m/d/Y'); + } +?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/test3.php b/phpgwapi/inc/adodb/tests/test3.php index 42c91b27fd..099ec8767e 100644 --- a/phpgwapi/inc/adodb/tests/test3.php +++ b/phpgwapi/inc/adodb/tests/test3.php @@ -1,6 +1,6 @@ PConnect("", "sa", "natsoft", "northwind"); // connect to MySQL, testdb + $conn = &ADONewConnection("mysql"); // create a connection $conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb @@ -40,11 +44,20 @@ $conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $conn->debug=1; -$conn->Execute("delete from adoxyz where lastname like 'Smith%'"); +$conn->Execute("delete from adoxyz where lastname like 'Smi%'"); $rs = $conn->Execute($sql); // Execute the query and get the empty recordset $record = array(); // Initialize an array to hold the record data to insert +if (strpos($conn->databaseType,'mssql')!==false) $record['id'] = 751; +$record["firstname"] = 'Jann'; +$record["lastname"] = "Smitts"; +$record["created"] = time(); + +$insertSQL = $conn->GetInsertSQL($rs, $record); +$conn->Execute($insertSQL); // Insert the record into the database + +if (strpos($conn->databaseType,'mssql')!==false) $record['id'] = 752; // Set the values for the fields in the record $record["firstname"] = 'null'; $record["lastname"] = "Smith\$@//"; @@ -58,9 +71,10 @@ if (isset($_GET['f'])) $ADODB_FORCE_TYPE = $_GET['f']; // into the GetInsertSQL function. The function will process the data and return // a fully formatted insert sql statement. $insertSQL = $conn->GetInsertSQL($rs, $record); - $conn->Execute($insertSQL); // Insert the record into the database + + $insertSQL2 = $conn->GetInsertSQL($table='ADOXYZ', $record); if ($insertSQL != $insertSQL2) echo "

    Walt's new stuff failed: $insertSQL2

    "; //========================== @@ -68,18 +82,19 @@ if ($insertSQL != $insertSQL2) echo "

    Walt's new stuff failed: $insertS $sql = " SELECT * -FROM ADOXYZ WHERE lastname=".$conn->qstr($record['lastname']). " ORDER BY 1"; +FROM ADOXYZ WHERE lastname=".$conn->Param('var'). " ORDER BY 1"; // Select a record to update -$rs = $conn->Execute($sql); // Execute the query and get the existing record to update -if (!$rs) print "

    No record found!

    "; +$varr = array('var'=>$record['lastname'].''); +$rs = $conn->Execute($sql,$varr); // Execute the query and get the existing record to update +if (!$rs || $rs->EOF) print "

    No record found!

    "; $record = array(); // Initialize an array to hold the record data to update // Set the values for the fields in the record $record["firstName"] = "Caroline".rand(); -$record["lasTname"] = ""; // Update Caroline's lastname from Miranda to Smith +//$record["lasTname"] = ""; // Update Caroline's lastname from Miranda to Smith $record["creAted"] = '2002-12-'.(rand()%30+1); $record['num'] = ''; // Pass the single record recordset and the array containing the data to update @@ -88,19 +103,29 @@ $record['num'] = ''; // If the data has not changed, no recordset is returned $updateSQL = $conn->GetUpdateSQL($rs, $record); - -$conn->Execute($updateSQL); // Update the record in the database -if ($conn->Affected_Rows() != 1)print "

    Error: Rows Affected=".$conn->Affected_Rows().", should be 1

    "; +$conn->Execute($updateSQL,$varr); // Update the record in the database +if ($conn->Affected_Rows() != 1)print "

    Error1 : Rows Affected=".$conn->Affected_Rows().", should be 1

    "; $record["firstName"] = "Caroline".rand(); $record["lasTname"] = "Smithy Jones"; // Update Caroline's lastname from Miranda to Smith $record["creAted"] = '2002-12-'.(rand()%30+1); $record['num'] = 331; $updateSQL = $conn->GetUpdateSQL($rs, $record); -$conn->Execute($updateSQL); // Update the record in the database +$conn->Execute($updateSQL,$varr); // Update the record in the database +if ($conn->Affected_Rows() != 1)print "

    Error 2: Rows Affected=".$conn->Affected_Rows().", should be 1

    "; -$rs = $conn->Execute("select * from adoxyz where lastname like 'Smith%'"); -adodb_pr($rs); +$rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'"); +//adodb_pr($rs); +rs2html($rs); + +$record["firstName"] = "Carol-new-".rand(); +$record["lasTname"] = "Smithy"; // Update Caroline's lastname from Miranda to Smith +$record["creAted"] = '2002-12-'.(rand()%30+1); +$record['num'] = 331; + +$conn->AutoExecute('ADOXYZ',$record,'UPDATE', "lastname like 'Sm%'"); +$rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'"); +//adodb_pr($rs); rs2html($rs); } diff --git a/phpgwapi/inc/adodb/tests/test5.php b/phpgwapi/inc/adodb/tests/test5.php index f6b1319db5..8053a33c97 100644 --- a/phpgwapi/inc/adodb/tests/test5.php +++ b/phpgwapi/inc/adodb/tests/test5.php @@ -1,6 +1,6 @@ > MSSQL
    > MySQL
    > MySQL ODBC
    +> MySQLi +
    > SQLite
    > MySQL Proxy
    > Oracle (oci8)
    > PostgreSQL
    > PostgreSQL ODBC
    + +> PgSQL PDO
    +> MySQL PDO
    +> SQLite PDO
    +> Access PDO
    + +> OCI PDO
    + > DB2
    -> VFP
    +> VFP+ODBTP
    > ADO (for mssql and access)
    > $ADODB_COUNTRECS=false
    > No SQL Logging
    - - +> ADOdb time test + + + FETCH MODE IS NOT ADODB_FETCH_DEFAULT"; @@ -41,8 +53,8 @@ if (isset($nocountrecs)) $ADODB_COUNTRECS = false; if (!strpos(PHP_VERSION,'5') === 0) { ADOLoadCode("sybase"); - ADOLoadCode("postgres"); - ADOLoadCode("postgres7"); + //ADOLoadCode("postgres"); + //ADOLoadCode("postgres7"); ADOLoadCode("firebird"); ADOLoadCode("borland_ibase"); ADOLoadCode("informix"); @@ -80,7 +92,7 @@ if (!empty($testibase)) { //$_GET['nolog'] = true; $db = &ADONewConnection('firebird'); print "

    Connecting $db->databaseType...

    "; - if ($db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", "")) + if ($db->PConnect("localhost:d:\\firebird\\151\\examples\\EMPLOYEE.fdb", "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".'
    '.$db->ErrorMsg(); @@ -88,15 +100,75 @@ if (!empty($testibase)) { if (!empty($testsqlite)) { - $db = &ADONewConnection('sqlite'); + $path =urlencode('d:\inetpub\adodb\sqlite.db'); + $dsn = "sqlite://$path/"; + $db = ADONewConnection($dsn); + echo $dsn; + +// $db = &ADONewConnection('sqlite'); print "

    Connecting $db->databaseType...

    "; - if ($db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", "")) + if (1) + //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"; } +if (!empty($testpdopgsql)) { + $connstr = "pgsql:dbname=test"; + $u = 'tester';$p='test'; + $db = &ADONewConnection('pdo'); + print "

    Connecting $db->databaseType...

    "; + $db->Connect($connstr,$u,$p) || die("CONNECT FAILED"); + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); +} + +if (!empty($testpdomysql)) { + $connstr = "mysql:dbname=northwind"; + $u = 'root';$p=''; + $db = &ADONewConnection('pdo'); + print "

    Connecting $db->databaseType...

    "; + $db->Connect($connstr,$u,$p) || die("CONNECT FAILED"); + + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); +} + +if (!empty($testpdosqlite)) { + $connstr = "sqlite:d:/inetpub/adodb/sqlite-pdo.db3"; + $u = '';$p=''; + $db = &ADONewConnection('pdo'); + $db->hasTransactions = false; + print "

    Connecting $db->databaseType...

    "; + $db->Connect($connstr,$u,$p) || die("CONNECT FAILED"); + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); +} + +if (!empty($testpdoaccess)) { + $connstr = 'odbc:nwind'; + $u = '';$p=''; + $db = &ADONewConnection('pdo'); + $db->hasTransactions = false; + print "

    Connecting $db->databaseType...

    "; + $db->Connect($connstr,$u,$p) || die("CONNECT FAILED"); + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); +} + +if (!empty($testpdoora)) { + $connstr = 'oci:'; + $u = 'scott';$p='natsoft'; + $db = &ADONewConnection('pdo'); + #$db->hasTransactions = false; + print "

    Connecting $db->databaseType...

    "; + $db->Connect($connstr,$u,$p) || die("CONNECT FAILED"); + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); +} + // REQUIRES ODBC DSN CALLED nwind if (!empty($testaccess)) { $db = &ADONewConnection('access'); @@ -121,7 +193,7 @@ if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS $myDSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;' . 'DATA SOURCE=' . $access . ';'; //. 'USER ID=;PASSWORD=;'; - + $_GET['nolog'] = 1; if ($db->PConnect($myDSN, "", "", "")) { print "ADO version=".$db->_connectionID->version."
    "; testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); @@ -137,6 +209,14 @@ if (!empty($testvfp)) { // ODBC 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"; + echo "
    "; + $db = &ADONewConnection('odbtp'); + + if ( $db->PConnect('localhost','DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=d:\inetpub\adodb;EXCLUSIVE=NO;')) { + print "

    Connecting $db->databaseType...

    ";flush(); + testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)"); + } else print "ERROR: Visual FoxPro odbtp requires a Windows ODBC DSN=vfp-adoxyz, VFP driver"; + } @@ -144,16 +224,17 @@ if (!empty($testvfp)) { // ODBC if (!empty($testmysql)) { // MYSQL - if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + if (PHP_VERSION >= 5 || $_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost'; else $server = "mangrove"; $user = 'root'; $password = ''; $database = 'northwind'; - $db = &ADONewConnection("mysql://$user:$password@$server/$database?persist"); + $db = &ADONewConnection("mysqlt://$user:$password@$server/$database?persist"); print "

    Connecting $db->databaseType...

    "; if (true || $db->PConnect($server, "root", "", "northwind")) { + //$db->Execute("DROP TABLE ADOXYZ") || die('fail drop'); //$db->debug=1;$db->Execute('drop table ADOXYZ'); testdb($db, - "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); + "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'".'
    '.$db->ErrorMsg(); } @@ -162,7 +243,7 @@ if (!empty($testmysqli)) { // MYSQL $db = &ADONewConnection('mysqli'); print "

    Connecting $db->databaseType...

    "; - if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + if (PHP_VERSION >= 5 || $_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost'; else $server = "mangrove"; if ($db->PConnect($server, "root", "", "northwind")) { //$db->debug=1;$db->Execute('drop table ADOXYZ'); @@ -178,7 +259,7 @@ if (!empty($testmysqlodbc)) { // MYSQL $db = &ADONewConnection('odbc'); $db->hasTransactions = false; print "

    Connecting $db->databaseType...

    "; - if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + if ($_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost'; else $server = "mangrove"; if ($db->PConnect('mysql', "root", "")) testdb($db, @@ -189,7 +270,7 @@ if (!empty($testmysqlodbc)) { // MYSQL if (!empty($testproxy)){ $db = &ADONewConnection('proxy'); print "

    Connecting $db->databaseType...

    "; - if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + if ($_SERVER['HTTP_HOST'] == 'localhost') $server = 'localhost'; if ($db->PConnect('http://localhost/php/phplens/adodb/server.php')) testdb($db, @@ -201,7 +282,7 @@ if (!empty($testproxy)){ ADOLoadCode('oci805'); ADOLoadCode("oci8po"); if (!empty($testoracle)) { - $dsn = "oci8po://scott:natsoft@panther?persist"; + $dsn = "oci8po://juris10:natsoft@sherkhan?persist"; $db = ADONewConnection($dsn); print "

    Connecting $db->databaseType...

    "; if (true || $db->Connect('', "scott", "natsoft",'')) @@ -222,23 +303,41 @@ if (false && !empty($testoracle)) { ADOLoadCode("db2"); // no longer supported if (!empty($testdb2)) { - $db = ADONewConnection(); print "

    Connecting $db->databaseType...

    "; - 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".'
    '.$db->ErrorMsg(); + + $dsn = "db2_sample"; + $dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP; uid=root; pwd=natsoft"; + if ($db->Connect($dsn)) { + // 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".'
    '.$db->ErrorMsg(); +echo "
    "; +flush(); + $dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP; uid=root; pwd=natsoft"; + + $db = ADONewConnection('odbtp'); + if ($db->Connect('127.0.0.1',$dsn)) { + + $db->debug=1; + $arr = $db->GetArray( "||SQLProcedures" ); adodb_pr($arr); + $arr = $db->GetArray( "||SQLProcedureColumns|||GET_ROUTINE_SAR" );adodb_pr($arr); + + testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)"); + } else echo ("ERROR Connection"); + echo $db->ErrorMsg(); } +$server = 'sherkhan'; + ADOLoadCode('odbc_mssql'); if (!empty($testmssql)) { // MS SQL Server via ODBC $db = ADONewConnection(); print "

    Connecting $db->databaseType...

    "; - $dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=localhost;Database=northwind;"; + $dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=$server;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)"); @@ -248,7 +347,6 @@ if (!empty($testmssql)) { // MS SQL Server via ODBC } ADOLoadCode("ado_mssql"); - if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less $db = &ADONewConnection("ado_mssql"); @@ -256,7 +354,7 @@ if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC print "

    Connecting DSN-less $db->databaseType...

    "; $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};" - . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No" ; + . "SERVER=$server;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No"; if ($db->PConnect($myDSN, "", "", "")) @@ -272,13 +370,13 @@ if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably //$db->debug=1; print "

    Connecting $db->databaseType...

    "; - $ok = $db->PConnect('tigress','adodb','natsoft','northwind'); + $ok = $db->Connect('','adodb','natsoft','northwind'); 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'".'
    '.$db->ErrorMsg(); + } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='adodb', password='natsoft', database='ai'".'
    '.$db->ErrorMsg(); } @@ -287,10 +385,24 @@ if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB pro $db = &ADONewConnection("ado_mssql"); print "

    Connecting DSN-less OLEDB Provider $db->databaseType...

    "; //$db->debug=1; - $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes"; - if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB')) + $myDSN="SERVER=localhost;DATABASE=northwind;Trusted_Connection=yes"; + 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'"; + } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'"; + +} + + +if (extension_loaded('odbtp') && !empty($testmssql)) { // MS SQL Server via ODBC + $db = ADONewConnection('odbtp'); + + $dsn = "PROVIDER=MSDASQL;Driver={SQL Server};Server=$server;Database=northwind;uid=adodb;pwd=natsoft"; + + if ($db->PConnect('localhost',$dsn, "", "")) { + print "

    Connecting $db->databaseType...

    "; + 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"; } diff --git a/phpgwapi/inc/adodb/tests/testmssql.php b/phpgwapi/inc/adodb/tests/testmssql.php index 77febcef33..69647f4b11 100644 --- a/phpgwapi/inc/adodb/tests/testmssql.php +++ b/phpgwapi/inc/adodb/tests/testmssql.php @@ -1,7 +1,7 @@ Connect('localhost','sa','natsoft','northwind') or die('Fail'); +$conn->Connect('127.0.0.1','adodb','natsoft','northwind') or die('Fail'); $conn->debug =1; $query = 'select * from products'; diff --git a/phpgwapi/inc/adodb/tests/testoci8.php b/phpgwapi/inc/adodb/tests/testoci8.php index 59823e25ea..1c8bf28309 100644 --- a/phpgwapi/inc/adodb/tests/testoci8.php +++ b/phpgwapi/inc/adodb/tests/testoci8.php @@ -2,7 +2,7 @@ Connect('','scott','natsoft'); + +$sql = "select * from (select ID, firstname as \"First Name\", lastname as \"Last Name\" from adoxyz + order by (1))"; } if ($driver == 'access') { @@ -52,7 +55,7 @@ if ($driver == 'access') { if (empty($driver) or $driver == 'mysql') { $db = NewADOConnection('mysql'); - $db->Connect('localhost','root','','xphplens'); + $db->Connect('localhost','root','','test'); } //$db->pageExecuteCountRows = false; @@ -77,7 +80,7 @@ print "
    "; $pager = new ADODB_Pager($db,$sql); $pager->showPageLinks = true; -$pager->linksPerPage = 3; +$pager->linksPerPage = 10; $pager->cache = 60; $pager->Render($rows=7); ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/testpear.php b/phpgwapi/inc/adodb/tests/testpear.php index ad4b0b46d6..05eca9c0fa 100644 --- a/phpgwapi/inc/adodb/tests/testpear.php +++ b/phpgwapi/inc/adodb/tests/testpear.php @@ -1,6 +1,6 @@ PHP ".PHP_VERSION.""; - print "

    \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}

    "; + print "

    \$_SESSION['AVAR']={$_SESSION['AVAR']}

    "; print "
    Cookies: "; - print_r($HTTP_COOKIE_VARS); + print_r($_COOKIE); ### RANDOMLY PERFORM Garbage Collection - if (rand() % 10 == 0) { +### In real-production environment, this is done for you +### by php's session extension, which calls adodb_sess_gc() +### automatically for you. See php.ini's +### session.cookie_lifetime and session.gc_probability + + if (rand() % 5 == 0) { print "

    Garbage Collection

    "; adodb_sess_gc(10); - print "

    Random session destroy

    "; - session_destroy(); + if (rand() % 2 == 0) { + print "

    Random session destroy

    "; + session_destroy(); + } } ?> \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/xmlschema-mssql.xml b/phpgwapi/inc/adodb/tests/xmlschema-mssql.xml new file mode 100644 index 0000000000..2877bfc85b --- /dev/null +++ b/phpgwapi/inc/adodb/tests/xmlschema-mssql.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + +id + + +id + + + +
    + + SQL to be executed only on specific platforms + + insert into mytable ( row1, row2 ) values ( 12, 'postgres stuff' ) + + + insert into mytable ( row1, row2 ) values ( 12, 'mysql stuff' ) + + + INSERT into simple_table ( name, description ) values ( '12', 'Microsoft stuff' ) + + +
    \ No newline at end of file diff --git a/phpgwapi/inc/adodb/tests/xmlschema.xml b/phpgwapi/inc/adodb/tests/xmlschema.xml index 6fc9ab798a..183171a414 100644 --- a/phpgwapi/inc/adodb/tests/xmlschema.xml +++ b/phpgwapi/inc/adodb/tests/xmlschema.xml @@ -22,6 +22,9 @@ insert into mytable ( row1, row2 ) values ( 12, 'mysql stuff' ) + + + insert into mytable ( row1, row2 ) values ( 12, 'Microsoft stuff' ) diff --git a/phpgwapi/inc/adodb/toexport.inc.php b/phpgwapi/inc/adodb/toexport.inc.php index a99df49bca..cc20669a11 100644 --- a/phpgwapi/inc/adodb/toexport.inc.php +++ b/phpgwapi/inc/adodb/toexport.inc.php @@ -1,7 +1,7 @@ name; if ($escquote) $v = str_replace($quote,$escquotequote,$v); - $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); $elements[] = $v; } @@ -94,9 +94,11 @@ function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = if ($hasNumIndex) { for ($j=0; $j < $max; $j++) { - $v = trim($rs->fields[$j]); + $v = $rs->fields[$j]; + if (!is_object($v)) $v = trim($v); + else $v = 'Object'; if ($escquote) $v = str_replace($quote,$escquotequote,$v); - $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; else $elements[] = $v; @@ -104,7 +106,7 @@ function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = } 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))); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; else $elements[] = $v; diff --git a/phpgwapi/inc/adodb/tohtml.inc.php b/phpgwapi/inc/adodb/tohtml.inc.php index 86bfca0732..f4fe40800b 100644 --- a/phpgwapi/inc/adodb/tohtml.inc.php +++ b/phpgwapi/inc/adodb/tohtml.inc.php @@ -1,6 +1,6 @@ Close(); // // RETURNS: number of rows displayed + + function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true,$echo = true) { $s ='';$rows=0;$docnt = false; -GLOBAL $gSQLMaxRows,$gSQLBlockRows; +GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND; if (!$rs) { printf(ADODB_BAD_RS,'rs2html'); @@ -52,11 +55,15 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows; $hdr = "
    \n\n"; for ($i=0; $i < $ncols; $i++) { $field = $rs->FetchField($i); - if ($zheaderarray) $fname = $zheaderarray[$i]; - else $fname = htmlspecialchars($field->name); - $typearr[$i] = $rs->MetaType($field->type,$field->max_length); - //print " $field->name $field->type $typearr[$i] "; - + if ($field) { + if ($zheaderarray) $fname = $zheaderarray[$i]; + else $fname = htmlspecialchars($field->name); + $typearr[$i] = $rs->MetaType($field->type,$field->max_length); + //print " $field->name $field->type $typearr[$i] "; + } else { + $fname = 'Field '.($i+1); + $typearr[$i] = 'C'; + } if (strlen($fname)==0) $fname = ' '; $hdr .= ""; } @@ -77,15 +84,22 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows; $type = $typearr[$i]; switch($type) { case 'D': - if (!strpos($v,':')) { + if (empty($v)) $s .= "\n"; + else if (!strpos($v,':')) { $s .= " \n"; - break; } + break; case 'T': - $s .= " \n"; + if (empty($v)) $s .= "\n"; + else $s .= " \n"; break; - case 'I': + case 'N': + if (abs($v) - round($v,0) < 0.00000001) + $v = round($v); + else + $v = round($v,$ADODB_ROUND); + case 'I': $s .= " \n"; break; @@ -178,4 +192,4 @@ function arr2html(&$arr,$ztabhtml='',$zheaderarray='') print $s; } -?> +?> \ No newline at end of file
    $fname   ".$rs->UserDate($v,"D d, M Y") ." ".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."    ".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ." ".stripslashes((trim($v))) ."