From: moodler \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']} Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().' \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']} \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']} Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().' $msg \$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}Session Error: PHP.INI setting session.gc_maxlifetimenot set: $ADODB_SESS_LIFE
"; */
- $ADODB_SESS_LIFE=1440;
-}
-
-function adodb_sess_open($save_path, $session_name)
-{
-GLOBAL $ADODB_SESSION_CONNECT,
- $ADODB_SESSION_DRIVER,
- $ADODB_SESSION_USER,
- $ADODB_SESSION_PWD,
- $ADODB_SESSION_DB,
- $ADODB_SESS_CONN,
- $ADODB_SESS_DEBUG;
-
- $ADODB_SESS_INSERT = false;
-
- if (isset($ADODB_SESS_CONN)) return true;
-
- $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
- if (!empty($ADODB_SESS_DEBUG)) {
- $ADODB_SESS_CONN->debug = true;
- print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";
- }
- return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
- $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
-
-}
-
-function adodb_sess_close()
-{
-global $ADODB_SESS_CONN;
-
- if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
- return true;
-}
-
-function adodb_sess_read($key)
-{
-$Crypt = new MD5Crypt;
-global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;
- $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
- if ($rs) {
- if ($rs->EOF) {
- $ADODB_SESS_INSERT = true;
- $v = '';
- } else {
- /* Decrypt session data */
- $v = rawurldecode($Crypt->Decrypt(reset($rs->fields), ADODB_Session_Key()));
- }
- $rs->Close();
- return $v;
- }
- else $ADODB_SESS_INSERT = true;
-
- return '';
-}
-
-function adodb_sess_write($key, $val)
-{
-$Crypt = new MD5Crypt;
- global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
-
- $expiry = time() + $ADODB_SESS_LIFE;
-
- /* encrypt session data.. */
- $val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());
-
- $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
- if ($ADODB_SESSION_EXPIRE_NOTIFY) {
- $var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
- global $$var;
- $arr['expireref'] = $$var;
- }
- $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,
- $arr,
- 'sesskey',$autoQuote = true);
-
- if (!$rs) {
- ADOConnection::outp( 'Session Error: PHP.INI setting session.gc_maxlifetimenot set: $ADODB_SESS_LIFE
";
+ $ADODB_SESS_LIFE=1440;
+}
+
+function adodb_sess_open($save_path, $session_name)
+{
+GLOBAL $ADODB_SESSION_CONNECT,
+ $ADODB_SESSION_DRIVER,
+ $ADODB_SESSION_USER,
+ $ADODB_SESSION_PWD,
+ $ADODB_SESSION_DB,
+ $ADODB_SESS_CONN,
+ $ADODB_SESS_DEBUG;
+
+ $ADODB_SESS_INSERT = false;
+
+ if (isset($ADODB_SESS_CONN)) return true;
+
+ $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
+ if (!empty($ADODB_SESS_DEBUG)) {
+ $ADODB_SESS_CONN->debug = true;
+ print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";
+ }
+ return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
+ $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
+
+}
+
+function adodb_sess_close()
+{
+global $ADODB_SESS_CONN;
+
+ if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
+ return true;
+}
+
+function adodb_sess_read($key)
+{
+$Crypt = new MD5Crypt;
+global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;
+ $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
+ if ($rs) {
+ if ($rs->EOF) {
+ $ADODB_SESS_INSERT = true;
+ $v = '';
+ } else {
+ // Decrypt session data
+ $v = rawurldecode($Crypt->Decrypt(reset($rs->fields), ADODB_Session_Key()));
+ }
+ $rs->Close();
+ return $v;
+ }
+ else $ADODB_SESS_INSERT = true;
+
+ return '';
+}
+
+function adodb_sess_write($key, $val)
+{
+$Crypt = new MD5Crypt;
+ global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
+
+ $expiry = time() + $ADODB_SESS_LIFE;
+
+ // encrypt session data..
+ $val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());
+
+ $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
+ if ($ADODB_SESSION_EXPIRE_NOTIFY) {
+ $var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
+ global $$var;
+ $arr['expireref'] = $$var;
+ }
+ $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,
+ $arr,
+ 'sesskey',$autoQuote = true);
+
+ if (!$rs) {
+ ADOConnection::outp( '
"; -print_r($a); -print ""; -} -/* Lens_ParseTest(); */ - -/** - Parse arguments, treat "text" (text) and 'text' as quotation marks. - To escape, use "" or '' or )) - - @param endstmtchar Character that indicates end of statement - @param tokenchars Include the following characters in tokens apart from A-Z and 0-9 - @returns 2 dimensional array containing parsed tokens. -*/ -function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-') -{ - $pos = 0; - $intoken = false; - $stmtno = 0; - $endquote = false; - $tokens = array(); - $tokens[$stmtno] = array(); - $max = strlen($args); - $quoted = false; - - while ($pos < $max) { - $ch = substr($args,$pos,1); - switch($ch) { - case ' ': - case "\t": - case "\n": - case "\r": - if (!$quoted) { - if ($intoken) { - $intoken = false; - $tokens[$stmtno][] = implode('',$tokarr); - } - break; - } - - $tokarr[] = $ch; - break; - - case '(': - case ')': - case '"': - case "'": - - if ($intoken) { - if (empty($endquote)) { - $tokens[$stmtno][] = implode('',$tokarr); - if ($ch == '(') $endquote = ')'; - else $endquote = $ch; - $quoted = true; - $intoken = true; - $tokarr = array(); - } else if ($endquote == $ch) { - $ch2 = substr($args,$pos+1,1); - if ($ch2 == $endquote) { - $pos += 1; - $tokarr[] = $ch2; - } else { - $quoted = false; - $intoken = false; - $tokens[$stmtno][] = implode('',$tokarr); - $endquote = ''; - } - } else - $tokarr[] = $ch; - - }else { - - if ($ch == '(') $endquote = ')'; - else $endquote = $ch; - $quoted = true; - $intoken = true; - $tokarr = array(); - } - break; - - default: - - if (!$intoken) { - if ($ch == $endstmtchar) { - $stmtno += 1; - $tokens[$stmtno] = array(); - break; - } - - $intoken = true; - $quoted = false; - $endquote = false; - $tokarr = array(); - - } - - if ($quoted) $tokarr[] = $ch; - else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch; - else { - if ($ch == $endstmtchar) { - $tokens[$stmtno][] = implode('',$tokarr); - $stmtno += 1; - $tokens[$stmtno] = array(); - $intoken = false; - $tokarr = array(); - break; - } - $tokens[$stmtno][] = implode('',$tokarr); - $tokens[$stmtno][] = $ch; - $intoken = false; - } - } - $pos += 1; - } - - return $tokens; -} - - -class ADODB_DataDict { - var $connection; - var $debug = false; - var $dropTable = "DROP TABLE %s"; - var $addCol = ' ADD'; - var $alterCol = ' ALTER COLUMN'; - var $dropCol = ' DROP COLUMN'; - var $schema = false; - var $serverInfo = array(); - var $autoIncrement = false; - var $dataProvider; - var $blobSize = 100; /* / any varchar/char field this size or greater is treated as a blob */ - /* / in other words, we use a text area for editting. */ - - function GetCommentSQL($table,$col) - { - return false; - } - - function SetCommentSQL($table,$col,$cmt) - { - return false; - } - - function &MetaTables() - { - return $this->connection->MetaTables(); - } - - function &MetaColumns($tab) - { - return $this->connection->MetaColumns($tab); - } - - function &MetaPrimaryKeys($tab,$owner=false,$intkey=false) - { - return $this->connection->MetaPrimaryKeys($tab.$owner,$intkey); - } - - function MetaType($t,$len=-1,$fieldobj=false) - { - return ADORecordSet::MetaType($t,$len,$fieldobj); - } - - /* Executes the sql array returned by GetTableSQL and GetIndexSQL */ - function ExecuteSQLArray($sql, $continueOnError = true) - { - $rez = 2; - $conn = &$this->connection; - $saved = $conn->debug; - foreach($sql as $line) { - - if ($this->debug) $conn->debug = true; - $ok = $conn->Execute($line); - $conn->debug = $saved; - if (!$ok) { - if ($this->debug) ADOConnection::outp($conn->ErrorMsg()); - if (!$continueOnError) return 0; - $rez = 1; - } - } - return 2; - } - - /* - Returns the actual type given a character code. - - C: varchar - X: CLOB (character large object) or largest varchar size if CLOB is not supported - C2: Multibyte varchar - X2: Multibyte CLOB - - B: BLOB (binary large object) - - D: Date - T: Date-time - L: Integer field suitable for storing booleans (0 or 1) - I: Integer - F: Floating point number - N: Numeric or decimal number - */ - - function ActualType($meta) - { - return $meta; - } - - function CreateDatabase($dbname,$options=false) - { - $options = $this->_Options($options); - $s = 'CREATE DATABASE '.$dbname; - if (isset($options[$this->upperName])) $s .= ' '.$options[$this->upperName]; - $sql[] = $s; - return $sql; - } - - /* - Generates the SQL to create index. Returns an array of sql strings. - */ - function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false) - { - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - return $this->_IndexSQL($idxname, $tabname, $flds, $this->_Options($idxoptions)); - } - - function SetSchema($schema) - { - $this->schema = $schema; - } - - function AddColumnSQL($tabname, $flds) - { - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - $sql = array(); - list($lines,$pkey) = $this->_GenFields($flds); - foreach($lines as $v) { - $sql[] = "ALTER TABLE $tabname $this->addCol $v"; - } - return $sql; - } - - function AlterColumnSQL($tabname, $flds) - { - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - $sql = array(); - list($lines,$pkey) = $this->_GenFields($flds); - - foreach($lines as $v) { - $sql[] = "ALTER TABLE $tabname $this->alterCol $v"; - } - return $sql; - } - - function DropColumnSQL($tabname, $flds) - { - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - if (!is_array($flds)) $flds = explode(',',$flds); - $sql = array(); - foreach($flds as $v) { - $sql[] = "ALTER TABLE $tabname $this->dropCol $v"; - } - return $sql; - } - - function DropTableSQL($tabname) - { - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - $sql[] = sprintf($this->dropTable,$tabname); - return $sql; - } - - /* - Generate the SQL to create table. Returns an array of sql strings. - */ - function CreateTableSQL($tabname, $flds, $tableoptions=false) - { - if (!$tableoptions) $tableoptions = array(); - - list($lines,$pkey) = $this->_GenFields($flds); - - $taboptions = $this->_Options($tableoptions); - if ($this->schema) $tabname = $this->schema.'.'.$tabname; - $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions); - - $tsql = $this->_Triggers($tabname,$taboptions); - foreach($tsql as $s) $sql[] = $s; - - return $sql; - } - - function _GenFields($flds) - { - if (is_string($flds)) { - $padding = ' '; - $txt = $flds.$padding; - $flds = array(); - $flds0 = Lens_ParseArgs($txt,','); - $hasparam = false; - foreach($flds0 as $f0) { - $f1 = array(); - foreach($f0 as $token) { - switch (strtoupper($token)) { - case 'CONSTRAINT': - case 'DEFAULT': - $hasparam = $token; - break; - default: - if ($hasparam) $f1[$hasparam] = $token; - else $f1[] = $token; - $hasparam = false; - break; - } - } - $flds[] = $f1; - - } - } - $this->autoIncrement = false; - $lines = array(); - $pkey = array(); - foreach($flds as $fld) { - $fld = _array_change_key_case($fld); - - $fname = false; - $fdefault = false; - $fautoinc = false; - $ftype = false; - $fsize = false; - $fprec = false; - $fprimary = false; - $fnoquote = false; - $fdefts = false; - $fdefdate = false; - $fconstraint = false; - $fnotnull = false; - $funsigned = false; - - /* ----------------- */ - /* Parse attributes */ - foreach($fld as $attr => $v) { - if ($attr == 2 && is_numeric($v)) $attr = 'SIZE'; - else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v); - - switch($attr) { - case '0': - case 'NAME': $fname = $v; break; - case '1': - case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break; - case 'SIZE': $dotat = strpos($v,'.'); - if ($dotat === false) $fsize = $v; - else { - $fsize = substr($v,0,$dotat); - $fprec = substr($v,$dotat+1); - } - break; - case 'UNSIGNED': $funsigned = true; break; - case 'AUTOINCREMENT': - case 'AUTO': $fautoinc = true; $fnotnull = true; break; - case 'KEY': - case 'PRIMARY': $fprimary = $v; $fnotnull = true; break; - case 'DEF': - case 'DEFAULT': $fdefault = $v; break; - case 'NOTNULL': $fnotnull = $v; break; - case 'NOQUOTE': $fnoquote = $v; break; - case 'DEFDATE': $fdefdate = $v; break; - case 'DEFTIMESTAMP': $fdefts = $v; break; - case 'CONSTRAINT': $fconstraint = $v; break; - } /* switch */ - } /* foreach $fld */ - - /* -------------------- */ - /* VALIDATE FIELD INFO */ - if (!strlen($fname)) { - if ($this->debug) ADOConnection::outp("Undefined NAME"); - return false; - } - - if (!strlen($ftype)) { - if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'"); - return false; - } else { - $ftype = strtoupper($ftype); - } - - $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec); - - if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; /* some blob types do not accept nulls */ - - if ($fprimary) $pkey[] = $fname; - - /* some databases do not allow blobs to have defaults */ - if ($ty == 'X') $fdefault = false; - - /* -------------------- */ - /* CONSTRUCT FIELD SQL */ - if ($fdefts) { - if (substr($this->connection->databaseType,0,5) == 'mysql') { - $ftype = 'TIMESTAMP'; - } else { - $fdefault = $this->connection->sysTimeStamp; - } - } else if ($fdefdate) { - if (substr($this->connection->databaseType,0,5) == 'mysql') { - $ftype = 'TIMESTAMP'; - } else { - $fdefault = $this->connection->sysDate; - } - } else if (strlen($fdefault) && !$fnoquote) - if ($ty == 'C' or $ty == 'X' or - ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) - if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') - $fdefault = trim($fdefault); - else if (strtolower($fdefault) != 'null') - $fdefault = $this->connection->qstr($fdefault); - $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned); - - $fname = str_pad($fname,16); - $lines[] = "$fname $ftype$suffix"; - - if ($fautoinc) $this->autoIncrement = true; - } /* foreach $flds */ - - - return array($lines,$pkey); - } - /* - GENERATE THE SIZE PART OF THE DATATYPE - $ftype is the actual type - $ty is the type defined originally in the DDL - */ - function _GetSize($ftype, $ty, $fsize, $fprec) - { - if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) { - $ftype .= "(".$fsize; - if ($fprec) $ftype .= ",".$fprec; - $ftype .= ')'; - } - return $ftype; - } - - - /* return string must begin with space */ - function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint) - { - $suffix = ''; - if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault"; - if ($fnotnull) $suffix .= ' NOT NULL'; - if ($fconstraint) $suffix .= ' '.$fconstraint; - return $suffix; - } - - function _IndexSQL($idxname, $tabname, $flds, $idxoptions) - { - if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname"; - if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE'; - else $unique = ''; - - if (is_array($flds)) $flds = implode(', ',$flds); - $s = "CREATE$unique INDEX $idxname ON $tabname "; - if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName]; - $s .= "($flds)"; - $sql[] = $s; - - return $sql; - } - - function _DropAutoIncrement($tabname) - { - return false; - } - - function _TableSQL($tabname,$lines,$pkey,$tableoptions) - { - $sql = array(); - - if (isset($tableoptions['REPLACE'])) { - $sql[] = sprintf($this->dropTable,$tabname); - if ($this->autoIncrement) { - $sInc = $this->_DropAutoIncrement($tabname); - if ($sInc) $sql[] = $sInc; - } - } - $s = "CREATE TABLE $tabname (\n"; - $s .= implode(",\n", $lines); - if (sizeof($pkey)>0) { - $s .= ",\n PRIMARY KEY ("; - $s .= implode(", ",$pkey).")"; - } - if (isset($tableoptions['CONSTRAINTS'])) - $s .= "\n".$tableoptions['CONSTRAINTS']; - - if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) - $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS']; - - $s .= "\n)"; - if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName]; - $sql[] = $s; - - return $sql; - } - - /* - GENERATE TRIGGERS IF NEEDED - used when table has auto-incrementing field that is emulated using triggers - */ - function _Triggers($tabname,$taboptions) - { - return array(); - } - - /* - Sanitize options, so that array elements with no keys are promoted to keys - */ - function _Options($opts) - { - if (!is_array($opts)) return array(); - $newopts = array(); - foreach($opts as $k => $v) { - if (is_numeric($k)) $newopts[strtoupper($v)] = $v; - else $newopts[strtoupper($k)] = $v; - } - return $newopts; - } - - -/* -"Florian Buzin [ easywe ]"
"; +print_r($a); +print ""; +} +//Lens_ParseTest(); + +/** + Parse arguments, treat "text" (text) and 'text' as quotation marks. + To escape, use "" or '' or )) + + @param endstmtchar Character that indicates end of statement + @param tokenchars Include the following characters in tokens apart from A-Z and 0-9 + @returns 2 dimensional array containing parsed tokens. +*/ +function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-') +{ + $pos = 0; + $intoken = false; + $stmtno = 0; + $endquote = false; + $tokens = array(); + $tokens[$stmtno] = array(); + $max = strlen($args); + $quoted = false; + + while ($pos < $max) { + $ch = substr($args,$pos,1); + switch($ch) { + case ' ': + case "\t": + case "\n": + case "\r": + if (!$quoted) { + if ($intoken) { + $intoken = false; + $tokens[$stmtno][] = implode('',$tokarr); + } + break; + } + + $tokarr[] = $ch; + break; + + case '(': + case ')': + case '"': + case "'": + + if ($intoken) { + if (empty($endquote)) { + $tokens[$stmtno][] = implode('',$tokarr); + if ($ch == '(') $endquote = ')'; + else $endquote = $ch; + $quoted = true; + $intoken = true; + $tokarr = array(); + } else if ($endquote == $ch) { + $ch2 = substr($args,$pos+1,1); + if ($ch2 == $endquote) { + $pos += 1; + $tokarr[] = $ch2; + } else { + $quoted = false; + $intoken = false; + $tokens[$stmtno][] = implode('',$tokarr); + $endquote = ''; + } + } else + $tokarr[] = $ch; + + }else { + + if ($ch == '(') $endquote = ')'; + else $endquote = $ch; + $quoted = true; + $intoken = true; + $tokarr = array(); + } + break; + + default: + + if (!$intoken) { + if ($ch == $endstmtchar) { + $stmtno += 1; + $tokens[$stmtno] = array(); + break; + } + + $intoken = true; + $quoted = false; + $endquote = false; + $tokarr = array(); + + } + + if ($quoted) $tokarr[] = $ch; + else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch; + else { + if ($ch == $endstmtchar) { + $tokens[$stmtno][] = implode('',$tokarr); + $stmtno += 1; + $tokens[$stmtno] = array(); + $intoken = false; + $tokarr = array(); + break; + } + $tokens[$stmtno][] = implode('',$tokarr); + $tokens[$stmtno][] = $ch; + $intoken = false; + } + } + $pos += 1; + } + + return $tokens; +} + + +class ADODB_DataDict { + var $connection; + var $debug = false; + var $dropTable = "DROP TABLE %s"; + var $addCol = ' ADD'; + var $alterCol = ' ALTER COLUMN'; + var $dropCol = ' DROP COLUMN'; + var $schema = false; + var $serverInfo = array(); + var $autoIncrement = false; + var $quote = ''; + var $dataProvider; + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + /// in other words, we use a text area for editting. + + function GetCommentSQL($table,$col) + { + return false; + } + + function SetCommentSQL($table,$col,$cmt) + { + return false; + } + + function &MetaTables() + { + return $this->connection->MetaTables(); + } + + function &MetaColumns($tab) + { + return $this->connection->MetaColumns($tab); + } + + function &MetaPrimaryKeys($tab,$owner=false,$intkey=false) + { + return $this->connection->MetaPrimaryKeys($tab.$owner,$intkey); + } + + function MetaType($t,$len=-1,$fieldobj=false) + { + return ADORecordSet::MetaType($t,$len,$fieldobj); + } + + // Executes the sql array returned by GetTableSQL and GetIndexSQL + function ExecuteSQLArray($sql, $continueOnError = true) + { + $rez = 2; + $conn = &$this->connection; + $saved = $conn->debug; + foreach($sql as $line) { + + if ($this->debug) $conn->debug = true; + $ok = $conn->Execute($line); + $conn->debug = $saved; + if (!$ok) { + if ($this->debug) ADOConnection::outp($conn->ErrorMsg()); + if (!$continueOnError) return 0; + $rez = 1; + } + } + return 2; + } + + /* + Returns the actual type given a character code. + + C: varchar + X: CLOB (character large object) or largest varchar size if CLOB is not supported + C2: Multibyte varchar + X2: Multibyte CLOB + + B: BLOB (binary large object) + + D: Date + T: Date-time + L: Integer field suitable for storing booleans (0 or 1) + I: Integer + F: Floating point number + N: Numeric or decimal number + */ + + function ActualType($meta) + { + return $meta; + } + + function CreateDatabase($dbname,$options=false) + { + $options = $this->_Options($options); + if (!preg_match('/^[a-z0-9A-Z_]*$/',$dbname)) $dbname = $this->quote.$dbname.$this->quote; + $s = 'CREATE DATABASE '.$dbname; + if (isset($options[$this->upperName])) $s .= ' '.$options[$this->upperName]; + $sql[] = $s; + return $sql; + } + + /* + Generates the SQL to create index. Returns an array of sql strings. + */ + function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false) + { + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + return $this->_IndexSQL($idxname, $tabname, $flds, $this->_Options($idxoptions)); + } + + function SetSchema($schema) + { + $this->schema = $schema; + } + + function AddColumnSQL($tabname, $flds) + { + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + $sql = array(); + list($lines,$pkey) = $this->_GenFields($flds); + foreach($lines as $v) { + $sql[] = "ALTER TABLE $tabname $this->addCol $v"; + } + return $sql; + } + + function AlterColumnSQL($tabname, $flds) + { + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + $sql = array(); + list($lines,$pkey) = $this->_GenFields($flds); + + foreach($lines as $v) { + $sql[] = "ALTER TABLE $tabname $this->alterCol $v"; + } + return $sql; + } + + function DropColumnSQL($tabname, $flds) + { + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + if (!is_array($flds)) $flds = explode(',',$flds); + $sql = array(); + foreach($flds as $v) { + $sql[] = "ALTER TABLE $tabname $this->dropCol $v"; + } + return $sql; + } + + function DropTableSQL($tabname) + { + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + $sql[] = sprintf($this->dropTable,$tabname); + return $sql; + } + + /* + Generate the SQL to create table. Returns an array of sql strings. + */ + function CreateTableSQL($tabname, $flds, $tableoptions=false) + { + if (!$tableoptions) $tableoptions = array(); + + list($lines,$pkey) = $this->_GenFields($flds); + + $taboptions = $this->_Options($tableoptions); + if ($this->schema) $tabname = $this->schema.'.'.$tabname; + $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions); + + $tsql = $this->_Triggers($tabname,$taboptions); + foreach($tsql as $s) $sql[] = $s; + + return $sql; + } + + function _GenFields($flds) + { + if (is_string($flds)) { + $padding = ' '; + $txt = $flds.$padding; + $flds = array(); + $flds0 = Lens_ParseArgs($txt,','); + $hasparam = false; + foreach($flds0 as $f0) { + $f1 = array(); + foreach($f0 as $token) { + switch (strtoupper($token)) { + case 'CONSTRAINT': + case 'DEFAULT': + $hasparam = $token; + break; + default: + if ($hasparam) $f1[$hasparam] = $token; + else $f1[] = $token; + $hasparam = false; + break; + } + } + $flds[] = $f1; + + } + } + $this->autoIncrement = false; + $lines = array(); + $pkey = array(); + foreach($flds as $fld) { + $fld = _array_change_key_case($fld); + + $fname = false; + $fdefault = false; + $fautoinc = false; + $ftype = false; + $fsize = false; + $fprec = false; + $fprimary = false; + $fnoquote = false; + $fdefts = false; + $fdefdate = false; + $fconstraint = false; + $fnotnull = false; + $funsigned = false; + + //----------------- + // Parse attributes + foreach($fld as $attr => $v) { + if ($attr == 2 && is_numeric($v)) $attr = 'SIZE'; + else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v); + + switch($attr) { + case '0': + case 'NAME': $fname = $v; break; + case '1': + case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break; + case 'SIZE': $dotat = strpos($v,'.'); + if ($dotat === false) $fsize = $v; + else { + $fsize = substr($v,0,$dotat); + $fprec = substr($v,$dotat+1); + } + break; + case 'UNSIGNED': $funsigned = true; break; + case 'AUTOINCREMENT': + case 'AUTO': $fautoinc = true; $fnotnull = true; break; + case 'KEY': + case 'PRIMARY': $fprimary = $v; $fnotnull = true; break; + case 'DEF': + case 'DEFAULT': $fdefault = $v; break; + case 'NOTNULL': $fnotnull = $v; break; + case 'NOQUOTE': $fnoquote = $v; break; + case 'DEFDATE': $fdefdate = $v; break; + case 'DEFTIMESTAMP': $fdefts = $v; break; + case 'CONSTRAINT': $fconstraint = $v; break; + } //switch + } // foreach $fld + + //-------------------- + // VALIDATE FIELD INFO + if (!strlen($fname)) { + if ($this->debug) ADOConnection::outp("Undefined NAME"); + return false; + } + + if (!strlen($ftype)) { + if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'"); + return false; + } else { + $ftype = strtoupper($ftype); + } + + $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec); + + if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls + + if ($fprimary) $pkey[] = $fname; + + // some databases do not allow blobs to have defaults + if ($ty == 'X') $fdefault = false; + + //-------------------- + // CONSTRUCT FIELD SQL + if ($fdefts) { + if (substr($this->connection->databaseType,0,5) == 'mysql') { + $ftype = 'TIMESTAMP'; + } else { + $fdefault = $this->connection->sysTimeStamp; + } + } else if ($fdefdate) { + if (substr($this->connection->databaseType,0,5) == 'mysql') { + $ftype = 'TIMESTAMP'; + } else { + $fdefault = $this->connection->sysDate; + } + } else if (strlen($fdefault) && !$fnoquote) + if ($ty == 'C' or $ty == 'X' or + ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) + if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') + $fdefault = trim($fdefault); + else if (strtolower($fdefault) != 'null') + $fdefault = $this->connection->qstr($fdefault); + $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned); + + $fname = str_pad($fname,16); + $lines[] = "$fname $ftype$suffix"; + + if ($fautoinc) $this->autoIncrement = true; + } // foreach $flds + + + return array($lines,$pkey); + } + /* + GENERATE THE SIZE PART OF THE DATATYPE + $ftype is the actual type + $ty is the type defined originally in the DDL + */ + function _GetSize($ftype, $ty, $fsize, $fprec) + { + if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) { + $ftype .= "(".$fsize; + if ($fprec) $ftype .= ",".$fprec; + $ftype .= ')'; + } + return $ftype; + } + + + // return string must begin with space + function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint) + { + $suffix = ''; + if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault"; + if ($fnotnull) $suffix .= ' NOT NULL'; + if ($fconstraint) $suffix .= ' '.$fconstraint; + return $suffix; + } + + function _IndexSQL($idxname, $tabname, $flds, $idxoptions) + { + if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname"; + if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE'; + else $unique = ''; + + if (is_array($flds)) $flds = implode(', ',$flds); + $s = "CREATE$unique INDEX $idxname ON $tabname "; + if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName]; + $s .= "($flds)"; + $sql[] = $s; + + return $sql; + } + + function _DropAutoIncrement($tabname) + { + return false; + } + + function _TableSQL($tabname,$lines,$pkey,$tableoptions) + { + $sql = array(); + + if (isset($tableoptions['REPLACE'])) { + $sql[] = sprintf($this->dropTable,$tabname); + if ($this->autoIncrement) { + $sInc = $this->_DropAutoIncrement($tabname); + if ($sInc) $sql[] = $sInc; + } + } + $s = "CREATE TABLE $tabname (\n"; + $s .= implode(",\n", $lines); + if (sizeof($pkey)>0) { + $s .= ",\n PRIMARY KEY ("; + $s .= implode(", ",$pkey).")"; + } + if (isset($tableoptions['CONSTRAINTS'])) + $s .= "\n".$tableoptions['CONSTRAINTS']; + + if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) + $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS']; + + $s .= "\n)"; + if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName]; + $sql[] = $s; + + return $sql; + } + + /* + GENERATE TRIGGERS IF NEEDED + used when table has auto-incrementing field that is emulated using triggers + */ + function _Triggers($tabname,$taboptions) + { + return array(); + } + + /* + Sanitize options, so that array elements with no keys are promoted to keys + */ + function _Options($opts) + { + if (!is_array($opts)) return array(); + $newopts = array(); + foreach($opts as $k => $v) { + if (is_numeric($k)) $newopts[strtoupper($v)] = $v; + else $newopts[strtoupper($k)] = $v; + } + return $newopts; + } + + +/* +"Florian Buzin [ easywe ]"
|<
';
- var $prev = '<<
';
- var $next = '>>
';
- var $last = '>|
';
- var $moreLinks = '...';
- var $startLinks = '...';
- var $gridHeader = false;
- var $htmlSpecialChars = true;
- var $page = 'Page';
- var $linkSelectedColor = 'red';
- var $cache = 0; #secs to cache with CachePageExecute()
-
- /* ---------------------------------------------- */
- /* constructor */
- /* */
- /* $db adodb connection object */
- /* $sql sql statement */
- /* $id optional id to identify which pager, */
- /* if you have multiple on 1 page. */
- /* $id should be only be [a-z0-9]* */
- /* */
- function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
- {
- global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
-
- $curr_page = $id.'_curr_page';
- if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
-
- $this->sql = $sql;
- $this->id = $id;
- $this->db = $db;
- $this->showPageLinks = $showPageLinks;
-
- $next_page = $id.'_next_page';
-
- if (isset($HTTP_GET_VARS[$next_page])) {
- $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
- }
- if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
-
- $this->curr_page = $HTTP_SESSION_VARS[$curr_page];
-
- }
-
- /* --------------------------- */
- /* Display link to first page */
- function Render_First($anchor=true)
- {
- global $PHP_SELF;
- if ($anchor) {
- ?>
- first;?>
- first ";
- }
- }
-
- /* -------------------------- */
- /* Display link to next page */
- function render_next($anchor=true)
- {
- global $PHP_SELF;
-
- if ($anchor) {
- ?>
- next;?>
- next ";
- }
- }
-
- /* ------------------ */
- /* Link to last page */
- /* */
- /* for better performance with large recordsets, you can set */
- /* $this->db->pageExecuteCountRows = false, which disables */
- /* last page counting. */
- function render_last($anchor=true)
- {
- global $PHP_SELF;
-
- if (!$this->db->pageExecuteCountRows) return;
-
- if ($anchor) {
- ?>
- last;?>
- last ";
- }
- }
-
- /* --------------------------------------------------- */
- /* original code by "Pablo Costa" ", - $header, - " |
", - $grid, - " |
", - $footer, - " |
|<
';
+ var $prev = '<<
';
+ var $next = '>>
';
+ var $last = '>|
';
+ var $moreLinks = '...';
+ var $startLinks = '...';
+ var $gridHeader = false;
+ var $htmlSpecialChars = true;
+ var $page = 'Page';
+ var $linkSelectedColor = 'red';
+ var $cache = 0; #secs to cache with CachePageExecute()
+
+ //----------------------------------------------
+ // constructor
+ //
+ // $db adodb connection object
+ // $sql sql statement
+ // $id optional id to identify which pager,
+ // if you have multiple on 1 page.
+ // $id should be only be [a-z0-9]*
+ //
+ function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
+ {
+ global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
+
+ $curr_page = $id.'_curr_page';
+ if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
+
+ $this->sql = $sql;
+ $this->id = $id;
+ $this->db = $db;
+ $this->showPageLinks = $showPageLinks;
+
+ $next_page = $id.'_next_page';
+
+ if (isset($HTTP_GET_VARS[$next_page])) {
+ $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
+ }
+ if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
+
+ $this->curr_page = $HTTP_SESSION_VARS[$curr_page];
+
+ }
+
+ //---------------------------
+ // Display link to first page
+ function Render_First($anchor=true)
+ {
+ global $PHP_SELF;
+ if ($anchor) {
+ ?>
+ first;?>
+ first ";
+ }
+ }
+
+ //--------------------------
+ // Display link to next page
+ function render_next($anchor=true)
+ {
+ global $PHP_SELF;
+
+ if ($anchor) {
+ ?>
+ next;?>
+ next ";
+ }
+ }
+
+ //------------------
+ // Link to last page
+ //
+ // for better performance with large recordsets, you can set
+ // $this->db->pageExecuteCountRows = false, which disables
+ // last page counting.
+ function render_last($anchor=true)
+ {
+ global $PHP_SELF;
+
+ if (!$this->db->pageExecuteCountRows) return;
+
+ if ($anchor) {
+ ?>
+ last;?>
+ last ";
+ }
+ }
+
+ //---------------------------------------------------
+ // original code by "Pablo Costa" ", + $header, + " |
", + $grid, + " |
", + $footer, + " |
Parameter | Value | Description |
Avg Time | Count | SQL | Max | Min |
".round($rs->fields[0],6)." | ".$rs->fields[2]." | ".$prefix.htmlspecialchars($sql).$suffix."". + " | ".$rs->fields[3]." | ".$rs->fields[4]." |
$this->helpurl. ".$this->conn->ErrorMsg()."
"; + $s = "Load | Count | SQL | Max | Min |
".round($rs->fields[0],6)." | ".$rs->fields[2]." | ".$prefix.htmlspecialchars($sql).$suffix."". + " | ".$rs->fields[3]." | ".$rs->fields[4]." |
+ ADOdb Performance Monitor for $app | |
+ Performance Stats View SQL + View Tables Poll Stats", + "$form", + " |
"; + $this->Poll($pollsecs); + break; + case 'viewsql': + if (empty($HTTP_GET_VARS['hidem'])) + echo " Clear SQL Log
"; + echo($this->SuspiciousSQL($nsql)); + echo($this->ExpensiveSQL($nsql)); + echo($this->InvalidSQL($nsql)); + break; + case 'tables': + echo $this->Tables(); break; + } + global $ADODB_vers; + echo "$ADODB_vers Sponsored by phpLens"; + } + + /* + Runs in infinite loop, returning real-time statistics + */ + function Poll($secs=5) + { + $this->conn->fnExecute = false; + //$this->conn->debug=1; + if ($secs <= 1) $secs = 1; + echo "Accumulating statistics, every $secs seconds...\n";flush(); + $arro =& $this->PollParameters(); + $cnt = 0; + set_time_limit(0); + sleep($secs); + while (1) { + $arr =& $this->PollParameters(); + + $hits = sprintf('%2.2f',$arr[0]); + $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs); + $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs); + $sess = sprintf('%5d',$arr[3]); + + $load = $this->CPULoad(); + if ($load !== false) { + $oslabel = 'WS-CPU%'; + $osval = sprintf(" %2.1f ",(float) $load); + }else { + $oslabel = ''; + $osval = ''; + } + if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n"; + $cnt += 1; + echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n"; + flush(); + + sleep($secs); + $arro = $arr; + } + } + + /* + Returns basic health check in a command line interface + */ + function HealthCheckCLI() + { + return $this->HealthCheck(true); + } + + + /* + Returns basic health check as HTML + */ + function HealthCheck($cli=false) + { + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + if ($cli) $html = ''; + else $html = $this->table.''.$this->titles; + + $oldc = false; + $bgc = ''; + foreach($this->settings as $name => $arr) { + if ($arr === false) break; + + if (!is_string($name)) { + if ($cli) $html .= " -- $arr -- \n"; + else $html .= " '.$this->conn->databaseType.'
color> "; + continue; + } + + if (!is_array($arr)) break; + $category = $arr[0]; + $how = $arr[1]; + if (sizeof($arr)>2) $desc = $arr[2]; + else $desc = ' '; + + + if ($category == 'HIDE') continue; + + $val = $this->_DBParameter($how); + + if ($desc && strncmp($desc,"=",1) === 0) { + $fn = substr($desc,1); + $desc = $this->$fn($val); + } + + if ($val === false) { + $m = $this->conn->ErrorMsg(); + $val = "Error: $m"; + } else { + if (is_numeric($val) && $val >= 256*1024) { + if ($val % (1024*1024) == 0) { + $val /= (1024*1024); + $val .= 'M'; + } else if ($val % 1024 == 0) { + $val /= 1024; + $val .= 'K'; + } + //$val = htmlspecialchars($val); + } + } + if ($category != $oldc) { + $oldc = $category; + //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color; + } + if (strlen($desc)==0) $desc = ' '; + if (strlen($val)==0) $val = ' '; + if ($cli) { + $html .= str_replace(' ','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc))); + + }else { + $html .= "$arr \n"; + } + } + + if (!$cli) $html .= " ".$name.' '.$val.' '.$desc."
\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}
"; - - - Installation - ============ - 1. Create this table in your database (syntax might vary depending on your db): - - create table sessions ( - SESSKEY char(32) not null, - EXPIRY int(11) unsigned not null, - EXPIREREF varchar(64), - DATA CLOB, - primary key (sesskey) - ); - - - 2. Then define the following parameters in this file: - $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase'; - $ADODB_SESSION_CONNECT='server to connect to'; - $ADODB_SESSION_USER ='user'; - $ADODB_SESSION_PWD ='password'; - $ADODB_SESSION_DB ='database'; - $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 - session bugs in earlier versions of PHP. - - 4. If you want to receive notifications when a session expires, then - you can tag a session with an EXPIREREF, and before the session - record is deleted, we can call a function that will pass the EXPIREREF - as the first parameter, and the session key as the second parameter. - - To do this, define a notification function, say NotifyFn: - - function NotifyFn($expireref, $sesskey) - { - } - - Then define a global variable, with the first parameter being the - global variable you would like to store in the EXPIREREF field, and - the second is the function name. - - In this example, we want to be notified when a user's session - has expired, so we store the user id in $USERID, and make this - the value stored in the EXPIREREF field: - - $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn'); -*/ - -if (!defined('_ADODB_LAYER')) { - include (dirname(__FILE__).'/adodb.inc.php'); -} - -if (!defined('ADODB_SESSION')) { - - define('ADODB_SESSION',1); - - /* if database time and system time is difference is greater than this, then give warning */ - define('ADODB_SESSION_SYNCH_SECS',60); - -/****************************************************************************************\ - Global definitions -\****************************************************************************************/ -GLOBAL $ADODB_SESSION_CONNECT, - $ADODB_SESSION_DRIVER, - $ADODB_SESSION_USER, - $ADODB_SESSION_PWD, - $ADODB_SESSION_DB, - $ADODB_SESS_CONN, - $ADODB_SESS_LIFE, - $ADODB_SESS_DEBUG, - $ADODB_SESSION_EXPIRE_NOTIFY, - $ADODB_SESSION_CRC; - $ADODB_SESSION_USE_LOBS; - - - $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime'); - if ($ADODB_SESS_LIFE <= 1) { - /* bug in PHP 4.0.3 pl 1 -- how about other versions? */ - /* print "Session: connection failed
",false); -} - -/****************************************************************************************\ - Close the connection -\****************************************************************************************/ -function adodb_sess_close() -{ -global $ADODB_SESS_CONN; - - if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close(); - return true; -} - -/****************************************************************************************\ - Slurp in the session variables and return the serialized string -\****************************************************************************************/ -function adodb_sess_read($key) -{ -global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC; - - $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time()); - if ($rs) { - if ($rs->EOF) { - $v = ''; - } else - $v = rawurldecode(reset($rs->fields)); - - $rs->Close(); - - /* new optimization adodb 2.1 */ - $ADODB_SESSION_CRC = strlen($v).crc32($v); - - return $v; - } - - return ''; /* thx to Jorma Tuomainen, webmaster#wizactive.com */ -} - -/****************************************************************************************\ - Write the serialized data to a database. - - If the data has not been modified since adodb_sess_read(), we do not write. -\****************************************************************************************/ -function adodb_sess_write($key, $val) -{ - global - $ADODB_SESS_CONN, - $ADODB_SESS_LIFE, - $ADODB_SESSION_TBL, - $ADODB_SESS_DEBUG, - $ADODB_SESSION_CRC, - $ADODB_SESSION_EXPIRE_NOTIFY, - $ADODB_SESSION_DRIVER, /* added */ - $ADODB_SESSION_USE_LOBS; /* added */ - - $expiry = time() + $ADODB_SESS_LIFE; - - /* 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
"; - $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); - $rs = $ADODB_SESS_CONN->Execute($qry); - return true; - } - $val = rawurlencode($val); - - $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val); - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - $var = reset($ADODB_SESSION_EXPIRE_NOTIFY); - global $$var; - $arr['expireref'] = $$var; - } - - - if ($ADODB_SESSION_USE_LOBS === false) { /* no lobs, simply use replace() */ - $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, 'sesskey',$autoQuote = true); - if (!$rs) { - $err = $ADODB_SESS_CONN->ErrorMsg(); - } - } else { - /* what value shall we insert/update for lob row? */ - switch ($ADODB_SESSION_DRIVER) { - /* empty_clob or empty_lob for oracle dbs */ - case "oracle": - case "oci8": - case "oci8po": - case "oci805": - $lob_value = sprintf("empty_%s()", strtolower($ADODB_SESSION_USE_LOBS)); - break; - - /* null for all other */ - default: - $lob_value = "null"; - break; - } - - /* do we insert or update? => as for sesskey */ - $res = $ADODB_SESS_CONN->Execute("select count(*) as cnt from $ADODB_SESSION_TBL where sesskey = '$key'"); - if ($res && ($res->fields["CNT"] > 0)) { - $qry = sprintf("update %s set expiry = %d, data = %s where sesskey = '%s'", $ADODB_SESSION_TBL, $expiry, $lob_value, $key); - } else { - /* insert */ - $qry = sprintf("insert into %s (sesskey, expiry, data) values ('%s', %d, %s)", $ADODB_SESSION_TBL, $key, $expiry, $lob_value); - } - - $err = ""; - $rs1 = $ADODB_SESS_CONN->Execute($qry); - if (!$rs1) { - $err .= $ADODB_SESS_CONN->ErrorMsg()."\n"; - } - $rs2 = $ADODB_SESS_CONN->UpdateBlob($ADODB_SESSION_TBL, 'data', $val, "sesskey='$key'", strtoupper($ADODB_SESSION_USE_LOBS)); - if (!$rs2) { - $err .= $ADODB_SESS_CONN->ErrorMsg()."\n"; - } - $rs = ($rs1 && $rs2) ? true : false; - } - - if (!$rs) { - 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 */ - if ($ADODB_SESS_CONN->databaseType == 'access') - $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'"); - } - return !empty($rs); -} - -function adodb_sess_destroy($key) -{ - global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; - - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - reset($ADODB_SESSION_EXPIRE_NOTIFY); - $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); - $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); - $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $ADODB_SESS_CONN->SetFetchMode($savem); - if ($rs) { - $ADODB_SESS_CONN->BeginTrans(); - while (!$rs->EOF) { - $ref = $rs->fields[0]; - $key = $rs->fields[1]; - $fn($ref,$key); - $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $rs->MoveNext(); - } - $ADODB_SESS_CONN->CommitTrans(); - } - } else { - $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'"; - $rs = $ADODB_SESS_CONN->Execute($qry); - } - return $rs ? true : false; -} - -function adodb_sess_gc($maxlifetime) -{ - global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; - - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - reset($ADODB_SESSION_EXPIRE_NOTIFY); - $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); - $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); - $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time()); - $ADODB_SESS_CONN->SetFetchMode($savem); - if ($rs) { - $ADODB_SESS_CONN->BeginTrans(); - while (!$rs->EOF) { - $ref = $rs->fields[0]; - $key = $rs->fields[1]; - $fn($ref,$key); - $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $rs->MoveNext(); - } - $ADODB_SESS_CONN->CommitTrans(); - } - } else { - $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time(); - $ADODB_SESS_CONN->Execute($qry); - - if ($ADODB_SESS_DEBUG) ADOConnection::outp("Garbage Collection: $qry
"); - } - /* suggested by Cameron, "GaM3R"$msg
"); - } - } - - return true; -} - -session_module_name('user'); -session_set_save_handler( - "adodb_sess_open", - "adodb_sess_close", - "adodb_sess_read", - "adodb_sess_write", - "adodb_sess_destroy", - "adodb_sess_gc"); -} - -/* 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); -} - -?> +\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['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']}
"; + + + Installation + ============ + 1. Create this table in your database (syntax might vary depending on your db): + + create table sessions ( + SESSKEY char(32) not null, + EXPIRY int(11) unsigned not null, + EXPIREREF varchar(64), + DATA CLOB, + primary key (sesskey) + ); + + + 2. Then define the following parameters in this file: + $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase'; + $ADODB_SESSION_CONNECT='server to connect to'; + $ADODB_SESSION_USER ='user'; + $ADODB_SESSION_PWD ='password'; + $ADODB_SESSION_DB ='database'; + $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 + session bugs in earlier versions of PHP. + + 4. If you want to receive notifications when a session expires, then + you can tag a session with an EXPIREREF, and before the session + record is deleted, we can call a function that will pass the EXPIREREF + as the first parameter, and the session key as the second parameter. + + To do this, define a notification function, say NotifyFn: + + function NotifyFn($expireref, $sesskey) + { + } + + Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY. + This is an array with 2 elements, the first being the name of the variable + you would like to store in the EXPIREREF field, and the 2nd is the + notification function's name. + + In this example, we want to be notified when a user's session + has expired, so we store the user id in the global variable $USERID, + store this value in the EXPIREREF field: + + $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn'); + + Then when the NotifyFn is called, we are passed the $USERID as the first + parameter, eg. NotifyFn($userid, $sesskey). +*/ + +if (!defined('_ADODB_LAYER')) { + include (dirname(__FILE__).'/adodb.inc.php'); +} + +if (!defined('ADODB_SESSION')) { + + define('ADODB_SESSION',1); + + /* if database time and system time is difference is greater than this, then give warning */ + define('ADODB_SESSION_SYNCH_SECS',60); + +/****************************************************************************************\ + Global definitions +\****************************************************************************************/ +GLOBAL $ADODB_SESSION_CONNECT, + $ADODB_SESSION_DRIVER, + $ADODB_SESSION_USER, + $ADODB_SESSION_PWD, + $ADODB_SESSION_DB, + $ADODB_SESS_CONN, + $ADODB_SESS_LIFE, + $ADODB_SESS_DEBUG, + $ADODB_SESSION_EXPIRE_NOTIFY, + $ADODB_SESSION_CRC, + $ADODB_SESSION_USE_LOBS; + + if (!isset($ADODB_SESSION_USE_LOBS)) $ADODB_SESSION_USE_LOBS = 'CLOB'; + + $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime'); + if ($ADODB_SESS_LIFE <= 1) { + // bug in PHP 4.0.3 pl 1 -- how about other versions? + //print "Session: connection failed
",false); +} + +/****************************************************************************************\ + Close the connection +\****************************************************************************************/ +function adodb_sess_close() +{ +global $ADODB_SESS_CONN; + + if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close(); + return true; +} + +/****************************************************************************************\ + Slurp in the session variables and return the serialized string +\****************************************************************************************/ +function adodb_sess_read($key) +{ +global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC; + + $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time()); + if ($rs) { + if ($rs->EOF) { + $v = ''; + } else + $v = rawurldecode(reset($rs->fields)); + + $rs->Close(); + + // new optimization adodb 2.1 + $ADODB_SESSION_CRC = strlen($v).crc32($v); + + return $v; + } + + return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com +} + +/****************************************************************************************\ + Write the serialized data to a database. + + If the data has not been modified since adodb_sess_read(), we do not write. +\****************************************************************************************/ +function adodb_sess_write($key, $val) +{ + global + $ADODB_SESS_CONN, + $ADODB_SESS_LIFE, + $ADODB_SESSION_TBL, + $ADODB_SESS_DEBUG, + $ADODB_SESSION_CRC, + $ADODB_SESSION_EXPIRE_NOTIFY, + $ADODB_SESSION_DRIVER, // added + $ADODB_SESSION_USE_LOBS; // added + + $expiry = time() + $ADODB_SESS_LIFE; + + // 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
"; + $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); + $rs = $ADODB_SESS_CONN->Execute($qry); + return true; + } + $val = rawurlencode($val); + + $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val); + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + $var = reset($ADODB_SESSION_EXPIRE_NOTIFY); + global $$var; + $arr['expireref'] = $$var; + } + + + if ($ADODB_SESSION_USE_LOBS === false) { // no lobs, simply use replace() + $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, 'sesskey',$autoQuote = true); + if (!$rs) { + $err = $ADODB_SESS_CONN->ErrorMsg(); + } + } else { + // what value shall we insert/update for lob row? + switch ($ADODB_SESSION_DRIVER) { + // empty_clob or empty_lob for oracle dbs + case "oracle": + case "oci8": + case "oci8po": + case "oci805": + $lob_value = sprintf("empty_%s()", strtolower($ADODB_SESSION_USE_LOBS)); + break; + + // null for all other + default: + $lob_value = "null"; + break; + } + + // do we insert or update? => as for sesskey + $res = $ADODB_SESS_CONN->Execute("select count(*) as cnt from $ADODB_SESSION_TBL where sesskey = '$key'"); + if ($res && reset($res->fields) > 0) { + $qry = sprintf("update %s set expiry = %d, data = %s where sesskey = '%s'", $ADODB_SESSION_TBL, $expiry, $lob_value, $key); + } else { + // insert + $qry = sprintf("insert into %s (sesskey, expiry, data) values ('%s', %d, %s)", $ADODB_SESSION_TBL, $key, $expiry, $lob_value); + } + + $err = ""; + $rs1 = $ADODB_SESS_CONN->Execute($qry); + if (!$rs1) { + $err .= $ADODB_SESS_CONN->ErrorMsg()."\n"; + } + $rs2 = $ADODB_SESS_CONN->UpdateBlob($ADODB_SESSION_TBL, 'data', $val, "sesskey='$key'", strtoupper($ADODB_SESSION_USE_LOBS)); + if (!$rs2) { + $err .= $ADODB_SESS_CONN->ErrorMsg()."\n"; + } + $rs = ($rs1 && $rs2) ? true : false; + } + + if (!$rs) { + 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 + if ($ADODB_SESS_CONN->databaseType == 'access') + $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'"); + } + return !empty($rs); +} + +function adodb_sess_destroy($key) +{ + global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; + + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + reset($ADODB_SESSION_EXPIRE_NOTIFY); + $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); + $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); + $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $ADODB_SESS_CONN->SetFetchMode($savem); + if ($rs) { + $ADODB_SESS_CONN->BeginTrans(); + while (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + $fn($ref,$key); + $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $rs->MoveNext(); + } + $ADODB_SESS_CONN->CommitTrans(); + } + } else { + $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'"; + $rs = $ADODB_SESS_CONN->Execute($qry); + } + return $rs ? true : false; +} + +function adodb_sess_gc($maxlifetime) +{ + global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; + + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + reset($ADODB_SESSION_EXPIRE_NOTIFY); + $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); + $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); + $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time()); + $ADODB_SESS_CONN->SetFetchMode($savem); + if ($rs) { + $ADODB_SESS_CONN->BeginTrans(); + while (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + $fn($ref,$key); + $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $rs->MoveNext(); + } + $ADODB_SESS_CONN->CommitTrans(); + } + } else { + $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time(); + $ADODB_SESS_CONN->Execute($qry); + + if ($ADODB_SESS_DEBUG) ADOConnection::outp("Garbage Collection: $qry
"); + } + // suggested by Cameron, "GaM3R"$msg
"); + } + } + + return true; +} + +session_module_name('user'); +session_set_save_handler( + "adodb_sess_open", + "adodb_sess_close", + "adodb_sess_read", + "adodb_sess_write", + "adodb_sess_destroy", + "adodb_sess_gc"); +} + +/* 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); +} + +?> diff --git a/lib/adodb/adodb-session.php b/lib/adodb/adodb-session.php index d808b06d7c..4a2aefdfb4 100644 --- a/lib/adodb/adodb-session.php +++ b/lib/adodb/adodb-session.php @@ -1,379 +1,398 @@ -\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['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']}
"; - - - Installation - ============ - 1. Create this table in your database (syntax might vary depending on your db): - - create table sessions ( - SESSKEY char(32) not null, - EXPIRY int(11) unsigned not null, - EXPIREREF varchar(64), - DATA text not null, - primary key (sesskey) - ); - - - 2. Then define the following parameters in this file: - $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase'; - $ADODB_SESSION_CONNECT='server to connect to'; - $ADODB_SESSION_USER ='user'; - $ADODB_SESSION_PWD ='password'; - $ADODB_SESSION_DB ='database'; - $ADODB_SESSION_TBL = 'sessions' - - 3. Recommended is PHP 4.0.6 or later. There are documented - session bugs in earlier versions of PHP. - - 4. If you want to receive notifications when a session expires, then - you can tag a session with an EXPIREREF, and before the session - record is deleted, we can call a function that will pass the EXPIREREF - as the first parameter, and the session key as the second parameter. - - To do this, define a notification function, say NotifyFn: - - function NotifyFn($expireref, $sesskey) - { - } - - Then define a global variable, with the first parameter being the - global variable you would like to store in the EXPIREREF field, and - the second is the function name. - - In this example, we want to be notified when a user's session - has expired, so we store the user id in $USERID, and make this - the value stored in the EXPIREREF field: - - $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn'); -*/ - -if (!defined('_ADODB_LAYER')) { - include (dirname(__FILE__).'/adodb.inc.php'); -} - -if (!defined('ADODB_SESSION')) { - - define('ADODB_SESSION',1); - - /* if database time and system time is difference is greater than this, then give warning */ - define('ADODB_SESSION_SYNCH_SECS',60); - -/****************************************************************************************\ - Global definitions -\****************************************************************************************/ -GLOBAL $ADODB_SESSION_CONNECT, - $ADODB_SESSION_DRIVER, - $ADODB_SESSION_USER, - $ADODB_SESSION_PWD, - $ADODB_SESSION_DB, - $ADODB_SESS_CONN, - $ADODB_SESS_LIFE, - $ADODB_SESS_DEBUG, - $ADODB_SESSION_EXPIRE_NOTIFY, - $ADODB_SESSION_CRC; - - - $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime'); - if ($ADODB_SESS_LIFE <= 1) { - /* bug in PHP 4.0.3 pl 1 -- how about other versions? */ - /* print "Session: connection failed
",false); -} - -/****************************************************************************************\ - Close the connection -\****************************************************************************************/ -function adodb_sess_close() -{ -global $ADODB_SESS_CONN; - - if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close(); - return true; -} - -/****************************************************************************************\ - Slurp in the session variables and return the serialized string -\****************************************************************************************/ -function adodb_sess_read($key) -{ -global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC; - - $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time()); - if ($rs) { - if ($rs->EOF) { - $v = ''; - } else - $v = rawurldecode(reset($rs->fields)); - - $rs->Close(); - - /* new optimization adodb 2.1 */ - $ADODB_SESSION_CRC = strlen($v).crc32($v); - - return $v; - } - - return ''; /* thx to Jorma Tuomainen, webmaster#wizactive.com */ -} - -/****************************************************************************************\ - Write the serialized data to a database. - - If the data has not been modified since adodb_sess_read(), we do not write. -\****************************************************************************************/ -function adodb_sess_write($key, $val) -{ - global - $ADODB_SESS_CONN, - $ADODB_SESS_LIFE, - $ADODB_SESSION_TBL, - $ADODB_SESS_DEBUG, - $ADODB_SESSION_CRC, - $ADODB_SESSION_EXPIRE_NOTIFY; - - $expiry = time() + $ADODB_SESS_LIFE; - - /* 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
"; - $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); - $rs = $ADODB_SESS_CONN->Execute($qry); - return true; - } - $val = rawurlencode($val); - - $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val); - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - $var = reset($ADODB_SESSION_EXPIRE_NOTIFY); - global $$var; - $arr['expireref'] = $$var; - } - $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, - 'sesskey',$autoQuote = true); - - if (!$rs) { - 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 */ - if ($ADODB_SESS_CONN->databaseType == 'access') - $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'"); - } - return !empty($rs); -} - -function adodb_sess_destroy($key) -{ - global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; - - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - reset($ADODB_SESSION_EXPIRE_NOTIFY); - $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); - $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); - $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $ADODB_SESS_CONN->SetFetchMode($savem); - if ($rs) { - $ADODB_SESS_CONN->BeginTrans(); - while (!$rs->EOF) { - $ref = $rs->fields[0]; - $key = $rs->fields[1]; - $fn($ref,$key); - $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $rs->MoveNext(); - } - $ADODB_SESS_CONN->CommitTrans(); - } - } else { - $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'"; - $rs = $ADODB_SESS_CONN->Execute($qry); - } - return $rs ? true : false; -} - -function adodb_sess_gc($maxlifetime) -{ - global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; - - if ($ADODB_SESSION_EXPIRE_NOTIFY) { - reset($ADODB_SESSION_EXPIRE_NOTIFY); - $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); - $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); - $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time()); - $ADODB_SESS_CONN->SetFetchMode($savem); - if ($rs) { - $ADODB_SESS_CONN->BeginTrans(); - while (!$rs->EOF) { - $ref = $rs->fields[0]; - $key = $rs->fields[1]; - $fn($ref,$key); - $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); - $rs->MoveNext(); - } - $ADODB_SESS_CONN->CommitTrans(); - } - } else { - $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time(); - $ADODB_SESS_CONN->Execute($qry); - - if ($ADODB_SESS_DEBUG) ADOConnection::outp("Garbage Collection: $qry
"); - } - /* suggested by Cameron, "GaM3R"$msg
"); - } - } - - return true; -} - -session_module_name('user'); -session_set_save_handler( - "adodb_sess_open", - "adodb_sess_close", - "adodb_sess_read", - "adodb_sess_write", - "adodb_sess_destroy", - "adodb_sess_gc"); -} - -/* 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); -} - +\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['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']}
"; + + + Installation + ============ + 1. Create this table in your database (syntax might vary depending on your db): + + create table sessions ( + SESSKEY char(32) not null, + EXPIRY int(11) unsigned not null, + EXPIREREF varchar(64), + DATA text not null, + primary key (sesskey) + ); + + For oracle: + create table sessions ( + SESSKEY char(32) not null, + EXPIRY DECIMAL(16) not null, + EXPIREREF varchar(64), + DATA varchar(4000) not null, + primary key (sesskey) + ); + + + 2. Then define the following parameters. You can either modify + this file, or define them before this file is included: + + $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase'; + $ADODB_SESSION_CONNECT='server to connect to'; + $ADODB_SESSION_USER ='user'; + $ADODB_SESSION_PWD ='password'; + $ADODB_SESSION_DB ='database'; + $ADODB_SESSION_TBL = 'sessions' + + 3. Recommended is PHP 4.0.6 or later. There are documented + session bugs in earlier versions of PHP. + + 4. If you want to receive notifications when a session expires, then + you can tag a session with an EXPIREREF, and before the session + record is deleted, we can call a function that will pass the EXPIREREF + as the first parameter, and the session key as the second parameter. + + To do this, define a notification function, say NotifyFn: + + function NotifyFn($expireref, $sesskey) + { + } + + Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY. + This is an array with 2 elements, the first being the name of the variable + you would like to store in the EXPIREREF field, and the 2nd is the + notification function's name. + + In this example, we want to be notified when a user's session + has expired, so we store the user id in the global variable $USERID, + store this value in the EXPIREREF field: + + $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn'); + + Then when the NotifyFn is called, we are passed the $USERID as the first + parameter, eg. NotifyFn($userid, $sesskey). +*/ + +if (!defined('_ADODB_LAYER')) { + include (dirname(__FILE__).'/adodb.inc.php'); +} + +if (!defined('ADODB_SESSION')) { + + define('ADODB_SESSION',1); + + /* if database time and system time is difference is greater than this, then give warning */ + define('ADODB_SESSION_SYNCH_SECS',60); + +/****************************************************************************************\ + Global definitions +\****************************************************************************************/ +GLOBAL $ADODB_SESSION_CONNECT, + $ADODB_SESSION_DRIVER, + $ADODB_SESSION_USER, + $ADODB_SESSION_PWD, + $ADODB_SESSION_DB, + $ADODB_SESS_CONN, + $ADODB_SESS_LIFE, + $ADODB_SESS_DEBUG, + $ADODB_SESSION_EXPIRE_NOTIFY, + $ADODB_SESSION_CRC; + + + $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime'); + if ($ADODB_SESS_LIFE <= 1) { + // bug in PHP 4.0.3 pl 1 -- how about other versions? + //print "Session: connection failed
",false); +} + +/****************************************************************************************\ + Close the connection +\****************************************************************************************/ +function adodb_sess_close() +{ +global $ADODB_SESS_CONN; + + if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close(); + return true; +} + +/****************************************************************************************\ + Slurp in the session variables and return the serialized string +\****************************************************************************************/ +function adodb_sess_read($key) +{ +global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC; + + $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time()); + if ($rs) { + if ($rs->EOF) { + $v = ''; + } else + $v = rawurldecode(reset($rs->fields)); + + $rs->Close(); + + // new optimization adodb 2.1 + $ADODB_SESSION_CRC = strlen($v).crc32($v); + + return $v; + } + + return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com +} + +/****************************************************************************************\ + Write the serialized data to a database. + + If the data has not been modified since adodb_sess_read(), we do not write. +\****************************************************************************************/ +function adodb_sess_write($key, $val) +{ + global + $ADODB_SESS_CONN, + $ADODB_SESS_LIFE, + $ADODB_SESSION_TBL, + $ADODB_SESS_DEBUG, + $ADODB_SESSION_CRC, + $ADODB_SESSION_EXPIRE_NOTIFY; + + $expiry = time() + $ADODB_SESS_LIFE; + + // 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
"; + $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time(); + $rs = $ADODB_SESS_CONN->Execute($qry); + return true; + } + $val = rawurlencode($val); + + $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val); + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + $var = reset($ADODB_SESSION_EXPIRE_NOTIFY); + global $$var; + $arr['expireref'] = $$var; + } + $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, + 'sesskey',$autoQuote = true); + + if (!$rs) { + 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 + if ($ADODB_SESS_CONN->databaseType == 'access') + $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'"); + } + return !empty($rs); +} + +function adodb_sess_destroy($key) +{ + global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; + + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + reset($ADODB_SESSION_EXPIRE_NOTIFY); + $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); + $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); + $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $ADODB_SESS_CONN->SetFetchMode($savem); + if ($rs) { + $ADODB_SESS_CONN->BeginTrans(); + while (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + $fn($ref,$key); + $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $rs->MoveNext(); + } + $ADODB_SESS_CONN->CommitTrans(); + } + } else { + $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'"; + $rs = $ADODB_SESS_CONN->Execute($qry); + } + return $rs ? true : false; +} + +function adodb_sess_gc($maxlifetime) +{ + global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY; + + if ($ADODB_SESSION_EXPIRE_NOTIFY) { + reset($ADODB_SESSION_EXPIRE_NOTIFY); + $fn = next($ADODB_SESSION_EXPIRE_NOTIFY); + $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM); + $rs =& $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time()); + $ADODB_SESS_CONN->SetFetchMode($savem); + if ($rs) { + $ADODB_SESS_CONN->BeginTrans(); + while (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + $fn($ref,$key); + $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'"); + $rs->MoveNext(); + } + $ADODB_SESS_CONN->CommitTrans(); + } + } else { + $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time(); + $ADODB_SESS_CONN->Execute($qry); + + if ($ADODB_SESS_DEBUG) ADOConnection::outp("Garbage Collection: $qry
"); + } + // suggested by Cameron, "GaM3R"$msg
"); + } + } + + return true; +} + +session_module_name('user'); +session_set_save_handler( + "adodb_sess_open", + "adodb_sess_close", + "adodb_sess_read", + "adodb_sess_write", + "adodb_sess_destroy", + "adodb_sess_gc"); +} + +/* 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); +} + ?> \ No newline at end of file diff --git a/lib/adodb/adodb-time.inc.php b/lib/adodb/adodb-time.inc.php index 5a0f6cac36..5ea9c9eef9 100644 --- a/lib/adodb/adodb-time.inc.php +++ b/lib/adodb/adodb-time.inc.php @@ -1,868 +1,899 @@ - 4 digit year conversion. The maximum is billions of years in the -future, but this is a theoretical limit as the computation of that year -would take too long with the current implementation of adodb_mktime(). - -This library replaces native functions as follows: - -- getdate() with adodb_getdate() - date() with adodb_date() - gmdate() with adodb_gmdate() - mktime() with adodb_mktime() - gmmktime() with adodb_gmmktime()45 -- -The parameters are identical, except that adodb_date() accepts a subset -of date()'s field formats. Mktime() will convert from local time to GMT, -and date() will convert from GMT to local time, but daylight savings is -not handled currently. - -This library is independant of the rest of ADOdb, and can be used -as standalone code. - -PERFORMANCE - -For high speed, this library uses the native date functions where -possible, and only switches to PHP code when the dates fall outside -the 32-bit signed integer range. - -GREGORIAN CORRECTION - -Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, -October 4, 1582 (Julian) was followed immediately by Friday, October 15, -1582 (Gregorian). - -Since 0.06, we handle this correctly, so: - -adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) - == 24 * 3600 (1 day) - -============================================================================= - -COPYRIGHT - -(c) 2003 John Lim and released under BSD-style license except for code by jackbbs, -which includes adodb_mktime, adodb_get_gmt_different, adodb_is_leap_year -and originally found at http://www.php.net/manual/en/function.mktime.php - -============================================================================= - -BUG REPORTS - -These should be posted to the ADOdb forums at - - http://phplens.com/lens/lensforum/topics.php?id=4 - -============================================================================= - -FUNCTION DESCRIPTIONS - - -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) - -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 -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" -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 - -- - -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) - -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. - -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. - -============================================================================= - -NOTES - -Useful url for generating test timestamps: - http://www.4webhelp.net/us/timestamp.php - -Possible future optimizations include - -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 - http://webexhibits.org/daylightsaving/ - - -CHANGELOG -- 3 March 2003 0.08 -Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS -if you want PHP to handle negative timestamps between 1901 to 1969. - -- 27 Feb 2003 0.07 -All negative numbers handled by adodb now because of RH 7.3+ problems. -See http://bugs.php.net/bug.php?id=20048&edit=2 - -- 4 Feb 2003 0.06 -Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates -are now correctly handled. - -- 29 Jan 2003 0.05 - -Leap year checking differs under Julian calendar (pre 1582). Also -leap year code optimized by checking for most common case first. - -We also handle month overflow correctly in mktime (eg month set to 13). - -Day overflow for less than one month's days is supported. - -- 28 Jan 2003 0.04 - -Gregorian correction handled. In PHP5, we might throw an error if -mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10. -Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582. - -- 27 Jan 2003 0.03 - -Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION. -Fixed calculation of days since start of year for <1970. - -- 27 Jan 2003 0.02 - -Changed _adodb_getdate() to inline leap year checking for better performance. -Fixed problem with time-zones west of GMT +0000. - -- 24 Jan 2003 0.01 - -First implementation. -*/ - - -/* Initialization */ - -/* - Version Number -*/ -define('ADODB_DATE_VERSION',0.08); - -/* - 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! - - 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 - echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1 - - References: - http://bugs.php.net/bug.php?id=20048&edit=2 - http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html -*/ - -if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); - -function adodb_date_test_date($y1,$m) -{ - /* 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
Testing gregorian <=> julian conversion
";
- $t = adodb_mktime(0,0,0,10,11,1492);
- /* http://www.holidayorigins.com/html/columbus_day.html - Friday check */
- if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing
';
-
- $t = adodb_mktime(0,0,0,2,29,1500);
- if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years
';
-
- $t = adodb_mktime(0,0,0,2,29,1700);
- if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years
';
-
- print adodb_mktime(0,0,0,10,4,1582).' ';
- print adodb_mktime(0,0,0,10,15,1582);
- $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582));
- if ($diff != 3600*24) print " Error in gregorian correction = ".($diff/3600/24)." days
";
-
- print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : 'Error')."
";
- print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : 'Error')."
";
-
- print "
Testing overflow
";
-
- $t = adodb_mktime(0,0,0,3,33,1965);
- if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1
';
- $t = adodb_mktime(0,0,0,4,33,1971);
- if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2
';
- $t = adodb_mktime(0,0,0,1,60,1965);
- if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).'
';
- $t = adodb_mktime(0,0,0,12,32,1965);
- if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).'
';
- $t = adodb_mktime(0,0,0,12,63,1965);
- if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).'
';
- $t = adodb_mktime(0,0,0,13,3,1965);
- if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1
';
-
- print "Testing 2-digit => 4-digit year conversion
";
- if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000
";
- if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010
";
- if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020
";
- if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030
";
- if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940
";
- if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950
";
- if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990
";
-
- /* Test string formating */
- print "
Testing date formating
"; - $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003'; - $s1 = date($fmt,0); - $s2 = adodb_date($fmt,0); - if ($s1 != $s2) { - print " date() 0 failed"; */
- $pos = strcmp($s1,$s2);
-
- if (($s1) != ($s2)) {
- for ($j=0,$k=strlen($s1); $j < $k; $j++) {
- if ($s1[$j] != $s2[$j]) {
- print substr($s1,$j).' ';
- break;
- }
- }
- print "Error date(): $ts
- \"$s1\" (date len=".strlen($s1).")
- \"$s2\" (adodb_date len=".strlen($s2).")
";
- $fail = true;
- }
-
- $a1 = getdate($ts);
- $a2 = adodb_getdate($ts);
- $rez = array_diff($a1,$a2);
- if (sizeof($rez)>0) {
- print "Error getdate() $ts
";
- print_r($a1);
- print "
";
- print_r($a2);
- print "
"; - $fail = true; - } - } - - /* Test generation of dates outside 1901-2038 */ - print "
Testing random dates between 100 and 4000
"; - adodb_date_test_date(100,1); - for ($i=100; --$i >= 0;) { - $y1 = 100+rand(0,1970-100); - $m = rand(1,12); - adodb_date_test_date($y1,$m); - - $y1 = 3000-rand(0,3000-1970); - adodb_date_test_date($y1,$m); - } - print ''; - $start = 1960+rand(0,10); - $yrs = 12; - $i = 365.25*86400*($start-1970); - $offset = 36000+rand(10000,60000); - $max = 365*$yrs*86400; - $lastyear = 0; - - /* we generate a timestamp, convert it to a date, and convert it back to a timestamp */ - /* and check if the roundtrip broke the original timestamp value. */ - print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; - - for ($max += $i; $i < $max; $i += $offset) { - $ret = adodb_date('m,d,Y,H,i,s',$i); - $arr = explode(',',$ret); - if ($lastyear != $arr[2]) { - $lastyear = $arr[2]; - print " $lastyear "; - flush(); - } - $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); - if ($i != $newi) { - print "Error at $i, adodb_mktime returned $newi ($ret)"; - $fail = true; - break; - } - } - - if (!$fail) print "
Passed !
"; - else print "Failed :-(
"; -} - -/** - Returns day of week, 0 = Sunday,... 6=Saturday. - Algorithm from PEAR::Date_Calc -*/ -function adodb_dow($year, $month, $day) -{ -/* -Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and -proclaimed that from that time onwards 3 days would be dropped from the calendar -every 400 years. - -Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). -*/ - if ($year <= 1582) { - if ($year < 1582 || - ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; - else - $greg_correction = 0; - } else - $greg_correction = 0; - - if($month > 2) - $month -= 2; - else { - $month += 10; - $year--; - } - - $day = ( floor((13 * $month - 1) / 5) + - $day + ($year % 100) + - floor(($year % 100) / 4) + - floor(($year / 100) / 4) - 2 * - floor($year / 100) + 77); - - return (($day - 7 * floor($day / 7))) + $greg_correction; -} - - -/** - Checks for leap year, returns true if it is. No 2-digit year check. Also - handles julian calendar correctly. -*/ -function _adodb_is_leap_year($year) -{ - if ($year % 4 != 0) return false; - - if ($year % 400 == 0) { - return true; - /* if gregorian calendar (>1582), century not-divisible by 400 is not leap */ - } else if ($year > 1582 && $year % 100 == 0 ) { - return false; - } - - return true; -} - -/** - checks for leap year, returns true if it is. Has 2-digit year check -*/ -function adodb_is_leap_year($year) -{ - return _adodb_is_leap_year(adodb_year_digit_check($year)); -} - -/** - Fix 2-digit years. Works for any century. - Assumes that if 2-digit is more than 30 years in future, then previous century. -*/ -function adodb_year_digit_check($y) -{ - if ($y < 100) { - - $yr = (integer) date("Y"); - $century = (integer) ($yr /100); - - if ($yr%100 > 50) { - $c1 = $century + 1; - $c0 = $century; - } else { - $c1 = $century; - $c0 = $century - 1; - } - $c1 *= 100; - /* if 2-digit year is less than 30 years in future, set it to this century */ - /* otherwise if more than 30 years in future, then we set 2-digit year to the prev century. */ - if (($y + $c1) < $yr+30) $y = $y + $c1; - else $y = $y + $c0*100; - } - return $y; -} - -/** - get local time zone offset from GMT -*/ -function adodb_get_gmt_different() -{ -static $DIFF; - if (isset($DIFF)) return $DIFF; - - $DIFF = mktime(0,0,0,1,2,1970) - gmmktime(0,0,0,1,2,1970); - return $DIFF; -} - -/** - Returns an array with date info. -*/ -function adodb_getdate($d=false,$fast=false) -{ - if ($d === false) return getdate(); - if (!defined('ADODB_TEST_DATES')) { - if ((abs($d) <= 0x7FFFFFFF)) { /* check if number in 32-bit signed range */ - if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) /* if windows, must be +ve integer */ - return @getdate($d); - } - } - return _adodb_getdate($d); -} - -/** - Low-level function that returns the getdate() array. We have a special - $fast flag, which if set to true, will return fewer array values, - and is much faster as it does not calculate dow, etc. -*/ -function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) -{ - $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_different()); - - $_day_power = 86400; - $_hour_power = 3600; - $_min_power = 60; - - if ($d < -12219321600) $d -= 86400*10; /* if 15 Oct 1582 or earlier, gregorian correction */ - - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); - - if ($d < 0) { - $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 */ - for ($a = 1970 ; --$a >= 0;) { - $lastd = $d; - - if ($leaf = _adodb_is_leap_year($a)) { - $d += $_day_power * 366; - } else - $d += $_day_power * 365; - if ($d >= 0) { - $year = $a; - break; - } - } - - $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; - - $d = $lastd; - $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 13 ; --$a > 0;) { - $lastd = $d; - $d += $mtab[$a] * $_day_power; - if ($d >= 0) { - $month = $a; - $ndays = $mtab[$a]; - break; - } - } - - $d = $lastd; - $day = $ndays + ceil(($d+1) / ($_day_power)); - - $d += ($ndays - $day+1)* $_day_power; - $hour = floor($d/$_hour_power); - - } else { - - for ($a = 1970 ;; $a++) { - $lastd = $d; - - if ($leaf = _adodb_is_leap_year($a)) { - $d -= $_day_power * 366; - } else - $d -= $_day_power * 365; - if ($d <= 0) { - $year = $a; - break; - } - } - $secsInYear = $lastd; - $d = $lastd; - $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 1 ; $a <= 12; $a++) { - $lastd = $d; - $d -= $mtab[$a] * $_day_power; - if ($d <= 0) { - $month = $a; - $ndays = $mtab[$a]; - break; - } - } - $d = $lastd; - $day = ceil(($d+1) / $_day_power); - $d = $d - ($day-1) * $_day_power; - $hour = floor($d /$_hour_power); - } - - $d -= $hour * $_hour_power; - $min = floor($d/$_min_power); - $secs = $d - $min * $_min_power; - if ($fast) { - return array( - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'leap' => $leaf, - 'ndays' => $ndays - ); - } - - - $dow = adodb_dow($year,$month,$day); - - return array( - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'wday' => $dow, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'weekday' => gmdate('l',$_day_power*(3+$dow)), - 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), - 0 => $origd - ); -} - -function adodb_gmdate($fmt,$d=false) -{ - return adodb_date($fmt,$d,true); -} - - -/** - Return formatted date based on timestamp $d -*/ -function adodb_date($fmt,$d=false,$is_gmt=false) -{ - if ($d === false) return date($fmt); - if (!defined('ADODB_TEST_DATES')) { - if ((abs($d) <= 0x7FFFFFFF)) { /* check if number in 32-bit signed range */ - if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) /* if windows, must be +ve integer */ - return @date($fmt,$d); - } - } - $_day_power = 86400; - - $arr = _adodb_getdate($d,true,$is_gmt); - $year = $arr['year']; - $month = $arr['mon']; - $day = $arr['mday']; - $hour = $arr['hours']; - $min = $arr['minutes']; - $secs = $arr['seconds']; - - $max = strlen($fmt); - $dates = ''; - - /* - at this point, we have the following integer vars to manipulate: - $year, $month, $day, $hour, $min, $secs - */ - for ($i=0; $i < $max; $i++) { - switch($fmt[$i]) { - case 'T': $dates .= date('T');break; - /* YEAR */ - case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; - case 'r': /* Thu, 21 Dec 2000 16:01:07 +0200 */ - - $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.' '; - - if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; - - if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; - - if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; - - $gmt = adodb_get_gmt_different(); - $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; - - case 'Y': $dates .= $year; break; - case 'y': $dates .= substr($year,strlen($year)-2,2); break; - /* MONTH */ - case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; - case 'n': $dates .= $month; break; - case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; - case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; - /* DAY */ - case 't': $dates .= $arr['ndays']; break; - case 'z': $dates .= $arr['yday']; break; - case 'w': $dates .= adodb_dow($year,$month,$day); break; - case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'j': $dates .= $day; break; - case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; - case 'S': - $d10 = $day % 10; - if ($d10 == 1) $dates .= 'st'; - else if ($d10 == 2) $dates .= 'nd'; - else if ($d10 == 3) $dates .= 'rd'; - else $dates .= 'th'; - break; - - /* HOUR */ - case 'Z': - $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_different(); break; - case 'O': - $gmt = ($is_gmt) ? 0 : adodb_get_gmt_different(); - $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; - - case 'H': - if ($hour < 10) $dates .= '0'.$hour; - else $dates .= $hour; - break; - case 'h': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } - - if ($hh < 10) $dates .= '0'.$hh; - else $dates .= $hh; - break; - - case 'G': - $dates .= $hour; - break; - - case 'g': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } - $dates .= $hh; - break; - /* MINUTES */ - case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; - /* SECONDS */ - case 'U': $dates .= $d; break; - case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; - /* AM/PM */ - /* Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM */ - case 'a': - if ($hour>=12) $dates .= 'pm'; - else $dates .= 'am'; - break; - case 'A': - if ($hour>=12) $dates .= 'PM'; - else $dates .= 'AM'; - break; - default: - $dates .= $fmt[$i]; break; - /* ESCAPE */ - case "\\": - $i++; - if ($i < $max) $dates .= $fmt[$i]; - break; - } - } - return $dates; -} - -/** - Returns a timestamp given a GMT/UTC time. - Note that $is_dst is not implemented and is ignored. -*/ -function adodb_gmmktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false) -{ - return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); -} - -/** - Return a timestamp given a local time. Originally by jackbbs. - Note that $is_dst is not implemented and is ignored. -*/ -function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) -{ - if (!defined('ADODB_TEST_DATES')) { - /* for windows, we don't check 1970 because with timezone differences, */ - /* 1 Jan 1970 could generate negative timestamp, which is illegal */ - if (!defined('ADODB_NO_NEGATIVE_TS') || ($year >= 1971)) - if (1901 < $year && $year < 2038) - return @mktime($hr,$min,$sec,$mon,$day,$year); - } - - $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_different(); - - $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; - } - - $_day_power = 86400; - $_hour_power = 3600; - $_min_power = 60; - - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); - - $_total_date = 0; - if ($year >= 1970) { - for ($a = 1970 ; $a <= $year; $a++) { - $leaf = _adodb_is_leap_year($a); - if ($leaf == true) { - $loop_table = $_month_table_leaf; - $_add_date = 366; - } else { - $loop_table = $_month_table_normal; - $_add_date = 365; - } - if ($a < $year) { - $_total_date += $_add_date; - } else { - for($b=1;$b<$mon;$b++) { - $_total_date += $loop_table[$b]; - } - } - } - $_total_date +=$day-1; - $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; - - } else { - for ($a = 1969 ; $a >= $year; $a--) { - $leaf = _adodb_is_leap_year($a); - if ($leaf == true) { - $loop_table = $_month_table_leaf; - $_add_date = 366; - } else { - $loop_table = $_month_table_normal; - $_add_date = 365; - } - if ($a > $year) { $_total_date += $_add_date; - } else { - for($b=12;$b>$mon;$b--) { - $_total_date += $loop_table[$b]; - } - } - } - $_total_date += $loop_table[$mon] - $day; - - $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; - $_day_time = $_day_power - $_day_time; - $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); - if ($ret < -12220185600) $ret += 10*86400; /* if earlier than 5 Oct 1582 - gregorian correction */ - else if ($ret < -12219321600) $ret = -12219321600; /* if in limbo, reset to 15 Oct 1582. */ - } - /* print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; */ - return $ret; -} - -?> + 4 digit year conversion. The maximum is billions of years in the +future, but this is a theoretical limit as the computation of that year +would take too long with the current implementation of adodb_mktime(). + +This library replaces native functions as follows: + ++ getdate() with adodb_getdate() + date() with adodb_date() + gmdate() with adodb_gmdate() + mktime() with adodb_mktime() + gmmktime() with adodb_gmmktime()45 ++ +The parameters are identical, except that adodb_date() accepts a subset +of date()'s field formats. Mktime() will convert from local time to GMT, +and date() will convert from GMT to local time, but daylight savings is +not handled currently. + +This library is independant of the rest of ADOdb, and can be used +as standalone code. + +PERFORMANCE + +For high speed, this library uses the native date functions where +possible, and only switches to PHP code when the dates fall outside +the 32-bit signed integer range. + +GREGORIAN CORRECTION + +Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, +October 4, 1582 (Julian) was followed immediately by Friday, October 15, +1582 (Gregorian). + +Since 0.06, we handle this correctly, so: + +adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) + == 24 * 3600 (1 day) + +============================================================================= + +COPYRIGHT + +(c) 2003 John Lim and released under BSD-style license except for code by jackbbs, +which includes adodb_mktime, adodb_get_gmt_different, adodb_is_leap_year +and originally found at http://www.php.net/manual/en/function.mktime.php + +============================================================================= + +BUG REPORTS + +These should be posted to the ADOdb forums at + + http://phplens.com/lens/lensforum/topics.php?id=4 + +============================================================================= + +FUNCTION DESCRIPTIONS + + +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) + +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 +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. ++ +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 + ++ +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) + +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) + +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. + +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. + +============================================================================= + +NOTES + +Useful url for generating test timestamps: + http://www.4webhelp.net/us/timestamp.php + +Possible future optimizations include + +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 + http://webexhibits.org/daylightsaving/ + + +CHANGELOG + +- 9 Aug 2003 0.10 +Fixed bug with dates after 2038. +See http://phplens.com/lens/lensforum/msgs.php?id=6980 + +- 1 July 2003 0.09 +Added support for Q (Quarter). +Added adodb_date2(), which accepts ISO date in 2nd param + +- 3 March 2003 0.08 +Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS +if you want PHP to handle negative timestamps between 1901 to 1969. + +- 27 Feb 2003 0.07 +All negative numbers handled by adodb now because of RH 7.3+ problems. +See http://bugs.php.net/bug.php?id=20048&edit=2 + +- 4 Feb 2003 0.06 +Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates +are now correctly handled. + +- 29 Jan 2003 0.05 + +Leap year checking differs under Julian calendar (pre 1582). Also +leap year code optimized by checking for most common case first. + +We also handle month overflow correctly in mktime (eg month set to 13). + +Day overflow for less than one month's days is supported. + +- 28 Jan 2003 0.04 + +Gregorian correction handled. In PHP5, we might throw an error if +mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10. +Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582. + +- 27 Jan 2003 0.03 + +Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION. +Fixed calculation of days since start of year for <1970. + +- 27 Jan 2003 0.02 + +Changed _adodb_getdate() to inline leap year checking for better performance. +Fixed problem with time-zones west of GMT +0000. + +- 24 Jan 2003 0.01 + +First implementation. +*/ + + +/* Initialization */ + +/* + Version Number +*/ +define('ADODB_DATE_VERSION',0.10); + +/* + 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! + + 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 + echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1 + + References: + http://bugs.php.net/bug.php?id=20048&edit=2 + http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html +*/ + +if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); + +function adodb_date_test_date($y1,$m) +{ + //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
Testing gregorian <=> julian conversion
";
+ $t = adodb_mktime(0,0,0,10,11,1492);
+ //http://www.holidayorigins.com/html/columbus_day.html - Friday check
+ if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing
';
+
+ $t = adodb_mktime(0,0,0,2,29,1500);
+ if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years
';
+
+ $t = adodb_mktime(0,0,0,2,29,1700);
+ if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years
';
+
+ print adodb_mktime(0,0,0,10,4,1582).' ';
+ print adodb_mktime(0,0,0,10,15,1582);
+ $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582));
+ if ($diff != 3600*24) print " Error in gregorian correction = ".($diff/3600/24)." days
";
+
+ print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : 'Error')."
";
+ print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : 'Error')."
";
+
+ print "
Testing overflow
";
+
+ $t = adodb_mktime(0,0,0,3,33,1965);
+ if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1
';
+ $t = adodb_mktime(0,0,0,4,33,1971);
+ if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2
';
+ $t = adodb_mktime(0,0,0,1,60,1965);
+ if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).'
';
+ $t = adodb_mktime(0,0,0,12,32,1965);
+ if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).'
';
+ $t = adodb_mktime(0,0,0,12,63,1965);
+ if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).'
';
+ $t = adodb_mktime(0,0,0,13,3,1965);
+ if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1
';
+
+ print "Testing 2-digit => 4-digit year conversion
";
+ if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000
";
+ if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010
";
+ if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020
";
+ if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030
";
+ if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940
";
+ if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950
";
+ if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990
";
+
+ // Test string formating
+ print "
Testing date formating
"; + $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003'; + $s1 = date($fmt,0); + $s2 = adodb_date($fmt,0); + if ($s1 != $s2) { + print " date() 0 failed";
+ $pos = strcmp($s1,$s2);
+
+ if (($s1) != ($s2)) {
+ for ($j=0,$k=strlen($s1); $j < $k; $j++) {
+ if ($s1[$j] != $s2[$j]) {
+ print substr($s1,$j).' ';
+ break;
+ }
+ }
+ print "Error date(): $ts
+ \"$s1\" (date len=".strlen($s1).")
+ \"$s2\" (adodb_date len=".strlen($s2).")
";
+ $fail = true;
+ }
+
+ $a1 = getdate($ts);
+ $a2 = adodb_getdate($ts);
+ $rez = array_diff($a1,$a2);
+ if (sizeof($rez)>0) {
+ print "Error getdate() $ts
";
+ print_r($a1);
+ print "
";
+ print_r($a2);
+ print "
"; + $fail = true; + } + } + + // Test generation of dates outside 1901-2038 + print "
Testing random dates between 100 and 4000
"; + adodb_date_test_date(100,1); + for ($i=100; --$i >= 0;) { + $y1 = 100+rand(0,1970-100); + $m = rand(1,12); + adodb_date_test_date($y1,$m); + + $y1 = 3000-rand(0,3000-1970); + adodb_date_test_date($y1,$m); + } + print ''; + $start = 1960+rand(0,10); + $yrs = 12; + $i = 365.25*86400*($start-1970); + $offset = 36000+rand(10000,60000); + $max = 365*$yrs*86400; + $lastyear = 0; + + // we generate a timestamp, convert it to a date, and convert it back to a timestamp + // and check if the roundtrip broke the original timestamp value. + print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; + + for ($max += $i; $i < $max; $i += $offset) { + $ret = adodb_date('m,d,Y,H,i,s',$i); + $arr = explode(',',$ret); + if ($lastyear != $arr[2]) { + $lastyear = $arr[2]; + print " $lastyear "; + flush(); + } + $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); + if ($i != $newi) { + print "Error at $i, adodb_mktime returned $newi ($ret)"; + $fail = true; + break; + } + } + + if (!$fail) print "
Passed !
"; + else print "Failed :-(
"; +} + +/** + Returns day of week, 0 = Sunday,... 6=Saturday. + Algorithm from PEAR::Date_Calc +*/ +function adodb_dow($year, $month, $day) +{ +/* +Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and +proclaimed that from that time onwards 3 days would be dropped from the calendar +every 400 years. + +Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). +*/ + if ($year <= 1582) { + if ($year < 1582 || + ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; + else + $greg_correction = 0; + } else + $greg_correction = 0; + + if($month > 2) + $month -= 2; + else { + $month += 10; + $year--; + } + + $day = ( floor((13 * $month - 1) / 5) + + $day + ($year % 100) + + floor(($year % 100) / 4) + + floor(($year / 100) / 4) - 2 * + floor($year / 100) + 77); + + return (($day - 7 * floor($day / 7))) + $greg_correction; +} + + +/** + Checks for leap year, returns true if it is. No 2-digit year check. Also + handles julian calendar correctly. +*/ +function _adodb_is_leap_year($year) +{ + if ($year % 4 != 0) return false; + + if ($year % 400 == 0) { + return true; + // if gregorian calendar (>1582), century not-divisible by 400 is not leap + } else if ($year > 1582 && $year % 100 == 0 ) { + return false; + } + + return true; +} + +/** + checks for leap year, returns true if it is. Has 2-digit year check +*/ +function adodb_is_leap_year($year) +{ + return _adodb_is_leap_year(adodb_year_digit_check($year)); +} + +/** + Fix 2-digit years. Works for any century. + Assumes that if 2-digit is more than 30 years in future, then previous century. +*/ +function adodb_year_digit_check($y) +{ + if ($y < 100) { + + $yr = (integer) date("Y"); + $century = (integer) ($yr /100); + + if ($yr%100 > 50) { + $c1 = $century + 1; + $c0 = $century; + } else { + $c1 = $century; + $c0 = $century - 1; + } + $c1 *= 100; + // if 2-digit year is less than 30 years in future, set it to this century + // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. + if (($y + $c1) < $yr+30) $y = $y + $c1; + else $y = $y + $c0*100; + } + return $y; +} + +/** + get local time zone offset from GMT +*/ +function adodb_get_gmt_different() +{ +static $DIFF; + if (isset($DIFF)) return $DIFF; + + $DIFF = mktime(0,0,0,1,2,1970) - gmmktime(0,0,0,1,2,1970); + return $DIFF; +} + +/** + Returns an array with date info. +*/ +function adodb_getdate($d=false,$fast=false) +{ + if ($d === false) return getdate(); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return @getdate($d); + } + } + return _adodb_getdate($d); +} + +/** + Low-level function that returns the getdate() array. We have a special + $fast flag, which if set to true, will return fewer array values, + and is much faster as it does not calculate dow, etc. +*/ +function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) +{ + $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_different()); + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + if ($d < 0) { + $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 + for ($a = 1970 ; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) { + $d += $_day_power * 366; + } else + $d += $_day_power * 365; + if ($d >= 0) { + $year = $a; + break; + } + } + + $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; + + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 13 ; --$a > 0;) { + $lastd = $d; + $d += $mtab[$a] * $_day_power; + if ($d >= 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + + $d = $lastd; + $day = $ndays + ceil(($d+1) / ($_day_power)); + + $d += ($ndays - $day+1)* $_day_power; + $hour = floor($d/$_hour_power); + + } else { + + for ($a = 1970 ;; $a++) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) { + $d -= $_day_power * 366; + } else + $d -= $_day_power * 365; + if ($d < 0) { + $year = $a; + break; + } + } + $secsInYear = $lastd; + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 1 ; $a <= 12; $a++) { + $lastd = $d; + $d -= $mtab[$a] * $_day_power; + if ($d <= 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + $d = $lastd; + $day = ceil(($d+1) / $_day_power); + $d = $d - ($day-1) * $_day_power; + $hour = floor($d /$_hour_power); + } + + $d -= $hour * $_hour_power; + $min = floor($d/$_min_power); + $secs = $d - $min * $_min_power; + if ($fast) { + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'leap' => $leaf, + 'ndays' => $ndays + ); + } + + + $dow = adodb_dow($year,$month,$day); + + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'wday' => $dow, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'weekday' => gmdate('l',$_day_power*(3+$dow)), + 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + 0 => $origd + ); +} + +function adodb_gmdate($fmt,$d=false) +{ + return adodb_date($fmt,$d,true); +} + +function adodb_date2($fmt, $d=false, $is_gmt=false) +{ + if ($d !== false) { + 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}))?|", + ($d), $rr)) return adodb_date($fmt,false,$is_gmt); + + if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt); + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + } + + return adodb_date($fmt,$d,$is_gmt); +} + +/** + Return formatted date based on timestamp $d +*/ +function adodb_date($fmt,$d=false,$is_gmt=false) +{ + if ($d === false) return date($fmt); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return @date($fmt,$d); + } + } + $_day_power = 86400; + + $arr = _adodb_getdate($d,true,$is_gmt); + $year = $arr['year']; + $month = $arr['mon']; + $day = $arr['mday']; + $hour = $arr['hours']; + $min = $arr['minutes']; + $secs = $arr['seconds']; + + $max = strlen($fmt); + $dates = ''; + + /* + at this point, we have the following integer vars to manipulate: + $year, $month, $day, $hour, $min, $secs + */ + for ($i=0; $i < $max; $i++) { + switch($fmt[$i]) { + case 'T': $dates .= date('T');break; + // YEAR + case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; + case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 + + $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.' '; + + if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; + + if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; + + if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; + + $gmt = adodb_get_gmt_different(); + $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; + + case 'Y': $dates .= $year; break; + case 'y': $dates .= substr($year,strlen($year)-2,2); break; + // MONTH + case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; + case 'Q': $dates .= ($month+3)>>2; break; + case 'n': $dates .= $month; break; + case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; + case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; + // DAY + case 't': $dates .= $arr['ndays']; break; + case 'z': $dates .= $arr['yday']; break; + case 'w': $dates .= adodb_dow($year,$month,$day); break; + case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'j': $dates .= $day; break; + case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; + case 'S': + $d10 = $day % 10; + if ($d10 == 1) $dates .= 'st'; + else if ($d10 == 2) $dates .= 'nd'; + else if ($d10 == 3) $dates .= 'rd'; + else $dates .= 'th'; + break; + + // HOUR + case 'Z': + $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_different(); break; + case 'O': + $gmt = ($is_gmt) ? 0 : adodb_get_gmt_different(); + $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; + + case 'H': + if ($hour < 10) $dates .= '0'.$hour; + else $dates .= $hour; + break; + case 'h': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + + if ($hh < 10) $dates .= '0'.$hh; + else $dates .= $hh; + break; + + case 'G': + $dates .= $hour; + break; + + case 'g': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + $dates .= $hh; + break; + // MINUTES + case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; + // SECONDS + case 'U': $dates .= $d; break; + case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; + // AM/PM + // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM + case 'a': + if ($hour>=12) $dates .= 'pm'; + else $dates .= 'am'; + break; + case 'A': + if ($hour>=12) $dates .= 'PM'; + else $dates .= 'AM'; + break; + default: + $dates .= $fmt[$i]; break; + // ESCAPE + case "\\": + $i++; + if ($i < $max) $dates .= $fmt[$i]; + break; + } + } + return $dates; +} + +/** + Returns a timestamp given a GMT/UTC time. + Note that $is_dst is not implemented and is ignored. +*/ +function adodb_gmmktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false) +{ + return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); +} + +/** + Return a timestamp given a local time. Originally by jackbbs. + Note that $is_dst is not implemented and is ignored. +*/ +function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false) +{ + if (!defined('ADODB_TEST_DATES')) { + // for windows, we don't check 1970 because with timezone differences, + // 1 Jan 1970 could generate negative timestamp, which is illegal + if (!defined('ADODB_NO_NEGATIVE_TS') || ($year >= 1971)) + if (1901 < $year && $year < 2038) + return @mktime($hr,$min,$sec,$mon,$day,$year); + } + + $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_different(); + + $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; + } + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + $_total_date = 0; + if ($year >= 1970) { + for ($a = 1970 ; $a <= $year; $a++) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a < $year) { + $_total_date += $_add_date; + } else { + for($b=1;$b<$mon;$b++) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date +=$day-1; + $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; + + } else { + for ($a = 1969 ; $a >= $year; $a--) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a > $year) { $_total_date += $_add_date; + } else { + for($b=12;$b>$mon;$b--) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date += $loop_table[$mon] - $day; + + $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; + $_day_time = $_day_power - $_day_time; + $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); + if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction + else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582. + } + //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; + return $ret; +} + +?> \ No newline at end of file diff --git a/lib/adodb/adodb-time.zip b/lib/adodb/adodb-time.zip new file mode 100644 index 0000000000..ac2b4a857d Binary files /dev/null and b/lib/adodb/adodb-time.zip differ diff --git a/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/Changelog b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/Changelog new file mode 100644 index 0000000000..aeabe1d8fa --- /dev/null +++ b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/Changelog @@ -0,0 +1,43 @@ +2003-05-03 14:20 richtl + + * INSTALL, xmlschema.html: Renamed adodb-xmlschema.php to + adodb-xmlschema.inc.php in the docs. + +2003-05-03 14:17 richtl + + * adodb-xmlschema.inc.php, adodb-xmlschema.php: Renamed + adodb-xmlschema.php to adodb-xmlschema.inc.php to fit in with the + ADODB standard. + +2003-05-03 14:16 richtl + + * xmlschema.html: Fixed a doc bug in the example. + +2003-05-03 14:15 richtl + + * example.php, example.xml: Initial add to CVS + +2003-05-03 13:46 richtl + + * adodb-xmlschema.php, xmlschema.html, INSTALL, LICENSE, README, + xmlschema.dtd, docs/blank.html, docs/classtrees_xmlschema.html, + docs/elementindex.html, docs/elementindex_xmlschema.html, + docs/errors.html, docs/index.html, docs/li_xmlschema.html, + docs/packages.html, docs/media/bg_left.png, + docs/media/stylesheet.css, + docs/xmlschema/_adodb-xmlschema_php.html, + docs/xmlschema/adoSchema.html, + docs/xmlschema/package_xmlschema.html: Initial import + +2003-05-03 13:46 richtl + + * adodb-xmlschema.php, xmlschema.html, INSTALL, LICENSE, README, + xmlschema.dtd, docs/blank.html, docs/classtrees_xmlschema.html, + docs/elementindex.html, docs/elementindex_xmlschema.html, + docs/errors.html, docs/index.html, docs/li_xmlschema.html, + docs/packages.html, docs/media/bg_left.png, + docs/media/stylesheet.css, + docs/xmlschema/_adodb-xmlschema_php.html, + docs/xmlschema/adoSchema.html, + docs/xmlschema/package_xmlschema.html: Initial revision + diff --git a/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/INSTALL b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/INSTALL new file mode 100644 index 0000000000..27355847ff --- /dev/null +++ b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/INSTALL @@ -0,0 +1,8 @@ +INSTALL + +To install adodb-xmlschema, simply copy the adodb-xmlschema.inc.php file into your ADODB directory. + +------------------------------------------------------------------------------------------------------------------------------------ +If you have any questions or comments, please email them to me at richtl@arscognita.com. + +$Id$ \ No newline at end of file diff --git a/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/LICENSE b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/LICENSE new file mode 100644 index 0000000000..d15af7a1e5 --- /dev/null +++ b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/LICENSE @@ -0,0 +1,544 @@ +adodb-xmlschema is dual licensed using BSD-Style and LGPL. Where there is any di +screpancy, the BSD-Style license will take precedence. In plain English, you do +not need to distribute your application in source code form, nor do you need to + distribute adodb-xmlschema source code, provided you follow the rest of terms o +f the BSD-style license. + +Commercial use of adodb-xmlschema is encouraged. Make money and multiply! + +BSD Style-License +================= + +Copyright (c) 2003 ars Cognita, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, + +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this l +ist of conditions and the following disclaimer in the documentation and/or other + materials provided with the distribution. +Neither the name of the John Lim nor the names of its contributors may be used t +o endorse or promote products derived from this software without specific prior +written permission. + +DISCLAIMER: +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WA +RRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIREC +T, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR P +ROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWI +SE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE P +OSSIBILITY OF SUCH DAMAGE. + +========================================================== + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + +Written by Richard Tango-Lowy.
+For more information, contact richtl@arscognita.com +or visit our site at www.arscognita.com.
+At the moment, you should report bugs by mailing them to me. (If I can't convince John to +make this part of ADODB :-), I'll create a project for it on SourceForge.) + +
adodb-xmlschema is a class that allows the user to quickly and easily +build a database on any ADOdb-supported platform using a simple XML format.
+This library is dual-licensed under a BSD-style license and under the GNU Lesser Public License. +See the LICENSE file for more information.
+ +To install adodb-xmlschema, simply copy the adodb-xmlschema.php file into your +ADODB directory.
+ +First, create an XML database schema. Let's call it "schema.xml:"
+<?xml version="1.0"?> +<schema> + <table name="mytable"> + <field name="row1" type="I"> + <descr>An integer row that's a primary key and autoincrements</descr> + <KEY/> + <AUTOINCREMENT/> + </field> + <field name="row2" type="C" size="16"> + <descr>A 16 character varchar row that can't be null</descr> + <NOTNULL/> + </field> + </table> + <index name="myindex" table="mytable"> + <col>row1</col> + <col>row2</col> + </index> + <sql> + <descr>SQL to be executed only on specific platforms</descr> + <query platform="postgres|postgres7"> + insert into mytable ( row1, row2 ) values ( 12, 'stuff' ) + </query> + <query platform="mysql"> + insert into mytable ( row1, row2 ) values ( 12, 'different stuff' ) + </query> + </sql> +</schema> +
Create a new database using the appropriate tool for your platform. +Executing the following PHP code will create the a mytable and myindex +in the database and insert two rows into mytable.
+// To build the schema, start by creating a normal ADOdb connection: +$db->NewADOConnection( 'mysql' ); +$db->Connect( ... ); + +// Create the schema object and build the query array. +$schema = new adoSchema( $db ); + +// Build the SQL array +$sql = $schema->ParseSchema( "schema.xml" ); + +// Execute the SQL on the database +$result = $schema->ExecuteSchema( $sql ); + +// Finally, clean up after the XML parser +// (PHP won't do this for you!) +$schema->Destroy(); ++ +
(See ADOdb_schema.dtd for the full specification)
++<?xml version="1.0"?> +<schema> + <table name="tablename" platform="platform1|platform2|..."> + <descr>Optional description</descr> + <field name="fieldname" type="datadict_type" size="size"> + <KEY/> + <NOTNULL/> + <AUTOINCREMENT/> + <DEFAULT value="value"/> + </field> + ... more fields + </table> + ... more tables + + <index name="indexname" platform="platform1|platform2|..."> + <descr>Optional description</descr> + <col>fieldname</col> + ... more columns + </index> + ... more indices + + <sql platform="platform1|platform2|..."> + <descr>Optional description</descr> + <query platform="platform1|platform2|...">SQL query</query> + ... more queries + </sql> + ... more SQL + </schema> ++
Thanks to John Lim for giving us ADODB, and for the hard work that keeps it on top of things. +And particulary for the datadict code that made xmlschema possible.
+And to the kind folks at PHP Documentor. Cool tool.
+And to Linus. I thought the end of Amiga was the end of computing. Guess I was wrong :-)
+$Id$
\ No newline at end of file diff --git a/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/docs/classtrees_xmlschema.html b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/docs/classtrees_xmlschema.html new file mode 100644 index 0000000000..b2f326bc51 --- /dev/null +++ b/lib/adodb/adodb-xmlschema-0.0.1-snap20030511/docs/classtrees_xmlschema.html @@ -0,0 +1,28 @@ + + + + + + +
+
+
+top +
| ||
adodb-xmlschema.php | procedural page adodb-xmlschema.php | |
adoSchema | in file adodb-xmlschema.php, method adoSchema::adoSchema() Constructor. | |
adoSchema | in file adodb-xmlschema.php, class adoSchema Loads and parses an XML file, creating an array of "ready-to-run" SQL statements | |
+top +
| ||
$dbconn | in file adodb-xmlschema.php, variable adoSchema::$dbconn | |
$dbType | in file adodb-xmlschema.php, variable adoSchema::$dbType | |
$dict | in file adodb-xmlschema.php, variable adoSchema::$dict | |
Destroy | in file adodb-xmlschema.php, method adoSchema::Destroy() Destructor | |
+top +
| ||
ExecuteSchema | in file adodb-xmlschema.php, method adoSchema::ExecuteSchema() Loads a schema into the database | |
+top +
| ||
ParseSchema | in file adodb-xmlschema.php, method adoSchema::ParseSchema() Loads and parses an XML file | |
+top +
| ||
$sqlArray | in file adodb-xmlschema.php, variable adoSchema::$sqlArray | |
+top +
| ||
$xmlParser | in file adodb-xmlschema.php, variable adoSchema::$xmlParser |
+top +
| ||
adodb-xmlschema.php | procedural page adodb-xmlschema.php | |
adoSchema | in file adodb-xmlschema.php, method adoSchema::adoSchema() Constructor. | |
adoSchema | in file adodb-xmlschema.php, class adoSchema Loads and parses an XML file, creating an array of "ready-to-run" SQL statements | |
+top +
| ||
$dbconn | in file adodb-xmlschema.php, variable adoSchema::$dbconn | |
$dbType | in file adodb-xmlschema.php, variable adoSchema::$dbType | |
$dict | in file adodb-xmlschema.php, variable adoSchema::$dict | |
Destroy | in file adodb-xmlschema.php, method adoSchema::Destroy() Destructor | |
+top +
| ||
ExecuteSchema | in file adodb-xmlschema.php, method adoSchema::ExecuteSchema() Loads a schema into the database | |
+top +
| ||
+top +
| ||
ParseSchema | in file adodb-xmlschema.php, method adoSchema::ParseSchema() Loads and parses an XML file | |
+top +
| ||
$sqlArray | in file adodb-xmlschema.php, variable adoSchema::$sqlArray | |
+top +
| ||
$xmlParser | in file adodb-xmlschema.php, variable adoSchema::$xmlParser |
Written by Richard Tango-Lowy.
+For more information, contact richtl@arscognita.com +or visit our site at www.arscognita.com.
+At the moment, you should report bugs by mailing them to me. (If I can't convince John to +make this part of ADODB :-), I'll create a project for it on SourceForge.) + +
adodb-xmlschema is a class that allows the user to quickly and easily +build a database using the excellent +ADODB database library and a simple +XML formatted file.
+This library is dual-licensed under a BSD-style license and under the GNU Lesser Public License. +See the LICENSE file for more information.
+ +To install adodb-xmlschema, simply copy the adodb-xmlschema.inc.php file into your +ADODB directory.
+ +First, create an XML database schema. Let's call it "schema.xml:"
+<?xml version="1.0"?> +<schema> + <table name="mytable"> + <field name="row1" type="I"> + <descr>An integer row that's a primary key and autoincrements</descr> + <KEY/> + <AUTOINCREMENT/> + </field> + <field name="row2" type="C" size="16"> + <descr>A 16 character varchar row that can't be null</descr> + <NOTNULL/> + </field> + </table> + <index name="myindex" table="mytable"> + <col>row1</col> + <col>row2</col> + </index> + <sql> + <descr>SQL to be executed only on specific platforms</descr> + <query platform="postgres|postgres7"> + insert into mytable ( row1, row2 ) values ( 12, 'stuff' ) + </query> + <query platform="mysql"> + insert into mytable ( row1, row2 ) values ( 12, 'different stuff' ) + </query> + </sql> +</schema> +
Create a new database using the appropriate tool for your platform. +Executing the following PHP code will create the a mytable and myindex +in the database and insert one row into mytable if the platform is postgres or mysql.
+// To build the schema, start by creating a normal ADOdb connection: +$db->NewADOConnection( 'mysql' ); +$db->Connect( ... ); + +// Create the schema object and build the query array. +$schema = new adoSchema( $db ); + +// Build the SQL array +$sql = $schema->ParseSchema( "schema.xml" ); + +// Execute the SQL on the database +$result = $schema->ExecuteSchema( $sql ); + +// Finally, clean up after the XML parser +// (PHP won't do this for you!) +$schema->Destroy(); ++ +
(See ADOdb_schema.dtd for the full specification)
++<?xml version="1.0"?> +<schema> + <table name="tablename" platform="platform1|platform2|..."> + <descr>Optional description</descr> + <field name="fieldname" type="datadict_type" size="size"> + <KEY/> + <NOTNULL/> + <AUTOINCREMENT/> + <DEFAULT value="value"/> + </field> + ... more fields + </table> + ... more tables + + <index name="indexname" platform="platform1|platform2|..."> + <descr>Optional description</descr> + <col>fieldname</col> + ... more columns + </index> + ... more indices + + <sql platform="platform1|platform2|..."> + <descr>Optional description</descr> + <query platform="platform1|platform2|...">SQL query</query> + ... more queries + </sql> + ... more SQL + </schema> ++
Thanks to John Lim for giving us ADODB, and for the hard work that keeps it on top of things. +And particulary for the datadict code that made xmlschema possible.
+And to the kind folks at PHP Documentor. Cool tool.
+And to Linus. I thought the end of Amiga was the end of computing. Guess I was wrong :-)
+$Id$
\ No newline at end of file diff --git a/lib/adodb/adodb-xmlschema.inc.php b/lib/adodb/adodb-xmlschema.inc.php index 9debc392e9..e86b62b23f 100644 --- a/lib/adodb/adodb-xmlschema.inc.php +++ b/lib/adodb/adodb-xmlschema.inc.php @@ -1,722 +1,1201 @@ -tableName = $name; - } - - /** - * Adds a field to a table object - * - * $name is the name of the table to which the field should be added. - * $type is an ADODB datadict field type. The following field types - * are supported as of ADODB 3.40: - * - C: varchar - * - X: CLOB (character large object) or largest varchar size - * if CLOB is not supported - * - C2: Multibyte varchar - * - X2: Multibyte CLOB - * - B: BLOB (binary large object) - * - D: Date (some databases do not support this, and we return a datetime type) - * - T: Datetime or Timestamp - * - L: Integer field suitable for storing booleans (0 or 1) - * - I: Integer (mapped to I4) - * - I1: 1-byte integer - * - I2: 2-byte integer - * - I4: 4-byte integer - * - I8: 8-byte integer - * - F: Floating point number - * - N: Numeric or decimal number - * - * @param string $name Name of the table to which the field will be added. - * @param string $type ADODB datadict field type. - * @param string $size Field size - * @param array $opts Field options array - * @return array Field specifier array - */ - function addField( $name, $type, $size = NULL, $opts = NULL ) { - - /* Set the field index so we know where we are */ - $this->currentField = $name; - - /* Set the field type (required) */ - $this->fieldSpec[$name]['TYPE'] = $type; - - /* Set the field size (optional) */ - if( isset( $size ) ) { - $this->fieldSpec[$name]['SIZE'] = $size; - } - - /* Set the field options */ - if( isset( $opts ) ) $this->fieldSpec[$name]['OPTS'] = $opts; - - /* Return array containing field specifier */ - return $this->fieldSpec; - } - - /** - * Adds a field option to the current field specifier - * - * This method adds a field option allowed by the ADOdb datadict - * and appends it to the given field. - * - * @param string $field Field name - * @param string $opt ADOdb field option - * @param mixed $value Field option value - * @return array Field specifier array - */ - function addFieldOpt( $field, $opt, $value = NULL ) { - - /* Add the option to the field specifier */ - if( $value === NULL ) { /* No value, so add only the option */ - $this->fieldSpec[$field]['OPTS'][] = $opt; - } else { /* Add the option and value */ - $this->fieldSpec[$field]['OPTS'][] = array( "$opt" => "$value" ); - } - - /* Return array containing field specifier */ - return $this->fieldSpec; - } - - /** - * Adds an option to the table - * - *This method takes a comma-separated list of table-level options - * and appends them to the table object. - * - * @param string $opt Table option - * @return string Option list - */ - function addTableOpt( $opt ) { - - $optlist = &$this->tableOpts; - $optlist ? $optlist .= ", $opt" : $optlist = $opt; - - /* Return the options list */ - return $optlist; - } - - /** - * Generates the SQL that will create the table in the database - * - * Returns SQL that will create the table represented by the object. - * - * @param object $dict ADOdb data dictionary - * @return array Array containing table creation SQL - */ - function create( $dict ) { - - /* Loop through the field specifier array, building the associative array for the field options */ - $fldarray = array(); - $i = 0; - - foreach( $this->fieldSpec as $field => $finfo ) { - $i++; - - /* Set an empty size if it isn't supplied */ - if( !isset( $finfo['SIZE'] ) ) $finfo['SIZE'] = ''; - - /* Initialize the field array with the type and size */ - $fldarray[$i] = array( $field, $finfo['TYPE'], $finfo['SIZE'] ); - - /* Loop through the options array and add the field options. */ - $opts = $finfo['OPTS']; - if( $opts ) { - foreach( $finfo['OPTS'] as $opt ) { - - if( is_array( $opt ) ) { /* Option has an argument. */ - $key = key( $opt ); - $value = $opt[key( $opt ) ]; - $fldarray[$i][$key] = $value; - } else { /* Option doesn't have arguments */ - array_push( $fldarray[$i], $opt ); - } - } - } - } - - /* Build table array */ - $sqlArray = $dict->CreateTableSQL( $this->tableName, $fldarray, $this->tableOpts ); - - /* Return the array containing the SQL to create the table */ - return $sqlArray; - } - - /** - * Destructor - */ - function destroy() { - unset( $this ); - } -} - -/** -* Creates an index object in ADOdb's datadict format -* -* This class stores information about a database index. As charactaristics -* of the index are loaded from the external source, methods and properties -* of this class are used to build up the index description in ADOdb's -* datadict format. -* -* @package xmlschema -* @access private -*/ -class dbIndex { - - /** - * @var string Index name - */ - var $indexName; - - /** - * @var string Name of the table this index is attached to - */ - var $tableName; - - /** - * @var array Indexed fields: Table columns included in this index - */ - var $fields; - - /** - * Constructor. Initialize the index and table names. - * - * @param string $name Index name - * @param string $table Name of indexed table - */ - function dbIndex( $name, $table ) { - $this->indexName = $name; - $this->tableName = $table; - } - - /** - * Adds a field to the index - * - * This method adds the specified column to an index. - * - * @param string $name Field name - * @return string Field list - */ - function addField( $name ) { - $fieldlist = &$this->fields; - $fieldlist ? $fieldlist .=" , $name" : $fieldlist = $name; - - /* Return the field list */ - return $fieldlist; - } - - /** - * Generates the SQL that will create the index in the database - * - * Returns SQL that will create the index represented by the object. - * - * @param object $dict ADOdb data dictionary object - * @return array Array containing index creation SQL - */ - function create( $dict ) { - - /* Build table array */ - $sqlArray = $dict->CreateIndexSQL( $this->indexName, $this->tableName, $this->fields ); - - /* Return the array containing the SQL to create the table */ - return $sqlArray; - } - - /** - * Destructor - */ - function destroy() { - unset( $this ); - } -} - -/** -* Creates the SQL to execute a list of provided SQL queries -* -* This class compiles a list of SQL queries specified in the external file. -* -* @package xmlschema -* @access private -*/ -class dbQuerySet { - - /** - * @var array List of SQL queries - */ - var $querySet; - - /** - * @var string String used to build of a query line by line - */ - var $query; - - /** - * Constructor. Initializes the queries array - */ - function dbQuerySet() { - $this->querySet = array(); - $this->query = ''; - } - - /** - * Appends a line to a query that is being built line by line - * - * $param string $data Line of SQL data or NULL to initialize a new query - */ - function buildQuery( $data = NULL ) { - isset( $data ) ? $this->query .= " " . trim( $data ) : $this->query = ''; - } - - /** - * Adds a completed query to the query list - * - * @return string SQL of added query - */ - function addQuery() { - - /* Push the query onto the query set array */ - $finishedQuery = $this->query; - array_push( $this->querySet, $finishedQuery ); - - /* Return the query set array */ - return $finishedQuery; - } - - /** - * Creates and returns the current query set - * - * @return array Query set - */ - function create() { - return $this->querySet; - } - - /** - * Destructor - */ - function destroy() { - unset( $this ); - } -} - - -/** -* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements -* -* This class is used to load and parse the XML file, to create an array of SQL statements -* that can be used to build a database, and to build the database using the SQL array. -* -* @package xmlschema -*/ -class adoSchema { - - /** - * @var array Array containing SQL queries to generate all objects - */ - var $sqlArray; - - /** - * @var object XML Parser object - */ - var $xmlParser; - - /** - * @var object ADOdb connection object - */ - var $dbconn; - - /** - * @var string Database type (platform) - */ - var $dbType; - - /** - * @var object ADOdb Data Dictionary - */ - var $dict; - - /** - * @var object Temporary dbTable object - * @access private - */ - var $table; - - /** - * @var object Temporary dbIndex object - * @access private - */ - var $index; - - /** - * @var object Temporary dbQuerySet object - * @access private - */ - var $querySet; - - /** - * @var string Current XML element - * @access private - */ - var $currentElement; - - /** - * @var long Original Magic Quotes Runtime value - * @access private - */ - var $mgq; - - /** - * Constructor. Initializes the xmlschema object - * - * @param object $dbconn ADOdb connection object - */ - function adoSchema( $dbconn ) { - - /* Initialize the environment */ - $this->mgq = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - - $this->dbconn = &$dbconn; - $this->dbType = $dbconn->databaseType; - $this->sqlArray = array(); - - /* Create an ADOdb dictionary object */ - $this->dict = NewDataDictionary( $dbconn ); - } - - /** - * Loads and parses an XML file - * - * This method accepts a path to an xmlschema-compliant XML file, - * loads it, parses it, and uses it to create the SQL to generate the objects - * described by the XML file. - * - * @param string $file XML file - * @return array Array of SQL queries, ready to execute - */ - function ParseSchema( $file ) { - - /* Create the parser */ - $this->xmlParser = &$xmlParser; - $xmlParser = xml_parser_create(); - xml_set_object( $xmlParser, &$this ); - - /* Initialize the XML callback functions */ - xml_set_element_handler( $xmlParser, "_xmlcb_startElement", "_xmlcb_endElement" ); - xml_set_character_data_handler( $xmlParser, "_xmlcb_cData" ); - - /* Open the file */ - if( !( $fp = fopen( $file, "r" ) ) ) { - die( "Unable to open file" ); - } - - /* Process the file */ - while( $data = fread( $fp, 4096 ) ) { - if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) { - die( sprint( "XML error: %s at line %d", - xml_error_string( xml_get_error_code( $xmlParser ) ), - xml_get_current_line_number( $xmlParser ) ) ); - } - } - - /* Return the array of queries */ - return $this->sqlArray; - } - - /** - * Loads a schema into the database - * - * Accepts an array of SQL queries generated by the parser - * and executes them. - * - * @param array $sqlArray Array of SQL statements - * @param boolean $continueOnErr Don't fail out if an error is encountered - * @return integer 0 if failed, 1 if errors, 2 if successful - */ - function ExecuteSchema( $sqlArray, $continueOnErr = TRUE ) { - $err = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr ); - - /* Return the success code */ - return $err; - } - - /** - * XML Callback to process start elements - * - * @access private - */ - function _xmlcb_startElement( $parser, $name, $attrs ) { - - $dbType = $this->dbType; - if( isset( $this->table ) ) $table = &$this->table; - if( isset( $this->index ) ) $index = &$this->index; - if( isset( $this->querySet ) ) $querySet = &$this->querySet; - $this->currentElement = $name; - - /* Process the element. Ignore unimportant elements. */ - if( in_array( trim( $name ), array( "SCHEMA", "DESCR", "COL", "CONSTRAINT" ) ) ) { - return FALSE; - } - - switch( $name ) { - - case "TABLE": /* Table element */ - if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) { - $this->table = new dbTable( $attrs['NAME'] ); - } else { - unset( $this->table ); - } - break; - - case "FIELD": /* Table field */ - if( isset( $this->table ) ) { - $fieldName = $attrs['NAME']; - $fieldType = $attrs['TYPE']; - isset( $attrs['SIZE'] ) ? $fieldSize = $attrs['SIZE'] : $fieldSize = NULL; - isset( $attrs['OPTS'] ) ? $fieldOpts = $attrs['OPTS'] : $fieldOpts = NULL; - $this->table->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts ); - } - break; - - case "KEY": /* Table field option */ - if( isset( $this->table ) ) { - $this->table->addFieldOpt( $this->table->currentField, 'KEY' ); - } - break; - - case "NOTNULL": /* Table field option */ - if( isset( $this->table ) ) { - $this->table->addFieldOpt( $this->table->currentField, 'NOTNULL' ); - } - break; - - case "AUTOINCREMENT": /* Table field option */ - if( isset( $this->table ) ) { - $this->table->addFieldOpt( $this->table->currentField, 'AUTOINCREMENT' ); - } - break; - - case "DEFAULT": /* Table field option */ - if( isset( $this->table ) ) { - $this->table->addFieldOpt( $this->table->currentField, 'DEFAULT', $attrs['VALUE'] ); - } - break; - - case "INDEX": /* Table index */ - if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) { - $this->index = new dbIndex( $attrs['NAME'], $attrs['TABLE'] ); - } else { - if( isset( $this->index ) ) unset( $this->index ); - } - break; - - case "SQL": /* Freeform SQL queryset */ - if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) { - $this->querySet = new dbQuerySet( $attrs ); - } else { - if( isset( $this->querySet ) ) unset( $this->querySet ); - } - break; - - case "QUERY": /* Queryset SQL query */ - if( isset( $this->querySet ) ) { - /* Ignore this query set if a platform is specified and it's different than the */ - /* current connection platform. */ - if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) { - $this->querySet->buildQuery(); - } else { - if( isset( $this->querySet->query ) ) unset( $this->querySet->query ); - } - } - break; - - default: - print "OPENING ELEMENT '$name'"; + if( isset( $title ) ) { + print ""; + } +} +?> \ No newline at end of file diff --git a/lib/adodb/adodb-xmlschema.zip b/lib/adodb/adodb-xmlschema.zip index c2614fa735..14e6a8f328 100644 Binary files a/lib/adodb/adodb-xmlschema.zip and b/lib/adodb/adodb-xmlschema.zip differ diff --git a/lib/adodb/adodb.inc.php b/lib/adodb/adodb.inc.php index 4840107c04..b43546eb0b 100644 --- a/lib/adodb/adodb.inc.php +++ b/lib/adodb/adodb.inc.php @@ -1,3354 +1,3604 @@ - - Manual is at http://php.weblogs.com/adodb_manual - - */ - - if (!defined('_ADODB_LAYER')) { - define('_ADODB_LAYER',1); - - /* ============================================================================================== */ - /* CONSTANT DEFINITIONS */ - /* ============================================================================================== */ - - define('ADODB_BAD_RS','$title
"; + } + if( isset( $this ) ) { + print "[" . get_class( $this ) . "] "; + } + if( is_array( $msg ) or is_object( $msg ) ) { + print_r( $msg ); + print "
"; + } else { + print "$msg
"; + } + print "
Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;
'); - - define('ADODB_FETCH_DEFAULT',0); - define('ADODB_FETCH_NUM',1); - define('ADODB_FETCH_ASSOC',2); - define('ADODB_FETCH_BOTH',3); - - /* - Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. - This currently works only with mssql, odbc, oci8po and ibase derived drivers. - - 0 = assoc lowercase field names. $rs->fields['orderid'] - 1 = assoc uppercase field names. $rs->fields['ORDERID'] - 2 = use native-case field names. $rs->fields['OrderID'] - */ - if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); - - /* allow [ ] @ ` and . in table names */ - define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)'); - - - if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); - - /** - * Set ADODB_DIR to the directory where this file resides... - * This constant was formerly called $ADODB_RootPath - */ - if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__)); - - if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); - - /* ============================================================================================== */ - /* GLOBAL VARIABLES */ - /* ============================================================================================== */ - - GLOBAL - $ADODB_vers, /* database version */ - $ADODB_Database, /* last database driver used */ - $ADODB_COUNTRECS, /* count number of records returned - slows down query */ - $ADODB_CACHE_DIR, /* directory to cache recordsets */ - $ADODB_EXTENSION, /* ADODB extension installed */ - $ADODB_COMPAT_PATCH, /* If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF */ - $ADODB_FETCH_MODE; /* DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... */ - - /* ============================================================================================== */ - /* GLOBAL SETUP */ - /* ============================================================================================== */ - - if (strnatcmp(PHP_VERSION,'4.3.0')>=0) { - define('ADODB_PHPVER',0x4300); - } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) { - define('ADODB_PHPVER',0x4200); - } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { - define('ADODB_PHPVER',0x4050); - } else { - define('ADODB_PHPVER',0x4000); - } - $ADODB_EXTENSION = defined('ADODB_EXTENSION'); - /* if (extension_loaded('dbx')) define('ADODB_DBX',1); */ - - /** - Accepts $src and $dest arrays, replacing string $data - */ - function ADODB_str_replace($src, $dest, $data) - { - if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); - - $s = reset($src); - $d = reset($dest); - while ($s !== false) { - $data = str_replace($s,$d,$data); - $s = next($src); - $d = next($dest); - } - return $data; - } - - function ADODB_Setup() - { - GLOBAL - $ADODB_vers, /* database version */ - $ADODB_Database, /* last database driver used */ - $ADODB_COUNTRECS, /* count number of records returned - slows down query */ - $ADODB_CACHE_DIR, /* directory to cache recordsets */ - $ADODB_FETCH_MODE; - - $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; - - if (!isset($ADODB_CACHE_DIR)) { - $ADODB_CACHE_DIR = '/tmp'; - } else { - /* do not accept url based paths, eg. http:/ or ftp:/ */ - if (strpos($ADODB_CACHE_DIR,':/* ') !== false) - die("Illegal path http:/* or ftp://"); - } - - - /* Initialize random number generator for randomizing cache flushes */ - srand(((double)microtime())*1000000); - - /** - * Name of last database driver loaded into memory. Set by ADOLoadCode(). - */ - $ADODB_Database = ''; - - /** - * ADODB version as a string. - */ - $ADODB_vers = 'V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved. Released BSD & LGPL.'; - - /** - * Determines whether recordset->RecordCount() is used. - * Set to false for highest performance -- RecordCount() will always return -1 then - * for databases that provide "virtual" recordcounts... - */ - $ADODB_COUNTRECS = true; - } - - - /* ============================================================================================== */ - /* CHANGE NOTHING BELOW UNLESS YOU ARE CODING */ - /* ============================================================================================== */ - - ADODB_Setup(); - - /* ============================================================================================== */ - /* CLASS ADOFieldObject */ - /* ============================================================================================== */ - /** - * Helper class for FetchFields -- holds info on a column - */ - class ADOFieldObject { - var $name = ''; - var $max_length=0; - var $type=""; - - /* additional fields by dannym... (danny_milo@yahoo.com) */ - var $not_null = false; - /* actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ */ - /* so we can as well make not_null standard (leaving it at "false" does not harm anyways) */ - - var $has_default = false; /* this one I have done only in mysql and postgres for now ... */ - /* others to come (dannym) */ - var $default_value; /* default, if any, and supported. Check has_default first. */ - } - - - - function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) - { - /* print "Errorno ($fn errno=$errno m=$errmsg) "; */ - - $thisConnection->_transOK = false; - if ($thisConnection->_oldRaiseFn) { - $fn = $thisConnection->_oldRaiseFn; - $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); - } - } - - /* ============================================================================================== */ - /* CLASS ADOConnection */ - /* ============================================================================================== */ - - /** - * Connection object. For connecting to databases, and executing queries. - */ - class ADOConnection { - /* */ - /* PUBLIC VARS */ - /* */ - var $dataProvider = 'native'; - var $databaseType = ''; /* / RDBMS currently in use, eg. odbc, mysql, mssql */ - var $database = ''; /* / Name of database to be used. */ - var $host = ''; /* / The hostname of the database server */ - var $user = ''; /* / The username which is used to connect to the database server. */ - var $password = ''; /* / Password for the username. For security, we no longer store it. */ - var $debug = false; /* / if set to true will output sql statements */ - var $maxblobsize = 256000; /* / maximum size of blobs or large text fields -- some databases die otherwise like foxpro */ - var $concat_operator = '+'; /* / default concat operator -- change to || for Oracle/Interbase */ - var $fmtDate = "'Y-m-d'"; /* / used by DBDate() as the default date format used by the database */ - var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /* / used by DBTimeStamp as the default timestamp fmt. */ - var $true = '1'; /* / string that represents TRUE for a database */ - var $false = '0'; /* / string that represents FALSE for a database */ - var $replaceQuote = "\\'"; /* / string to use to replace quotes */ - var $charSet=false; /* / character set to use - only for interbase */ - var $metaDatabasesSQL = ''; - var $metaTablesSQL = ''; - var $uniqueOrderBy = false; /* / All order by columns have to be unique */ - var $emptyDate = ' '; - /* -- */ - var $hasInsertID = false; /* / supports autoincrement ID? */ - var $hasAffectedRows = false; /* / supports affected rows for update/delete? */ - var $hasTop = false; /* / support mssql/access SELECT TOP 10 * FROM TABLE */ - var $hasLimit = false; /* / support pgsql/mysql SELECT * FROM TABLE LIMIT 10 */ - var $readOnly = false; /* / this is a readonly database - used by phpLens */ - var $hasMoveFirst = false; /* / has ability to run MoveFirst(), scrolling backwards */ - var $hasGenID = false; /* / can generate sequences using GenID(); */ - var $hasTransactions = true; /* / has transactions */ - /* -- */ - var $genID = 0; /* / sequence id used by GenID(); */ - var $raiseErrorFn = false; /* / error function to call */ - var $upperCase = false; /* / uppercase function to call for searching/where */ - var $isoDates = false; /* / accepts dates in ISO format */ - var $cacheSecs = 3600; /* / cache for 1 hour */ - var $sysDate = false; /* / name of function that returns the current date */ - var $sysTimeStamp = false; /* / name of function that returns the current timestamp */ - var $arrayClass = 'ADORecordSet_array'; /* / name of class used to generate array recordsets, which are pre-downloaded recordsets */ - - var $noNullStrings = false; /* / oracle specific stuff - if true ensures that '' is converted to ' ' */ - var $numCacheHits = 0; - var $numCacheMisses = 0; - var $pageExecuteCountRows = true; - var $uniqueSort = false; /* / indicates that all fields in order by must be unique */ - var $leftOuter = false; /* / operator to use for left outer join in WHERE clause */ - var $rightOuter = false; /* / operator to use for right outer join in WHERE clause */ - var $ansiOuter = false; /* / whether ansi outer join syntax supported */ - var $autoRollback = false; /* autoRollback on PConnect(). */ - var $poorAffectedRows = false; /* affectedRows not working or unreliable */ - - var $fnExecute = false; - var $fnCacheExecute = false; - var $blobEncodeType = false; /* false=not required, 'I'=encode to integer, 'C'=encode to char */ - var $dbxDriver = false; - - /* */ - /* PRIVATE VARS */ - /* */ - var $_oldRaiseFn = false; - var $_transOK = null; - var $_connectionID = false; /* / The returned link identifier whenever a successful database connection is made. */ - var $_errorMsg = ''; /* / A variable which was used to keep the returned last error message. The value will */ - /* / then returned by the errorMsg() function */ - - var $_queryID = false; /* / This variable keeps the last created result link identifier */ - - var $_isPersistentConnection = false; /* / A boolean variable to state whether its a persistent connection or normal connection. */ - var $_bindInputArray = false; /* / set to true if ADOConnection.Execute() permits binding of array parameters. */ - var $autoCommit = true; /* / do not modify this yourself - actually private */ - var $transOff = 0; /* / temporarily disable transactions */ - var $transCnt = 0; /* / count of nested transactions */ - - var $fetchMode=false; - - /** - * Constructor - */ - function ADOConnection() - { - die('Virtual Class -- cannot instantiate'); - } - - /** - Get server version info... - - @returns An array with 2 elements: $arr['string'] is the description string, - and $arr[version] is the version (also a string). - */ - function ServerInfo() - { - return array('description' => '', 'version' => ''); - } - - function _findvers($str) - { - if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; - else return ''; - } - - /** - * All error messages go through this bottleneck function. - * You can define your own handler by defining the function name in ADODB_OUTP. - */ - function outp($msg,$newline=true) - { - global $HTTP_SERVER_VARS; - - if (defined('ADODB_OUTP')) { - $fn = ADODB_OUTP; - $fn($msg,$newline); - return; - } - - if ($newline) $msg .= "$ss
\nInsert_ID error
'); - return false; - } - - - /** - * Portable Insert ID. Pablo RocaAffected_Rows error
',false); - return false; - } - - - /** - * @return the last error message - */ - function ErrorMsg() - { - return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; - } - - - /** - * @return the last error number. Normally 0 means no error. - */ - function ErrorNo() - { - return ($this->_errorMsg) ? -1 : 0; - } - - function MetaError($err=false) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - if ($err === false) $err = $this->ErrorNo(); - return adodb_error($this->dataProvider,$this->databaseType,$err); - } - - function MetaErrorMsg($errno) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - return adodb_errormsg($errno); - } - - /** - * @returns an array with the primary key columns in it. - */ - function MetaPrimaryKeys($table, $owner=false) - { - /* owner not used in base class - see oci8 */ - $p = array(); - $objs =& $this->MetaColumns($table); - if ($objs) { - foreach($objs as $v) { - if (!empty($v->primary_key)) - $p[] = $v->name; - } - } - if (sizeof($p)) return $p; - return false; - } - - - /** - * Choose a database to connect to. Many databases do not support this. - * - * @param dbName is the name of the database to select - * @return true or false - */ - function SelectDB($dbName) - {return false;} - - - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) - * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) - * - * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) - * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @param [arg3] is a private parameter only used by jlim - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - */ - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0) - { - if ($this->hasTop && $nrows > 0) { - /* suggested by Reinhard Balling. Access requires top after distinct */ - /* Informix requires first before distinct - F Riosa */ - $ismssql = (strpos($this->databaseType,'mssql') !== false); - if ($ismssql) $isaccess = false; - else $isaccess = (strpos($this->databaseType,'access') !== false); - - if ($offset <= 0) { - - /* access includes ties in result */ - if ($isaccess) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - - if ($secs2cache>0) return $this->CacheExecute($secs2cache, $sql,$inputarr,$arg3); - else return $this->Execute($sql,$inputarr,$arg3); - } else if ($ismssql){ - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - } - } else { - $nn = $nrows + $offset; - if ($isaccess || $ismssql) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } - } - } - - /* if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows */ - /* 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. */ - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - if ($offset>0){ - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); - else $rs = &$this->Execute($sql,$inputarr,$arg3); - } else { - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); - else $rs = &$this->Execute($sql,$inputarr,$arg3); - } - $ADODB_COUNTRECS = $savec; - if ($rs && !$rs->EOF) { - return $this->_rs2rs($rs,$nrows,$offset); - } - /* print_r($rs); */ - return $rs; - } - - - /** - * Convert database recordset to an array recordset - * input recordset's cursor should be at beginning, and - * old $rs will be closed. - * - * @param rs the recordset to copy - * @param [nrows] number of rows to retrieve (optional) - * @param [offset] offset by number of rows (optional) - * @return the new recordset - */ - function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) - { - if (! $rs) return false; - - $dbtype = $rs->databaseType; - if (!$dbtype) { - $rs = &$rs; /* required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? */ - return $rs; - } - if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { - $rs->MoveFirst(); - $rs = &$rs; /* required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? */ - return $rs; - } - $flds = array(); - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - $flds[] = $rs->FetchField($i); - } - $arr =& $rs->GetArrayLimit($nrows,$offset); - /* print_r($arr); */ - if ($close) $rs->Close(); - - $arrayClass = $this->arrayClass; - - $rs2 = new $arrayClass(); - $rs2->connection = &$this; - $rs2->sql = $rs->sql; - $rs2->dataProvider = $this->dataProvider; - $rs2->InitArrayFields($arr,$flds); - return $rs2; - } - - - function &GetArray($sql, $inputarr=false) - { - return $this->GetAll($sql,$inputarr); - } - - /** - * Return first element of first row of sql statement. Recordset is disposed - * for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function GetOne($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $ret = false; - $rs = &$this->Execute($sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); - } - $ADODB_COUNTRECS = $crecs; - return $ret; - } - - function CacheGetOne($secs2cache,$sql=false,$inputarr=false) - { - $ret = false; - $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); - } - - return $ret; - } - - function GetCol($sql, $inputarr = false, $trim = false) - { - $rv = false; - $rs = &$this->Execute($sql, $inputarr); - if ($rs) { - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } - } - $rs->Close(); - } - return $rv; - } - - function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) - { - $rv = false; - $rs = &$this->CacheExecute($secs, $sql, $inputarr); - if ($rs) { - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } - } - $rs->Close(); - } - return $rv; - } - - /* - Calculate the offset of a date for a particular database and generate - appropriate SQL. Useful for calculating future/past dates and storing - in a database. - - If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. - */ - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - return '('.$date.'+'.$dayFraction.')'; - } - - - /** - * Return all rows. Compat with PEAR DB - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetAll($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->Execute($sql,$inputarr); - $ADODB_COUNTRECS = $savec; - - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } - - function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - $ADODB_COUNTRECS = $savec; - - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } - - - - /** - * Return one row of sql statement. Recordset is disposed for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetRow($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $rs = $this->Execute($sql,$inputarr); - - $ADODB_COUNTRECS = $crecs; - if ($rs) { - $arr = array(); - if (!$rs->EOF) $arr = $rs->fields; - $rs->Close(); - return $arr; - } - - return false; - } - - function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) - { - $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - $arr = false; - if (!$rs->EOF) $arr = $rs->fields; - $rs->Close(); - return $arr; - } - return false; - } - - /** - * Insert or replace a single record. Note: this is not the same as MySQL's replace. - * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. - * Also note that no table locking is done currently, so it is possible that the - * record be inserted twice by two programs... - * - * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); - * - * $table table name - * $fieldArray associative array of data (you must quote strings yourself). - * $keyCol the primary key field name or if compound key, array of field names - * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers - * but does not work with dates nor SQL functions. - * has_autoinc the primary key is an auto-inc field, so skip in insert. - * - * Currently blob replace not supported - * - * returns 0 = fail, 1 = update, 2 = insert - */ - - function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) - { - if (count($fieldArray) == 0) return 0; - $first = true; - $uSet = ''; - - if (!is_array($keyCol)) { - $keyCol = array($keyCol); - } - foreach($fieldArray as $k => $v) { - if ($autoQuote && !is_numeric($v) and substr($v,0,1) != "'" and strcasecmp($v,'null')!=0) { - $v = $this->qstr($v); - $fieldArray[$k] = $v; - } - if (in_array($k,$keyCol)) continue; /* skip UPDATE if is key */ - - if ($first) { - $first = false; - $uSet = "$k=$v"; - } else - $uSet .= ",$k=$v"; - } - - $first = true; - foreach ($keyCol as $v) { - if ($first) { - $first = false; - $where = "$v=$fieldArray[$v]"; - } else { - $where .= " and $v=$fieldArray[$v]"; - } - } - - if ($uSet) { - $update = "UPDATE $table SET $uSet WHERE $where"; - - $rs = $this->Execute($update); - if ($rs) { - if ($this->poorAffectedRows) { - /* - The Select count(*) wipes out any errors that the update would have returned. - http://phplens.com/lens/lensforum/msgs.php?id=5696 - */ - if ($this->ErrorNo()<>0) return 0; - - # affected_rows == 0 if update field values identical to old values - # for mysql - which is silly. - - $cnt = $this->GetOne("select count(*) from $table where $where"); - if ($cnt > 0) return 1; /* record already exists */ - } else - if (($this->Affected_Rows()>0)) return 1; - } - - } - /* print "Error=".$this->ErrorNo().'
'; */
- $first = true;
- foreach($fieldArray as $k => $v) {
- if ($has_autoinc && in_array($k,$keyCol)) continue; /* skip autoinc col */
-
- if ($first) {
- $first = false;
- $iCols = "$k";
- $iVals = "$v";
- } else {
- $iCols .= ",$k";
- $iVals .= ",$v";
- }
- }
- $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
- $rs = $this->Execute($insert);
- return ($rs) ? 2 : 0;
- }
-
-
- /**
- * Will select, getting rows from $offset (1-based), for $nrows.
- * This simulates the MySQL "select * from table limit $offset,$nrows" , and
- * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
- * MySQL and PostgreSQL parameter ordering is the opposite of the other.
- * eg.
- * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
- * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
- *
- * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
- *
- * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
- * @param sql
- * @param [offset] is the row to start calculations from (1-based)
- * @param [nrows] is the number of rows to get
- * @param [inputarr] array of bind variables
- * @param [arg3] is a private parameter only used by jlim
- * @return the recordset ($rs->databaseType == 'array')
- */
- function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false)
- {
- if (!is_numeric($secs2cache)) {
- if ($sql === false) $sql = -1;
- if ($offset == -1) $offset = false;
- /* sql, nrows, offset,inputarr,arg3 */
- return $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$inputarr,$this->cacheSecs);
- } else {
- if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
- return $this->SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
- }
- }
-
- /**
- * Flush cached recordsets that match a particular $sql statement.
- * If $sql == false, then we purge all files in the cache.
- */
- function CacheFlush($sql=false,$inputarr=false)
- {
- global $ADODB_CACHE_DIR;
-
- if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
- if (strpos(strtoupper(PHP_OS),'WIN') !== false) {
- $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
- } else {
- $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
- /* old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; */
- }
- if ($this->debug) {
- ADOConnection::outp( "CacheFlush: $cmd
\n", system($cmd),""); - } else { - exec($cmd); - } - return; - } - $f = $this->_gencachename($sql.serialize($inputarr),false); - adodb_write_file($f,''); /* is adodb_write_file needed? */ - @unlink($f); - } - - /** - * Private function to generate filename for caching. - * Filename is generated based on: - * - * - sql statement - * - database type (oci8, ibase, ifx, etc) - * - database name - * - userid - * - * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). - * Assuming that we can have 50,000 files per directory with good performance, - * then we can scale to 12.8 million unique cached recordsets. Wow! - */ - function _gencachename($sql,$createdir) - { - global $ADODB_CACHE_DIR; - - $m = md5($sql.$this->databaseType.$this->database.$this->user); - $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2); - if ($createdir && !file_exists($dir)) { - $oldu = umask(0); - if (!mkdir($dir,0771)) - if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); - umask($oldu); - } - return $dir.'/adodb_'.$m.'.cache'; - } - - - /** - * Execute SQL, caching recordsets. - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. - * This is an optional parameter. - * @param sql SQL statement to execute - * @param [inputarr] holds the input data to bind to - * @param [arg3] reserved for john lim for future use - * @return RecordSet or false - */ - function &CacheExecute($secs2cache,$sql=false,$inputarr=false,$arg3=false) - { - if (!is_numeric($secs2cache)) { - $arg3 = $inputarr; - $inputarr = $sql; - $sql = $secs2cache; - $secs2cache = $this->cacheSecs; - } - include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); - - $md5file = $this->_gencachename($sql.serialize($inputarr),true); - $err = ''; - - if ($secs2cache > 0){ - $rs = &csv2rs($md5file,$err,$secs2cache); - $this->numCacheHits += 1; - } else { - $err='Timeout 1'; - $rs = false; - $this->numCacheMisses += 1; - } - if (!$rs) { - /* no cached rs found */ - if ($this->debug) { - if (get_magic_quotes_runtime()) { - ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); - } - ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); - } - $rs = &$this->Execute($sql,$inputarr,$arg3); - if ($rs) { - $eof = $rs->EOF; - $rs = &$this->_rs2rs($rs); /* read entire recordset into memory immediately */ - $txt = _rs2serialize($rs,false,$sql); /* serialize */ - - if (!adodb_write_file($md5file,$txt,$this->debug)) { - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); - } - if ($this->debug) ADOConnection::outp( " Cache write error"); - } - if ($rs->EOF && !$eof) { - $rs->MoveFirst(); - /* $rs = &csv2rs($md5file,$err); */ - $rs->connection = &$this; /* Pablo suggestion */ - } - - } else - @unlink($md5file); - } else { - if ($this->fnCacheExecute) { - $fn = $this->fnCacheExecute; - $fn($this, $secs2cache, $sql, $inputarr); - } - /* ok, set cached object found */ - $rs->connection = &$this; /* Pablo suggestion */ - if ($this->debug){ - global $HTTP_SERVER_VARS; - - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); - $ttl = $rs->timeCreated + $secs2cache - time(); - $s = is_array($sql) ? $sql[0] : $sql; - if ($inBrowser) $s = ''.htmlspecialchars($s).''; - - ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); - } - } - return $rs; - } - - - /** - * Generates an Update Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table and sql should only - * be a simple select stmt with no groupby/orderby/limit - * - * "Jonathan Younger"
ADONewConnection: Unable to load database driver '$db'
",false); - - return false; - } - - $cls = 'ADODB_'.$ADODB_Database; - $obj =& new $cls(); - if ($errorfn) $obj->raiseErrorFn = $errorfn; - - return $obj; - } - - function &NewDataDictionary(&$conn) - { - $provider = $conn->dataProvider; - $drivername = $conn->databaseType; - if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') - $drivername = $conn->dataProvider; - 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': - case 'db2': - break; - default: - $drivername = 'generic'; - break; - } - } - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - include_once(ADODB_DIR.'/adodb-datadict.inc.php'); - $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; - - if (!file_exists($path)) { - ADOConnection::outp("Database driver '$path' not available"); - return false; - } - include_once($path); - $class = "ADODB2_$drivername"; - $dict =& new $class(); - $dict->dataProvider = $conn->dataProvider; - $dict->connection = &$conn; - $dict->upperName = strtoupper($drivername); - if (is_resource($conn->_connectionID)) - $dict->serverInfo = $conn->ServerInfo(); - - return $dict; - } - - - /** - * Save a file $filename and its $contents (normally for caching) with file locking - */ - function adodb_write_file($filename, $contents,$debug=false) - { - # http:/* www.php.net/bugs.php?id=9203 Bug that flock fails on Windows */ - # So to simulate locking, we assume that rename is an atomic operation. - # First we delete $filename, then we create a $tempfile write to it and - # rename to the desired $filename. If the rename works, then we successfully - # modified the file exclusively. - # What a stupid need - having to simulate locking. - # Risks: - # 1. $tempfile name is not unique -- very very low - # 2. unlink($filename) fails -- ok, rename will fail - # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs - # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated - if (strpos(strtoupper(PHP_OS),'WIN') !== false) { - /* skip the decimal place */ - $mtime = substr(str_replace(' ','_',microtime()),2); - /* unlink will let some latencies develop, so uniqid() is more random */ - @unlink($filename); - /* getmypid() actually returns 0 on Win98 - never mind! */ - $tmpname = $filename.uniqid($mtime).getmypid(); - if (!($fd = fopen($tmpname,'a'))) return false; - $ok = ftruncate($fd,0); - if (!fwrite($fd,$contents)) $ok = false; - fclose($fd); - chmod($tmpname,0644); - if (!@rename($tmpname,$filename)) { - unlink($tmpname); - $ok = false; - } - if (!$ok) { - if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); - } - return $ok; - } - if (!($fd = fopen($filename, 'a'))) return false; - if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { - $ok = fwrite( $fd, $contents ); - fclose($fd); - chmod($filename,0644); - }else { - fclose($fd); - if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename'; - $traceArr = debug_backtrace(); - array_shift($traceArr); - $tabs = sizeof($traceArr)-1; - - foreach ($traceArr as $arr) { - $args = array(); - for ($i=0; $i < $tabs; $i++) $s .= ' '; - $tabs -= 1; - $s .= ''; - if (isset($arr['class'])) $s .= $arr['class'].'.'; - if (isset($arr['args'])) - foreach($arr['args'] as $v) { - if (is_null($v)) $args[] = 'null'; - else if (is_array($v)) $args[] = 'Array['.sizeof($v).']'; - else if (is_object($v)) $args[] = 'Object:'.get_class($v); - else if (is_bool($v)) $args[] = $v ? 'true' : 'false'; - else { - $v = (string) @$v; - $str = htmlspecialchars(substr($v,0,$MAXSTRLEN)); - if (strlen($v) > $MAXSTRLEN) $str .= '...'; - $args[] = $str; - } - } - $s .= $arr['function'].'('.implode(', ',$args).')'; - $s .= @sprintf(" # line %4d, file: %s", - $arr['line'],$arr['file'],$arr['file']); - $s .= "\n"; - } - $s .= ''; - if ($print) print $s; - } - return $s; - } - -} /* defined */ -?> + + Manual is at http://php.weblogs.com/adodb_manual + + */ + + if (!defined('_ADODB_LAYER')) { + define('_ADODB_LAYER',1); + + //============================================================================================== + // CONSTANT DEFINITIONS + //============================================================================================== + + define('ADODB_BAD_RS','
Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;
'); + + define('ADODB_FETCH_DEFAULT',0); + define('ADODB_FETCH_NUM',1); + define('ADODB_FETCH_ASSOC',2); + define('ADODB_FETCH_BOTH',3); + + /* + Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. + This currently works only with mssql, odbc, oci8po and ibase derived drivers. + + 0 = assoc lowercase field names. $rs->fields['orderid'] + 1 = assoc uppercase field names. $rs->fields['ORDERID'] + 2 = use native-case field names. $rs->fields['OrderID'] + */ + //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + + // allow [ ] @ ` and . in table names + define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)'); + + + if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); + + /** + * Set ADODB_DIR to the directory where this file resides... + * This constant was formerly called $ADODB_RootPath + */ + if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__)); + + if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); + + //============================================================================================== + // GLOBAL VARIABLES + //============================================================================================== + + GLOBAL + $ADODB_vers, // database version + $ADODB_Database, // last database driver used + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_EXTENSION, // ADODB extension installed + $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF + $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... + + //============================================================================================== + // GLOBAL SETUP + //============================================================================================== + + if (strnatcmp(PHP_VERSION,'4.3.0')>=0) { + define('ADODB_PHPVER',0x4300); + } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) { + define('ADODB_PHPVER',0x4200); + } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { + define('ADODB_PHPVER',0x4050); + } else { + define('ADODB_PHPVER',0x4000); + } + $ADODB_EXTENSION = defined('ADODB_EXTENSION'); + //if (extension_loaded('dbx')) define('ADODB_DBX',1); + + /** + Accepts $src and $dest arrays, replacing string $data + */ + function ADODB_str_replace($src, $dest, $data) + { + if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); + + $s = reset($src); + $d = reset($dest); + while ($s !== false) { + $data = str_replace($s,$d,$data); + $s = next($src); + $d = next($dest); + } + return $data; + } + + function ADODB_Setup() + { + GLOBAL + $ADODB_vers, // database version + $ADODB_Database, // last database driver used + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_FETCH_MODE; + + $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; + + if (!isset($ADODB_CACHE_DIR)) { + $ADODB_CACHE_DIR = '/tmp'; + } else { + // do not accept url based paths, eg. http:/ or ftp:/ + if (strpos($ADODB_CACHE_DIR,'://') !== false) + die("Illegal path http:// or ftp://"); + } + + + // Initialize random number generator for randomizing cache flushes + srand(((double)microtime())*1000000); + + /** + * Name of last database driver loaded into memory. Set by ADOLoadCode(). + */ + $ADODB_Database = ''; + + /** + * ADODB version as a string. + */ + $ADODB_vers = 'V4.00 20 Oct 2003 (c) 2000-2003 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.'; + + /** + * Determines whether recordset->RecordCount() is used. + * Set to false for highest performance -- RecordCount() will always return -1 then + * for databases that provide "virtual" recordcounts... + */ + $ADODB_COUNTRECS = true; + } + + + //============================================================================================== + // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB + //============================================================================================== + + ADODB_Setup(); + + //============================================================================================== + // CLASS ADOFieldObject + //============================================================================================== + /** + * Helper class for FetchFields -- holds info on a column + */ + class ADOFieldObject { + var $name = ''; + var $max_length=0; + var $type=""; + + // additional fields by dannym... (danny_milo@yahoo.com) + var $not_null = false; + // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ + // so we can as well make not_null standard (leaving it at "false" does not harm anyways) + + var $has_default = false; // this one I have done only in mysql and postgres for now ... + // others to come (dannym) + var $default_value; // default, if any, and supported. Check has_default first. + } + + + + function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) + { + //print "Errorno ($fn errno=$errno m=$errmsg) "; + $thisConnection->_transOK = false; + if ($thisConnection->_oldRaiseFn) { + $fn = $thisConnection->_oldRaiseFn; + $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); + } + } + + //============================================================================================== + // CLASS ADOConnection + //============================================================================================== + + /** + * Connection object. For connecting to databases, and executing queries. + */ + class ADOConnection { + // + // PUBLIC VARS + // + var $dataProvider = 'native'; + var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql + var $database = ''; /// Name of database to be used. + var $host = ''; /// The hostname of the database server + var $user = ''; /// The username which is used to connect to the database server. + var $password = ''; /// Password for the username. For security, we no longer store it. + var $debug = false; /// if set to true will output sql statements + var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro + var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase + var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. + var $true = '1'; /// string that represents TRUE for a database + var $false = '0'; /// string that represents FALSE for a database + var $replaceQuote = "\\'"; /// string to use to replace quotes + var $charSet=false; /// character set to use - only for interbase + var $metaDatabasesSQL = ''; + var $metaTablesSQL = ''; + var $uniqueOrderBy = false; /// All order by columns have to be unique + var $emptyDate = ' '; + //-- + var $hasInsertID = false; /// supports autoincrement ID? + var $hasAffectedRows = false; /// supports affected rows for update/delete? + var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE + var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $readOnly = false; /// this is a readonly database - used by phpLens + var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards + var $hasGenID = false; /// can generate sequences using GenID(); + var $hasTransactions = true; /// has transactions + //-- + var $genID = 0; /// sequence id used by GenID(); + var $raiseErrorFn = false; /// error function to call + var $upperCase = false; /// uppercase function to call for searching/where + var $isoDates = false; /// accepts dates in ISO format + var $cacheSecs = 3600; /// cache for 1 hour + var $sysDate = false; /// name of function that returns the current date + var $sysTimeStamp = false; /// name of function that returns the current timestamp + var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets + + var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' + var $numCacheHits = 0; + var $numCacheMisses = 0; + var $pageExecuteCountRows = true; + var $uniqueSort = false; /// indicates that all fields in order by must be unique + var $leftOuter = false; /// operator to use for left outer join in WHERE clause + var $rightOuter = false; /// operator to use for right outer join in WHERE clause + var $ansiOuter = false; /// whether ansi outer join syntax supported + var $autoRollback = false; // autoRollback on PConnect(). + var $poorAffectedRows = false; // affectedRows not working or unreliable + + var $fnExecute = false; + var $fnCacheExecute = false; + var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char + var $rsPrefix = "ADORecordSet_"; + + var $autoCommit = true; /// do not modify this yourself - actually private + var $transOff = 0; /// temporarily disable transactions + var $transCnt = 0; /// count of nested transactions + + var $fetchMode=false; + // + // PRIVATE VARS + // + var $_oldRaiseFn = false; + var $_transOK = null; + var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. + var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will + /// then returned by the errorMsg() function + var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 + var $_queryID = false; /// This variable keeps the last created result link identifier + + var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ + var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. + var $_evalAll = false; + var $_affected = false; + var $_logsql = false; + + + + /** + * Constructor + */ + function ADOConnection() + { + die('Virtual Class -- cannot instantiate'); + } + + /** + Get server version info... + + @returns An array with 2 elements: $arr['string'] is the description string, + and $arr[version] is the version (also a string). + */ + function ServerInfo() + { + return array('description' => '', 'version' => ''); + } + + function _findvers($str) + { + if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; + else return ''; + } + + /** + * All error messages go through this bottleneck function. + * You can define your own handler by defining the function name in ADODB_OUTP. + */ + function outp($msg,$newline=true) + { + global $HTTP_SERVER_VARS; + + if (defined('ADODB_OUTP')) { + $fn = ADODB_OUTP; + $fn($msg,$newline); + return; + } + + if ($newline) $msg .= "$ss
\n$ss
\nInsert_ID error
'); + return false; + } + + + /** + * Portable Insert ID. Pablo RocaAffected_Rows error
',false); + return false; + } + + + /** + * @return the last error message + */ + function ErrorMsg() + { + return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + } + + + /** + * @return the last error number. Normally 0 means no error. + */ + function ErrorNo() + { + return ($this->_errorMsg) ? -1 : 0; + } + + function MetaError($err=false) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + if ($err === false) $err = $this->ErrorNo(); + return adodb_error($this->dataProvider,$this->databaseType,$err); + } + + function MetaErrorMsg($errno) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + return adodb_errormsg($errno); + } + + /** + * @returns an array with the primary key columns in it. + */ + function MetaPrimaryKeys($table, $owner=false) + { + // owner not used in base class - see oci8 + $p = array(); + $objs =& $this->MetaColumns($table); + if ($objs) { + foreach($objs as $v) { + if (!empty($v->primary_key)) + $p[] = $v->name; + } + } + if (sizeof($p)) return $p; + return false; + } + + /** + * @returns assoc array where keys are tables, and values are foreign keys + */ + function MetaForeignKeys($table, $owner=false, $upper=false) + { + return false; + } + /** + * Choose a database to connect to. Many databases do not support this. + * + * @param dbName is the name of the database to select + * @return true or false + */ + function SelectDB($dbName) + {return false;} + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) + * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) + * + * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) + * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + { + if ($this->hasTop && $nrows > 0) { + // suggested by Reinhard Balling. Access requires top after distinct + // Informix requires first before distinct - F Riosa + $ismssql = (strpos($this->databaseType,'mssql') !== false); + if ($ismssql) $isaccess = false; + else $isaccess = (strpos($this->databaseType,'access') !== false); + + if ($offset <= 0) { + + // access includes ties in result + if ($isaccess) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + + if ($secs2cache>0) { + $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr); + } else { + $ret =& $this->Execute($sql,$inputarr); + } + return $ret; // PHP5 fix + } else if ($ismssql){ + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + } + } else { + $nn = $nrows + $offset; + if ($isaccess || $ismssql) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } + } + } + + // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows + // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + if ($offset>0){ + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } else { + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } + $ADODB_COUNTRECS = $savec; + if ($rs && !$rs->EOF) { + $rs =& $this->_rs2rs($rs,$nrows,$offset); + } + //print_r($rs); + return $rs; + } + + + /** + * Convert database recordset to an array recordset + * input recordset's cursor should be at beginning, and + * old $rs will be closed. + * + * @param rs the recordset to copy + * @param [nrows] number of rows to retrieve (optional) + * @param [offset] offset by number of rows (optional) + * @return the new recordset + */ + function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) + { + if (! $rs) return false; + + $dbtype = $rs->databaseType; + if (!$dbtype) { + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? + return $rs; + } + if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { + $rs->MoveFirst(); + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? + return $rs; + } + $flds = array(); + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + $flds[] = $rs->FetchField($i); + } + $arr =& $rs->GetArrayLimit($nrows,$offset); + //print_r($arr); + if ($close) $rs->Close(); + + $arrayClass = $this->arrayClass; + + $rs2 =& new $arrayClass(); + $rs2->connection = &$this; + $rs2->sql = $rs->sql; + $rs2->dataProvider = $this->dataProvider; + $rs2->InitArrayFields($arr,$flds); + return $rs2; + } + + /* + * Return all rows. Compat with PEAR DB + */ + function &GetAll($sql, $inputarr=false) + { + $arr =& $this->GetArray($sql,$inputarr); + return $arr; + } + + function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) + { + $rs =& $this->Execute($sql, $inputarr); + if (!$rs) return false; + + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) + { + if (!is_numeric($secs2cache)) { + $first2cols = $force_array; + $force_array = $inputarr; + } + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + if (!$rs) return false; + + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + /** + * Return first element of first row of sql statement. Recordset is disposed + * for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetOne($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $ret = false; + $rs = &$this->Execute($sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + $ADODB_COUNTRECS = $crecs; + return $ret; + } + + function CacheGetOne($secs2cache,$sql=false,$inputarr=false) + { + $ret = false; + $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + + return $ret; + } + + function GetCol($sql, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) + { + $rv = false; + $rs = &$this->CacheExecute($secs, $sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + /* + Calculate the offset of a date for a particular database and generate + appropriate SQL. Useful for calculating future/past dates and storing + in a database. + + If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. + */ + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + return '('.$date.'+'.$dayFraction.')'; + } + + + /** + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetArray($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->Execute($sql,$inputarr); + $ADODB_COUNTRECS = $savec; + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + $ADODB_COUNTRECS = $savec; + + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; + + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + + + /** + * Return one row of sql statement. Recordset is disposed for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetRow($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $rs =& $this->Execute($sql,$inputarr); + + $ADODB_COUNTRECS = $crecs; + if ($rs) { + $arr = array(); + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + + return false; + } + + function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) + { + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + $arr = false; + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + return false; + } + + /** + * Insert or replace a single record. Note: this is not the same as MySQL's replace. + * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. + * Also note that no table locking is done currently, so it is possible that the + * record be inserted twice by two programs... + * + * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); + * + * $table table name + * $fieldArray associative array of data (you must quote strings yourself). + * $keyCol the primary key field name or if compound key, array of field names + * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers + * but does not work with dates nor SQL functions. + * has_autoinc the primary key is an auto-inc field, so skip in insert. + * + * Currently blob replace not supported + * + * returns 0 = fail, 1 = update, 2 = insert + */ + + function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) + { + if (count($fieldArray) == 0) return 0; + $first = true; + $uSet = ''; + + if (!is_array($keyCol)) { + $keyCol = array($keyCol); + } + foreach($fieldArray as $k => $v) { + if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) { + $v = $this->qstr($v); + $fieldArray[$k] = $v; + } + if (in_array($k,$keyCol)) continue; // skip UPDATE if is key + + if ($first) { + $first = false; + $uSet = "$k=$v"; + } else + $uSet .= ",$k=$v"; + } + + $first = true; + foreach ($keyCol as $v) { + if ($first) { + $first = false; + $where = "$v=$fieldArray[$v]"; + } else { + $where .= " and $v=$fieldArray[$v]"; + } + } + + if ($uSet) { + $update = "UPDATE $table SET $uSet WHERE $where"; + + $rs = $this->Execute($update); + if ($rs) { + if ($this->poorAffectedRows) { + /* + The Select count(*) wipes out any errors that the update would have returned. + http://phplens.com/lens/lensforum/msgs.php?id=5696 + */ + if ($this->ErrorNo()<>0) return 0; + + # affected_rows == 0 if update field values identical to old values + # for mysql - which is silly. + + $cnt = $this->GetOne("select count(*) from $table where $where"); + if ($cnt > 0) return 1; // record already exists + } else + if (($this->Affected_Rows()>0)) return 1; + } + + } + // print "Error=".$this->ErrorNo().'
';
+ $first = true;
+ foreach($fieldArray as $k => $v) {
+ if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
+
+ if ($first) {
+ $first = false;
+ $iCols = "$k";
+ $iVals = "$v";
+ } else {
+ $iCols .= ",$k";
+ $iVals .= ",$v";
+ }
+ }
+ $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
+ $rs = $this->Execute($insert);
+ return ($rs) ? 2 : 0;
+ }
+
+
+ /**
+ * Will select, getting rows from $offset (1-based), for $nrows.
+ * This simulates the MySQL "select * from table limit $offset,$nrows" , and
+ * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
+ * MySQL and PostgreSQL parameter ordering is the opposite of the other.
+ * eg.
+ * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
+ * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
+ *
+ * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
+ *
+ * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
+ * @param sql
+ * @param [offset] is the row to start calculations from (1-based)
+ * @param [nrows] is the number of rows to get
+ * @param [inputarr] array of bind variables
+ * @return the recordset ($rs->databaseType == 'array')
+ */
+ function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
+ {
+ if (!is_numeric($secs2cache)) {
+ if ($sql === false) $sql = -1;
+ if ($offset == -1) $offset = false;
+ // sql, nrows, offset,inputarr
+ $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$inputarr,$this->cacheSecs);
+ } else {
+ if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
+ $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+ }
+ return $rs;
+ }
+
+ /**
+ * Flush cached recordsets that match a particular $sql statement.
+ * If $sql == false, then we purge all files in the cache.
+ */
+ function CacheFlush($sql=false,$inputarr=false)
+ {
+ global $ADODB_CACHE_DIR;
+
+ if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
+ if (strncmp(PHP_OS,'WIN',3) === 0) {
+ $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
+ } else {
+ $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
+ // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
+ }
+ if ($this->debug) {
+ ADOConnection::outp( "CacheFlush: $cmd
\n", system($cmd),""); + } else { + exec($cmd); + } + return; + } + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); + } + } + + /** + * Private function to generate filename for caching. + * Filename is generated based on: + * + * - sql statement + * - database type (oci8, ibase, ifx, etc) + * - database name + * - userid + * + * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). + * Assuming that we can have 50,000 files per directory with good performance, + * then we can scale to 12.8 million unique cached recordsets. Wow! + */ + function _gencachename($sql,$createdir) + { + global $ADODB_CACHE_DIR; + + $m = md5($sql.$this->databaseType.$this->database.$this->user); + $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2); + if ($createdir && !file_exists($dir)) { + $oldu = umask(0); + if (!mkdir($dir,0771)) + if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); + umask($oldu); + } + return $dir.'/adodb_'.$m.'.cache'; + } + + + /** + * Execute SQL, caching recordsets. + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. + * This is an optional parameter. + * @param sql SQL statement to execute + * @param [inputarr] holds the input data to bind to + * @return RecordSet or false + */ + function &CacheExecute($secs2cache,$sql=false,$inputarr=false) + { + if (!is_numeric($secs2cache)) { + $inputarr = $sql; + $sql = $secs2cache; + $secs2cache = $this->cacheSecs; + } + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + + if (is_array($sql)) $sql = $sql[0]; + + $md5file = $this->_gencachename($sql.serialize($inputarr),true); + $err = ''; + + if ($secs2cache > 0){ + $rs = &csv2rs($md5file,$err,$secs2cache); + $this->numCacheHits += 1; + } else { + $err='Timeout 1'; + $rs = false; + $this->numCacheMisses += 1; + } + if (!$rs) { + // no cached rs found + if ($this->debug) { + if (get_magic_quotes_runtime()) { + ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); + } + if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); + } + $rs = &$this->Execute($sql,$inputarr); + if ($rs) { + $eof = $rs->EOF; + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + $txt = _rs2serialize($rs,false,$sql); // serialize + + if (!adodb_write_file($md5file,$txt,$this->debug)) { + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + } + if ($this->debug) ADOConnection::outp( " Cache write error"); + } + if ($rs->EOF && !$eof) { + $rs->MoveFirst(); + //$rs = &csv2rs($md5file,$err); + $rs->connection = &$this; // Pablo suggestion + } + + } else + @unlink($md5file); + } else { + $this->_errorMsg = ''; + $this->_errorCode = 0; + + if ($this->fnCacheExecute) { + $fn = $this->fnCacheExecute; + $fn($this, $secs2cache, $sql, $inputarr); + } + // ok, set cached object found + $rs->connection = &$this; // Pablo suggestion + if ($this->debug){ + global $HTTP_SERVER_VARS; + + $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + $ttl = $rs->timeCreated + $secs2cache - time(); + $s = is_array($sql) ? $sql[0] : $sql; + if ($inBrowser) $s = ''.htmlspecialchars($s).''; + + ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); + } + } + return $rs; + } + + + /** + * Generates an Update Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table and sql should only + * be a simple select stmt with no groupby/orderby/limit + * + * "Jonathan Younger"
ADONewConnection: Unable to load database driver '$db'
",false); + + return false; + } + + $cls = 'ADODB_'.$ADODB_Database; + $obj =& new $cls(); + if ($errorfn) $obj->raiseErrorFn = $errorfn; + + return $obj; + } + + // $perf == true means called by NewPerfMonitor() + function _adodb_getdriver($provider,$drivername,$perf=false) + { + if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') + $drivername = $provider; + else { + if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5); + else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4); + else + switch($drivername) { + case 'oracle': $drivername = 'oci8';break; + //case 'sybase': $drivername = 'mssql';break; + case 'access': + if ($perf) $drivername = ''; + break; + case 'db2': + if ($perf) break; + default: + $drivername = 'generic'; + break; + } + } + + return $drivername; + } + + function &NewPerfMonitor(&$conn) + { + $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); + if (!$drivername || $drivername == 'generic') return false; + include_once(ADODB_DIR.'/adodb-perf.inc.php'); + @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php"); + $class = "Perf_$drivername"; + if (!class_exists($class)) return false; + $perf =& new $class($conn); + + return $perf; + } + + function &NewDataDictionary(&$conn) + { + $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + include_once(ADODB_DIR.'/adodb-datadict.inc.php'); + $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; + + if (!file_exists($path)) { + ADOConnection::outp("Database driver '$path' not available"); + return false; + } + include_once($path); + $class = "ADODB2_$drivername"; + $dict =& new $class(); + $dict->dataProvider = $conn->dataProvider; + $dict->connection = &$conn; + $dict->upperName = strtoupper($drivername); + if (is_resource($conn->_connectionID)) + $dict->serverInfo = $conn->ServerInfo(); + + return $dict; + } + + + /** + * Save a file $filename and its $contents (normally for caching) with file locking + */ + function adodb_write_file($filename, $contents,$debug=false) + { + # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows + # So to simulate locking, we assume that rename is an atomic operation. + # First we delete $filename, then we create a $tempfile write to it and + # rename to the desired $filename. If the rename works, then we successfully + # modified the file exclusively. + # What a stupid need - having to simulate locking. + # Risks: + # 1. $tempfile name is not unique -- very very low + # 2. unlink($filename) fails -- ok, rename will fail + # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs + # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated + if (strncmp(PHP_OS,'WIN',3) === 0) { + // skip the decimal place + $mtime = substr(str_replace(' ','_',microtime()),2); + // unlink will let some latencies develop, so uniqid() is more random + @unlink($filename); + // getmypid() actually returns 0 on Win98 - never mind! + $tmpname = $filename.uniqid($mtime).getmypid(); + if (!($fd = fopen($tmpname,'a'))) return false; + $ok = ftruncate($fd,0); + if (!fwrite($fd,$contents)) $ok = false; + fclose($fd); + chmod($tmpname,0644); + if (!@rename($tmpname,$filename)) { + unlink($tmpname); + $ok = false; + } + if (!$ok) { + if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); + } + return $ok; + } + if (!($fd = fopen($filename, 'a'))) return false; + if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { + $ok = fwrite( $fd, $contents ); + fclose($fd); + chmod($filename,0644); + }else { + fclose($fd); + if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename\n";print_r($var);echo "\n"; + } + + function adodb_backtrace($print=true,$levels=9999) + { + $s = ''; + if (PHPVERSION() >= 4.3) { + + $MAXSTRLEN = 64; + + $s = '
'; + $traceArr = debug_backtrace(); + array_shift($traceArr); + $tabs = sizeof($traceArr)-1; + + foreach ($traceArr as $arr) { + $levels -= 1; + if ($levels < 0) break; + + $args = array(); + for ($i=0; $i < $tabs; $i++) $s .= ' '; + $tabs -= 1; + $s .= ''; + if (isset($arr['class'])) $s .= $arr['class'].'.'; + if (isset($arr['args'])) + foreach($arr['args'] as $v) { + if (is_null($v)) $args[] = 'null'; + else if (is_array($v)) $args[] = 'Array['.sizeof($v).']'; + else if (is_object($v)) $args[] = 'Object:'.get_class($v); + else if (is_bool($v)) $args[] = $v ? 'true' : 'false'; + else { + $v = (string) @$v; + $str = htmlspecialchars(substr($v,0,$MAXSTRLEN)); + if (strlen($v) > $MAXSTRLEN) $str .= '...'; + $args[] = $str; + } + } + $s .= $arr['function'].'('.implode(', ',$args).')'; + $s .= @sprintf(" %% line %4d, file: %s", + $arr['line'],$arr['file'],$arr['file']); + $s .= "\n"; + } + $s .= ''; + if ($print) print $s; + } + return $s; + } + + +} // defined +?> \ No newline at end of file diff --git a/lib/adodb/crypt.inc.php b/lib/adodb/crypt.inc.php index 57e8894fa9..b99bbba551 100644 --- a/lib/adodb/crypt.inc.php +++ b/lib/adodb/crypt.inc.php @@ -1,5 +1,5 @@ */ +// Session Encryption by Ari Kuorikoski
V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim#natsoft.com.my)
-This software is dual licensed using BSD-Style and LGPL. Where - there is any discrepancy, the BSD-Style license will take precedence. This - means you can use it in proprietary and commercial products.
+V4.00 20 Oct 2003 (c) 2000-2003 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.
+Useful ADOdb links: Download Other Docs +
Introduction
Unique Features
How People are using ADOdb
Feature Requests and Bug Reports
- Installation
- Initializing Code ADONewConnection
+ Installation
+ Initializing Code and Connection Examples
+ Hacking ADOdb Safely
+ ADONewConnection
NewADOConnection
Supported Databases
Tutorial
@@ -43,67 +46,74 @@
Pivot Tables
Variables: $ADODB_COUNTRECS
- $ADODB_CACHE_DIR $ADODB_FETCH_MODE $ADODB_LANG
- Constants: ADODB_ASSOC_CASE
-
- ADOConnection
- Connections: Connect PConnect
- NConnect
- Executing SQL: Execute CacheExecute
- SelectLimit CacheSelectLimit
- Prepare PrepareSP Parameter
-
- GetOne CacheGetOne
- GetRow CacheGetRow
- GetAll CacheGetAll
- GetCol CacheGetCol
- Replace
- ExecuteCursor
- (oci8 only)
- Generates SQL: GetUpdateSQL GetInsertSQL
- Blobs: UpdateBlob UpdateClob
- UpdateBlobFile BlobEncode
- BlobDecode
- Paging/Scrolling: PageExecute CachePageExecute
- Cleanup: CacheFlush Close
- Transactions: BeginTrans CommitTrans
- RollbackTrans StartTrans CompleteTrans
- Fetching Data: SetFetchMode
- Strings: concat qstr quote
- Dates: DBDate DBTimeStamp
- UnixDate UnixTimeStamp
- OffsetDate SQLDate
- Rows Management: Affected_Rows Insert_ID
- GenID CreateSequence DropSequence
-
- Error Handling: ErrorMsg ErrorNo
- MetaError MetaErrorMsg
- Data Dictionary (metadata): MetaDatabases MetaTables
- MetaColumns MetaColumnNames
- MetaPrimaryKeys ServerInfo
-
- Statistics and Query-Rewriting: fnExecute and fnCacheExecute
- Deprecated: Bind BlankRecordSet
-
- ADORecordSet
- Returns one row:FetchRow FetchInto
- FetchObject FetchNextObject
- FetchObj FetchNextObj
- Returns all rows:GetArray GetRows
- GetAssoc
- Scrolling:Move MoveNext MoveFirst
- MoveLast AbsolutePosition CurrentRow
- AtFirstPage AtLastPage
- AbsolutePage
- Menu generation:GetMenu GetMenu2
- Dates:UserDate UserTimeStamp
- UnixDate UnixTimeStamp
- Recordset Info:RecordCount PO_RecordSet
- NextRecordSet
- Field Info:FieldCount FetchField
- MetaType
- Cleanup: Close
- Deprecated: GetRowAssoc Fields
+ $ADODB_CACHE_DIR $ADODB_FETCH_MODE
+ $ADODB_LANG
+ Constants: ADODB_ASSOC_CASE
+
+ ADOConnection
+ Connections: Connect PConnect
+ NConnect
+ Executing SQL: Execute CacheExecute
+ SelectLimit CacheSelectLimit
+ Param Prepare PrepareSP
+ Parameter
+ GetOne
+ CacheGetOne GetRow CacheGetRow
+ GetAll CacheGetAll GetCol
+ CacheGetCol GetAssoc CacheGetAssoc Replace
+
+ ExecuteCursor
+ (oci8 only)
+ Generates SQL strings: GetUpdateSQL GetInsertSQL
+ IfNull Concat Param
+ OffsetDate SQLDate
+ DBDate DBTimeStamp
+ Blobs: UpdateBlob UpdateClob
+ UpdateBlobFile BlobEncode
+ BlobDecode
+ Paging/Scrolling: PageExecute CachePageExecute
+ Cleanup: CacheFlush Close
+ Transactions: StartTrans CompleteTrans
+ FailTrans HasFailedTrans
+ BeginTrans CommitTrans
+ RollbackTrans
+ Fetching Data: SetFetchMode
+ Strings: concat qstr quote
+ Dates: DBDate DBTimeStamp UnixDate
+ UnixTimeStamp OffsetDate
+ SQLDate
+ Row Management: Affected_Rows Insert_ID
+ GenID CreateSequence DropSequence
+
+ Error Handling: ErrorMsg ErrorNo
+ MetaError MetaErrorMsg
+ Data Dictionary (metadata): MetaDatabases MetaTables
+ MetaColumns MetaColumnNames
+ MetaPrimaryKeys MetaForeignKeys
+ ServerInfo
+ Statistics and Query-Rewriting: LogSQL fnExecute
+ and fnCacheExecute
+ Deprecated: Bind BlankRecordSet
+
+ ADORecordSet
+ Returns one row:FetchRow FetchInto
+ FetchObject FetchNextObject
+ FetchObj FetchNextObj
+ Returns all rows:GetArray GetRows
+ GetAssoc
+ Scrolling:Move MoveNext MoveFirst
+ MoveLast AbsolutePosition CurrentRow
+ AtFirstPage AtLastPage
+ AbsolutePage
+ Menu generation:GetMenu GetMenu2
+ Dates:UserDate UserTimeStamp
+ UnixDate UnixTimeStamp
+ Recordset Info:RecordCount PO_RecordSet
+ NextRecordSet
+ Field Info:FieldCount FetchField
+ MetaType
+ Cleanup: Close
+ Deprecated: GetRowAssoc Fields
rs2html example
Differences between ADOdb and ADO
Database Driver Guide
@@ -115,8 +125,8 @@
API's (encapsulate the differences) so we can easily switch databases. PHP 4.0.5 or later
is now required (because we use array-based str_replace).
We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, Informix, - PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access, ADO and ODBC. We have had successful reports of connecting - to Progress and DB2 via ODBC. We hope more people + PostgreSQL, FrontBase, SQLite, Interbase (Firebird and Borland variants), Foxpro, Access, ADO, DB2, SAP DB and ODBC. + We have had successful reports of connecting to Progress and CacheLite via ODBC. We hope more people 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.
@@ -135,7 +145,9 @@ such as CHAR, TEXT and STRING are equivalent in different databases.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.
-You will use $conn->Connect()
or
-$conn->PConnect()
to perform the actual connection.
See the examples below in the Tutorial.
- + +At this point, you are not connected to the database. 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, +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, +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(). +
MySQL connections are very straightforward, and the parameters are identical + to mysql_connect:
++ $conn = &ADONewConnection('mysql'); + $conn->PConnect('localhost','userid','password','database'); ++
Most other database drivers use a similar convention: Connect($server, $user, $password, $database). Exceptions are listed below. +
PostgreSQL accepts connections using:
+a. the standard connection string:
++ $conn = &ADONewConnection('postgres7'); + $conn->PConnect('host=localhost port=5432 dbname=mary');+
b. the classical 4 parameters:
++ $conn->PConnect('localhost','userid','password','database'); ++
+ $conn = &ADONewConnection('ibase'); + $conn->PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey'); ++ +
With Oracle, you can connect in multiple ways.
+a. PHP and Oracle reside on the same machine, use default SID.
+$conn->Connect(false, 'scott', 'tiger');+
b. TNS Name defined, eg. 'TNSDB'
+$conn->PConnect(false, 'scott', 'tiger', TNSDB'); ++
or
+$conn->PConnect('TNSDB', 'scott', 'tiger');+
c. Host address and SID
+$conn->Connect('192.168.0.1', 'scott', 'tiger', 'SID');+
d. Host address and Service Name
+$conn->Connect('192.168.0.1', 'scott', 'tiger', 'servicename');+ +
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); ++For Microsoft SQL Server: +
+ $db =& ADONewConnection('odbc_mssql'); + $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;"; + $db->Connect($dsn,'userid','password'); ++DSN-less Connections with ADO
+<?php + include('adodb.inc.php'); + ADOLoadCode("ado_mssql"); + $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(); + print_r($arr); +?> ++ + +
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 +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. +If you want to use the default ADOdb drivers return false. + +
+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.
Name | -Tested | -Database | -RecordCount() usable | -Prerequisites | -Operating Systems | +Name | +Tested | +Database | +RecordCount() usable | +Prerequisites | +Operating Systems |
access | -B | -Microsoft Access/Jet. You need to create an ODBC DSN. | -Y/N | -ODBC | -Windows only | +access | +B | +Microsoft Access/Jet. You need to create an ODBC DSN. | +Y/N | +ODBC | +Windows only |
ado | -B | -Generic ADO, not tuned for specific databases. Allows - DSN-less connections. For best performance, use an OLEDB provider. - This is the base class for all ado drivers. -You can set $db->codePage before connecting. |
- ? depends on database | -ADO or OLEDB provider | -Windows only | +ado | +B | +Generic ADO, not tuned for specific databases. Allows + DSN-less connections. For best performance, use an OLEDB provider. This + is the base class for all ado drivers. +You can set $db->codePage before connecting. |
+ ? depends on database | +ADO or OLEDB provider | +Windows only |
ado_access | -B | -Microsoft Access/Jet using ADO. Allows DSN-less connections. - For best performance, use an OLEDB provider. | -Y/N | -ADO or OLEDB provider | -Windows only | +ado_access | +B | +Microsoft Access/Jet using ADO. Allows DSN-less connections. + For best performance, use an OLEDB provider. | +Y/N | +ADO or OLEDB provider | +Windows only |
ado_mssql | -B | -Microsoft SQL Server using ADO. Allows DSN-less connections. - For best performance, use an OLEDB provider. | -Y/N | -ADO or OLEDB provider | -Windows only | +ado_mssql | +B | +Microsoft SQL Server using ADO. Allows DSN-less connections. + For best performance, use an OLEDB provider. | +Y/N | +ADO or OLEDB provider | +Windows only |
db2 | -A | -DB2. Should work reliably as based on ODBC - driver. | -Y/N | -DB2 CLI/ODBC interface | -
- Unix and Windows. Unix - install hints. - |
+ db2 | +A | +DB2. Should work reliably as based on ODBC + driver. | +Y/N | +DB2 CLI/ODBC interface | + Unix and Windows. Unix + install hints. |
vfp | -A | -Microsoft Visual FoxPro. You need to create an ODBC DSN. | -Y/N | -ODBC | -Windows only | +vfp | +A | +Microsoft Visual FoxPro. You need to create an ODBC DSN. | +Y/N | +ODBC | +Windows only |
fbsql | -C | -FrontBase. | -Y | -? | -
- Unix and Windows - |
+ fbsql | +C | +FrontBase. | +Y | +? | + Unix and Windows |
ibase | -B | -Interbase 6 or earlier. Some users report you might need
- to use this - $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 Windows | +ibase | +B | +Interbase 6 or earlier. Some users report you might need
+ to use this + $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 Windows |
firebird | -C | -Firebird version of interbase. | -Y/N | -Interbase client | -Unix and Windows | +firebird | +C | +Firebird version of interbase. | +Y/N | +Interbase client | +Unix and Windows |
borland_ibase | -C | -Borland version of Interbase 6.5 or later. Very sad that - the forks differ. | -Y/N | -Interbase client | -Unix and Windows | +borland_ibase | +C | +Borland version of Interbase 6.5 or later. Very sad that + the forks differ. | +Y/N | +Interbase client | +Unix and Windows |
informix72 | -C | -Informix databases before Informix 7.3 that do no support - SELECT FIRST. | -Y/N | -Informix client | -Unix and Windows | +informix72 | +C | +Informix databases before Informix 7.3 that do no support + SELECT FIRST. | +Y/N | +Informix client | +Unix and Windows |
informix | -C | -Generic informix driver. | -Y/N | -Informix client | -Unix and Windows | +informix | +C | +Generic informix driver. | +Y/N | +Informix client | +Unix and Windows |
mssql | -A | -
- Microsoft SQL Server 7 and later. Works with Microsoft SQL Server - 2000 also. Note that date formating is problematic with this driver. For - example, the PHP mssql extension does not return the seconds for datetime! - |
- Y/N | -Mssql client | -
- Unix and Windows. |
+ mssql | +A | + Microsoft SQL Server 7 and later. Works + with Microsoft SQL Server 2000 also. Note that date formating is problematic + with this driver. For example, the PHP mssql extension does not return + the seconds for datetime! |
+ Y/N | +Mssql client | + Unix and Windows. |
mssqlpo | -A | -
- Portable mssql driver. Identical to above mssql driver, - except that '||', the concatenation operator, is converted to '+'. Useful - for porting scripts from most other sql variants that use ||. - |
- Y/N | -Mssql client | -
- Unix and Windows. |
+ ||||||
mssqlpo | +A | + Portable mssql driver. Identical to above + mssql driver, except that '||', the concatenation operator, is converted + to '+'. Useful for porting scripts from most other sql variants that use + ||. |
+ Y/N | +Mssql client | + Unix and Windows. |
||||||
mysql | -A | -MySQL without transaction support. You can also set - $db->clientFlags before connecting. | -Y/N | -MySQL client | -Unix and Windows | +mysql | +A | +MySQL without transaction support. You can also set $db->clientFlags + before connecting. | +Y/N | +MySQL client | +Unix and Windows |
mysqlt or maxsql | -A | -
- MySQL with transaction support. We recommend using ||
- as the concat operator for best portability. This can be done by running
- MySQL using: |
- Y/N | -MySQL client | -Unix and Windows | +mysqlt or maxsql | +A | + MySQL with transaction support. We recommend using
+ || as the concat operator for best portability. This can be done by running
+ MySQL using: |
+ Y/N | +MySQL client | +Unix and Windows |
oci8 | -A | -Oracle 8/9. Has more functionality than oracle driver
- (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before
- Connect/PConnect.
- There are 2 ways of connecting - with server IP
- and service name: Since 2.31, we support Oracle REF cursor variables directly - (see ExecuteCursor). - |
- Y/N | -Oracle client | -Unix and Windows | +oci8 | +A | +Oracle 8/9. Has more functionality than oracle driver
+ (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before
+ Connect/PConnect. There are 2 ways of connecting
+ - with server IP and service name: Since 2.31, we support Oracle REF cursor variables directly + (see ExecuteCursor). |
+ Y/N | +Oracle client | +Unix and Windows |
oci805 | -C | -Supports reduced Oracle functionality for Oracle 8.0.5. - SelectLimit is not as efficient as in the oci8 or oci8po drivers. | -Y/N | -Oracle client | -Unix and Windows | +oci805 | +C | +Supports reduced Oracle functionality for Oracle 8.0.5. + SelectLimit is not as efficient as in the oci8 or oci8po drivers. | +Y/N | +Oracle client | +Unix and Windows |
oci8po | -A | -Oracle 8/9 portable driver. This is nearly identical with
- the oci8 driver except (a) bind variables in Prepare() use the ? convention,
- 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. - |
- Y/N | -Oracle client | -Unix and Windows | +oci8po | +A | +Oracle 8/9 portable driver. This is nearly identical with
+ the oci8 driver except (a) bind variables in Prepare() use the ? convention,
+ 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. |
+ Y/N | +Oracle client | +Unix and Windows |
odbc | -A | -Generic ODBC, not tuned for specific databases. To connect,
- use - PConnect('DSN','user','pwd'). This is the base class for all odbc - derived drivers. |
- ? depends on database | -ODBC | -Unix and Windows. Unix - hints. | +odbc | +A | +Generic ODBC, not tuned for specific databases. To connect,
+ use + PConnect('DSN','user','pwd'). This is the base class for all odbc derived + drivers. |
+ ? depends on database | +ODBC | +Unix and Windows. Unix + hints. |
odbc_mssql | -C | -Uses ODBC to connect to MSSQL | -Y/N | -ODBC | -Unix and Windows. | +odbc_mssql | +C | +Uses ODBC to connect to MSSQL | +Y/N | +ODBC | +Unix and Windows. |
odbc_oracle | -C | -Uses ODBC to connect to Oracle | -Y/N | -ODBC | -Unix and Windows. | +odbc_oracle | +C | +Uses ODBC to connect to Oracle | +Y/N | +ODBC | +Unix and Windows. |
oracle | -C | -Implements old Oracle 7 client API. Use oci8 - driver if possible for better performance. | -Y/N | -Oracle client | -Unix and Windows | +oracle | +C | +Implements old Oracle 7 client API. Use oci8 + driver if possible for better performance. | +Y/N | +Oracle client | +Unix and Windows |
postgres | -A | -Generic PostgreSQL driver. Currently identical to postgres7 - driver. | -Y | -PostgreSQL client | -Unix and Windows. | +postgres | +A | +Generic PostgreSQL driver. Currently identical to postgres7 + driver. | +Y | +PostgreSQL client | +Unix and Windows. |
postgres64 | -A | -For PostgreSQL 6.4 and earlier which does not support LIMIT - internally. | -Y | -PostgreSQL client | -Unix and Windows. | +postgres64 | +A | +For PostgreSQL 6.4 and earlier which does not support LIMIT + internally. | +Y | +PostgreSQL client | +Unix and Windows. |
postgres7 | -A | -PostgreSQL which supports LIMIT and other version 7 functionality. | -Y | -PostgreSQL client | -Unix and Windows. | +postgres7 | +A | +PostgreSQL which supports LIMIT and other version 7 functionality. | +Y | +PostgreSQL client | +Unix and Windows. |
sqlanywhere | -C | -Sybase SQL Anywhere. Should work reliably as based on ODBC - driver. | -Y/N | -SQL Anywhere ODBC client | -
- ? - |
+ sapdb | +C | +SAP DB. Should work reliably as based on ODBC driver. | +Y/N | +SAP ODBC client | + ? |
sybase | -C | -Sybase. | -Y/N | -Sybase client | -
- Unix and Windows. - |
+ sqlanywhere | +C | +Sybase SQL Anywhere. Should work reliably as based on ODBC + driver. | +Y/N | +SQL Anywhere ODBC client | + ? |
+
sqlite | +B | +SQLite. Only tested on PHP5. | +Y | +- | + Unix and Windows. |
+ ||||||
sybase | +C | +Sybase. | +Y/N | +Sybase client | + Unix and Windows. |
$conn->Connect()
or
C = user contributed or experimental driver. Might not fully support all of
the latest features of ADOdb.
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, it might be better to disable RecordCount() emulation because - substantial amounts of memory are required to cache the recordset for counting. Also - there is a speed penalty of 40-50% if emulation is required. This is emulated in - most databases except for PostgreSQL and MySQL. - This variable is checked every time a query is executed, so you can selectively - choose which recordsets to count.
-- + 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, + it might be better to disable RecordCount() emulation because substantial amounts + of memory are required to cache the recordset for counting. Also there is a + speed penalty of 40-50% if emulation is required. This is emulated in most databases + except for PostgreSQL and MySQL. This variable is checked every time a query + is executed, so you can selectively choose which recordsets to count.
+
Task: Connect to the Access Northwind DSN, display the first 2 columns - of each row.
+Task: Connect to the Access Northwind DSN, display the first 2 columns of each + row.
In this example, we create a ADOConnection object, which represents the connection - to the database. The connection is initiated with PConnect, - which is a persistent connection. Whenever we want to query the database, we - call the ADOConnection.Execute() - function. This returns an ADORecordSet object which is actually a cursor that - holds the current row in the array fields[]. - We use MoveNext() - 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. + to the database. The connection is initiated with PConnect, + which is a persistent connection. Whenever we want to query the database, we + call the ADOConnection.Execute() + function. This returns an ADORecordSet object which is actually a cursor that + holds the current row in the array fields[]. + We use MoveNext() + 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 @@ -557,10 +697,10 @@ $conn->Close(); # optional property is set to true when end-of-file is reached. If an error occurs in Execute(), we return false instead of a recordset.The
$recordSet->fields[]
array is generated by the PHP database - extension. Some database extensions only index by number and do not index - the 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(). + extension. Some database extensions only index by number and do not index the + 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'); @@ -569,12 +709,12 @@ $conn->Close(); # optional 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(). - Note that it can return -1 if the number of rows returned cannot be determined.
+ Note that it can return -1 if the number of rows returned cannot be determined.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.
+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 @@ -602,20 +742,20 @@ $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.
+ This returns an object with at least 3 fields.-
- name: name of column
-- type: native field type of column
-- max_length: maximum length of field. Some databases such as MySQL - do not return the maximum length of the field correctly. In these cases max_length - will be set to -1.
+- name: name of column
+- type: native field type of column
+- max_length: maximum length of field. Some databases such as MySQL + do not return the maximum length of the field correctly. In these cases max_length + will be set to -1.
We then use MetaType() - to translate the native type to a generic type. Currently the following - generic types are defined:
+ 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"> - tag.
+ tag.
If the metatype is of type date or timestamp, then we print it using the user - defined date format with UserDate(), - which converts the PHP SQL date string format to a user defined one. Another - use for MetaType() - is data validation before doing an SQL insert or update.
+ defined date format with UserDate(), + which converts the PHP SQL date string format to a user defined one. Another + use for MetaType() + is data validation before doing an SQL insert or update.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.
+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 @@ -658,10 +800,10 @@ $sql .= "values ('ANATR',2,". with qstr().Observe the error-handling of the Execute statement. False is returned by - Execute() if an error occured. The error message - for the last error that occurred is displayed in ErrorMsg(). - Note: php_track_errors might have to be enabled for error messages to - be saved.
+ Execute() if an error occured. The error message + for the last error that occurred is displayed in ErrorMsg(). + Note: 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 @@ -675,15 +817,15 @@ $sql .= "values ('ANATR',2,".$In the above example, we have turned on debugging by setting debug = true. - This will display the SQL statement before execution, and also show any error - messages. There is no need to call ErrorMsg() - in this case. For displaying the recordset, see the rs2html() - example.
-Also see the section on Custom Error Handlers.
+ This will display the SQL statement before execution, and also show any error + messages. There is no need to call ErrorMsg() + in this case. For displaying the recordset, see the rs2html() + example. +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.
+ 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 @@ -693,9 +835,9 @@ $rs = $conn->Execute($ 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().
+ 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 @@ -708,20 +850,17 @@ $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 -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 -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 by -performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. -
+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 +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 + by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. +
<? #============================================== # SAMPLE GetUpdateSQL() and GetInsertSQL() code @@ -783,7 +922,6 @@ $conn->Close();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'); @@ -797,67 +935,69 @@ $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: -
-
|< <<
- >> >|
- |
- ||||||||||||||||||||||||
| ||||||||||||||||||||||||
Page 8/10 |
This will create a basic record pager that looks like this: +
+
|< <<
+ >> >|
+ |
+ ||||||||||||||||||||||||
|
+ ||||||||||||||||||||||||
Page 8/10 | +
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 - databases): + databases):
$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. + 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 G.
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. +
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'); @@ -904,10 +1044,10 @@ $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 row as an array, and the recordset object. For future compatibility, - you should not use the original recordset object.
+ of the filter function. It returns the processed recordset scrolled to + the first record. The filter function takes two parameters, the current + row as an array, and the recordset object. For future compatibility, you should + not use the original recordset object.@@ -918,21 +1058,17 @@ 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(): +status. Smart Transactions is much simpler. You start a smart transaction by calling +StartTrans():
$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(). - +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); @@ -940,8 +1076,12 @@ if (!CheckRecords()) $conn->FailTrans(); $conn->Execute($Sql2); $conn->CompleteTrans();-Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block is -executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable. +
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 + is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable.
$conn->StartTrans(); $conn->Execute($sql); @@ -951,34 +1091,31 @@ $conn->Execute($sql); $conn->Execute($Sql2); $conn->CompleteTrans();-
Note: Savepoints -are currently not supported. +
Note: Savepoints are currently not supported.
-ADOdb 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 which invokes the default -PHP error handler. -
-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 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 shown. - If you set error_reporting(E_ALL), all errors will be displayed on the screen. -
+ADOdb 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 + which invokes the default PHP error handler. +
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 + 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 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); # show any error messages triggered +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'); @@ -988,16 +1125,15 @@ $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 - 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. - +
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 + 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(0); # do not echo any errors +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'); @@ -1010,7 +1146,7 @@ $rs=$c->Execute('select * from productsz'); ## invalid table productsz if ($rs) $rs2html($rs); ?>-The following message will be logged in the error.log file: +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") @@ -1033,22 +1169,21 @@ else { } ?>--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: +
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');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. + occurs. We return false instead. You have to call ADODB_Pear_Error() to get + the last error or use the PEAR_ERROR_DIE technique.
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. + By default, it sends the messages to the client. You can override this to perform + error-logging.
Data Source Names
We now support connecting using PEAR style DSN's. A DSN is a connection string of the form:
@@ -1068,9 +1203,9 @@ PEAR::setErrorHandling('PEAR_ERROR_DIE'); }
This requires PEAR to be installed and in the default include path in php.ini.
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. +
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 @@ -1086,28 +1221,27 @@ $rs = $conn->CacheExec call.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 parameter, which defaults -to 60 minutes. +
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 + 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 info. - +
Please note that magic_quotes_runtime should be turned off. More + info.
Pivot Tables
- -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 - tutorial. We assume that your database supports the SQL case-when expression. -
+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 +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:
+ pivot on categories. So from the table on the left, we generate the pivot-table + on the right:
Rows | IO | CPU | Plan |
'.round($rs->fields[8],1).' | '.round($rs->fields[9],3).' | '.round($rs->fields[10],3).' | '.htmlspecialchars($rs->fields[0])." |
tablename | size_in_k | index size | reserved size |
'.$tab.' | '.$rs2->fields[3].' | '.$rs2->fields[4].' | '.$rs2->fields[2].' |
Unable to EXPLAIN non-select statement
'; + $sql = str_replace('?',"''",$sql); + $s = 'Explain: '.htmlspecialchars($sql).'
'; + $rs = $this->conn->Execute('EXPLAIN '.$sql); + $s .= rs2html($rs,false,false,false,false); + $s .= $this->Tracer($sql); + return $s; + } + + function Tables() + { + if (!$this->tablesSQL) return false; + + $rs = $this->conn->Execute($this->tablesSQL); + if (!$rs) return false; + + $html = rs2html($rs,false,false,false,false); + return $html; + } + + function GetReads() + { + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $rs = $this->conn->Execute('show status'); + $ADODB_FETCH_MODE = $save; + + if (!$rs) return 0; + $val = 0; + while (!$rs->EOF) { + switch($rs->fields[0]) { + case 'Com_select': + $val = $rs->fields[1]; + $rs->Close(); + return $val; + } + $rs->MoveNext(); + } + + $rs->Close(); + + return $val; + } + + function GetWrites() + { + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $rs = $this->conn->Execute('show status'); + $ADODB_FETCH_MODE = $save; + + if (!$rs) return 0; + $val = 0.0; + while (!$rs->EOF) { + switch($rs->fields[0]) { + case 'Com_insert': + $val += $rs->fields[1]; break; + case 'Com_delete': + $val += $rs->fields[1]; break; + case 'Com_update': + $val += $rs->fields[1]/2; + $rs->Close(); + return $val; + } + $rs->MoveNext(); + } + + $rs->Close(); + + return $val; + } + + function FindDBHitRatio() + { + // first find out type of table + //$this->conn->debug=1; + $rs = $this->conn->Execute('show table status'); + if (!$rs) return ''; + $type = strtoupper($rs->fields[1]); + $rs->Close(); + switch($type){ + case 'MYISAM': + case 'ISAM': + return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)'; + case 'INNODB': + return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)'; + default: + return $type.' not supported'; + } + + } + + function GetQHitRatio() + { + //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached + $hits = $this->_DBParameter(array("show status","Qcache_hits")); + $total = $this->_DBParameter(array("show status","Qcache_inserts")); + $total += $this->_DBParameter(array("show status","Qcache_not_cached")); + + $total += $hits; + if ($total) return ($hits*100)/$total; + return 0; + } + + /* + Use session variable to store Hit percentage, because MySQL + does not remember last value of SHOW INNODB STATUS hit ratio + + # 1st query to SHOW INNODB STATUS + 0.00 reads/s, 0.00 creates/s, 0.00 writes/s + Buffer pool hit rate 1000 / 1000 + + # 2nd query to SHOW INNODB STATUS + 0.00 reads/s, 0.00 creates/s, 0.00 writes/s + No buffer pool activity since the last printout + */ + function GetInnoDBHitRatio() + { + global $HTTP_SESSION_VARS; + + $stat = $this->conn->GetOne('show innodb status'); + $at = strpos($stat,'Buffer pool hit rate'); + $stat = substr($stat,$at,200); + if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) { + $val = 100*$arr[1]/$arr[2]; + $HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val; + return $val; + } else { + if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT']; + return 0; + } + return 0; + } + + function GetKeyHitRatio() + { + $hits = $this->_DBParameter(array("show status","Key_read_requests")); + $reqs = $this->_DBParameter(array("show status","Key_reads")); + if ($reqs == 0) return 0; + + return ($hits/($reqs+$hits))*100; + } + +} +?> \ No newline at end of file diff --git a/lib/adodb/perf/perf-oci8.inc.php b/lib/adodb/perf/perf-oci8.inc.php new file mode 100644 index 0000000000..d18b43285f --- /dev/null +++ b/lib/adodb/perf/perf-oci8.inc.php @@ -0,0 +1,451 @@ + array('RATIOH', + "select round((1-(phy.value / (cur.value + con.value)))*100,2) + from v\$sysstat cur, v\$sysstat con, v\$sysstat phy + where cur.name = 'db block gets' and + con.name = 'consistent gets' and + phy.name = 'physical reads'", + '=WarnCacheRatio'), + + 'sql cache hit ratio' => array( 'RATIOH', + 'select round(100*(sum(pins)-sum(reloads))/sum(pins),2) from v$librarycache', + 'increase shared_pool_size if too ratio low'), + + 'datadict cache hit ratio' => array('RATIOH', + "select + round((1 - (sum(getmisses) / (sum(gets) + + sum(getmisses))))*100,2) + from v\$rowcache", + 'increase shared_pool_size if too ratio low'), + + 'IO', + 'data reads' => array('IO', + "select value from v\$sysstat where name='physical reads'"), + + 'data writes' => array('IO', + "select value from v\$sysstat where name='physical writes'"), + + 'Data Cache', + 'data cache buffers' => array( 'DATAC', + "select a.value/b.value from v\$parameter a, v\$parameter b + where a.name = 'db_cache_size' and b.name= 'db_block_size'", + 'Number of cache buffers. Tune db_cache_size if the data cache hit ratio is too low.'), + 'data cache blocksize' => array('DATAC', + "select value from v\$parameter where name='db_block_size'", + '' ), + 'Memory Pools', + 'data cache size' => array('DATAC', + "select value from v\$parameter where name = 'db_cache_size'", + 'db_cache_size' ), + 'shared pool size' => array('DATAC', + "select value from v\$parameter where name = 'shared_pool_size'", + 'shared_pool_size, which holds shared cursors, stored procedures and similar shared structs' ), + 'java pool size' => array('DATAJ', + "select value from v\$parameter where name = 'java_pool_size'", + 'java_pool_size' ), + 'large pool buffer size' => array('CACHE', + "select value from v\$parameter where name='large_pool_size'", + 'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ), + + 'pga buffer size' => array('CACHE', + "select value from v\$parameter where name='pga_aggregate_target'", + 'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ), + + + 'Connections', + 'current connections' => array('SESS', + 'select count(*) from sys.v_$session where username is not null', + ''), + 'max connections' => array( 'SESS', + "select value from v\$parameter where name='sessions'", + ''), + + 'Memory Utilization', + 'data cache utilization ratio' => array('RATIOU', + "select round((1-bytes/sgasize)*100, 2) + from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f + where name = 'free memory' and pool = 'shared pool'", + 'Percentage of data cache actually in use - too low is bad, too high is worse'), + + 'shared pool utilization ratio' => array('RATIOU', + 'select round((sga.bytes/p.value)*100,2) + from v$sgastat sga, v$parameter p + where sga.name = \'free memory\' and sga.pool = \'shared pool\' + and p.name = \'shared_pool_size\'', + 'Percentage of shared pool actually used - too low is bad, too high is worse'), + + 'large pool utilization ratio' => array('RATIOU', + "select round((1-bytes/sgasize)*100, 2) + from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f + where name = 'free memory' and pool = 'large pool'", + 'Percentage of large_pool actually in use - too low is bad, too high is worse'), + 'sort buffer size' => array('CACHE', + "select value from v\$parameter where name='sort_area_size'", + 'sort_area_size (per query), uses memory in pga' ), + + 'pga usage at peak' => array('RATIOU', + '=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'), + 'Transactions', + 'rollback segments' => array('ROLLBACK', + "select count(*) from sys.v_\$rollstat", + ''), + + 'peak transactions' => array('ROLLBACK', + "select max_utilization tx_hwm + from sys.v_\$resource_limit + where resource_name = 'transactions'", + 'Taken from high-water-mark'), + 'max transactions' => array('ROLLBACK', + "select value from v\$parameter where name = 'transactions'", + 'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'), + 'Parameters', + 'cursor sharing' => array('CURSOR', + "select value from v\$parameter where name = 'cursor_sharing'", + 'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See cursor_sharing.'), + + 'index cache cost' => array('COST', + "select value from v\$parameter where name = 'optimizer_index_caching'", + '% of indexed data blocks expected in the cache. + Recommended is 20-80. Default is 0. See optimizer_index_caching.'), + + 'random page cost' => array('COST', + "select value from v\$parameter where name = 'optimizer_index_cost_adj'", + 'Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See optimizer_index_cost_adj. '), + + false + + ); + + + function perf_oci8(&$conn) + { + $savelog = $conn->LogSQL(false); + $this->version = $conn->ServerInfo(); + $conn->LogSQL($savelog); + $this->conn =& $conn; + } + + + function PGA() + { + if ($this->version['version'] < 9) return 'Oracle 9i or later required'; + + $rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from + (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb, + pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r + from v\$pga_target_advice) a left join + (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb, + pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r + from v\$pga_target_advice) b on + a.r = b.r+1 where + b.pct < 100"); + if (!$rs) return "Only in 9i or later"; + $rs->Close(); + if ($rs->EOF) return "PGA could be too big"; + + return reset($rs->fields); + } + + function Explain($sql) + { + $savelog = $this->conn->LogSQL(false); + $rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE"); + if (!$rs) { + echo "Missing PLAN_TABLE
++CREATE TABLE PLAN_TABLE ( + STATEMENT_ID VARCHAR2(30), + TIMESTAMP DATE, + REMARKS VARCHAR2(80), + OPERATION VARCHAR2(30), + OPTIONS VARCHAR2(30), + OBJECT_NODE VARCHAR2(128), + OBJECT_OWNER VARCHAR2(30), + OBJECT_NAME VARCHAR2(30), + OBJECT_INSTANCE NUMBER(38), + OBJECT_TYPE VARCHAR2(30), + OPTIMIZER VARCHAR2(255), + SEARCH_COLUMNS NUMBER, + ID NUMBER(38), + PARENT_ID NUMBER(38), + POSITION NUMBER(38), + COST NUMBER(38), + CARDINALITY NUMBER(38), + BYTES NUMBER(38), + OTHER_TAG VARCHAR2(255), + PARTITION_START VARCHAR2(255), + PARTITION_STOP VARCHAR2(255), + PARTITION_ID NUMBER(38), + OTHER LONG, + DISTRIBUTION VARCHAR2(30) +); +"; + return false; + } + + $rs->Close(); + // $this->conn->debug=1; + + $s = "
Explain: ".htmlspecialchars($sql)."
"; + + $this->conn->BeginTrans(); + $id = "ADODB ".microtime(); + $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql"); + $m = $this->conn->ErrorMsg(); + if ($m) { + $this->conn->RollbackTrans(); + $this->conn->LogSQL($savelog); + $s .= "$m
"; + return $s; + } + $rs = $this->conn->Execute(" + select + ''||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'' as Operation, + object_name,COST,CARDINALITY,bytes + FROM plan_table +START WITH id = 0 and STATEMENT_ID='$id' +CONNECT BY prior id=parent_id and statement_id='$id'"); + + $s .= rs2html($rs,false,false,false,false); + $this->conn->RollbackTrans(); + $this->conn->LogSQL($savelog); + $s .= $this->Tracer($sql); + return $s; + } + + + function CheckMemory() + { + if ($this->version['version'] < 9) return 'Oracle 9i or later required'; + + $rs =& $this->conn->Execute(" +select a.size_for_estimate as cache_mb_estimate, + case when a.size_factor=1 then + '<<= current' + when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then + '- BETTER - ' + else ' ' end as currsize, + a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0 + from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$conn_cache_advice) a , + (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$conn_cache_advice) b where a.r = b.r-1"); + if (!$rs) return false; + + /* + The v$conn_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size + */ + $s = "
Cache that is 50% of current size is still too big
"; + } else { + $s .= rs2html($rs,false,false,false,false); + } + return $s; + } + + /* + Generate html for suspicious/expensive sql + */ + function tohtml(&$rs,$type) + { + $o1 = $rs->FetchField(0); + $o2 = $rs->FetchField(1); + $o3 = $rs->FetchField(2); + if ($rs->EOF) return 'None found
'; + $check = ''; + $sql = ''; + $s = "\n\n".$o1->name.' | '.$o2->name.' | '.$o3->name.' |
".$carr[0].' | '.$carr[1].' | '.$prefix.$sql.$suffix.' |
".$carr[0].' | '.$carr[1].' | '.$prefix.$sql.$suffix.' |
'; + $s .= $this->_SuspiciousSQL(); + return $s; + } + + // code thanks to Ixora. + // http://www.ixora.com.au/scripts/query_opt.htm + // requires oracle 8.1.7 or later + function& ExpensiveSQL($numsql = 10) + { + $sql = " +select + substr(to_char(s.pct, '99.00'), 2) || '%' load, + s.executions executes, + p.sql_text +from + ( + select + address, + disk_reads, + executions, + pct, + rank() over (order by disk_reads desc) ranking + from + ( + select + address, + disk_reads, + executions, + 100 * ratio_to_report(disk_reads) over () pct + from + sys.v_\$sql + where + command_type != 47 and module != 'T.O.A.D.' + ) + where + disk_reads > 50 * executions + ) s, + sys.v_\$sqltext p +where + s.ranking <= $numsql and + p.address = s.address +order by + 1 desc, s.address, p.piece +"; + global $ADODB_CACHE_MODE,$HTTP_GET_VARS; + if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) { + echo "".$this->Explain($HTTP_GET_VARS['sql'])."\n"; + } + + if (isset($HTTP_GET_VARS['sql'])) return $this->_ExpensiveSQL(); + + $save = $ADODB_CACHE_MODE; + $ADODB_CACHE_MODE = ADODB_FETCH_NUM; + $savelog = $this->conn->LogSQL(false); + $rs =& $this->conn->Execute($sql); + $this->conn->LogSQL($savelog); + $ADODB_CACHE_MODE = $save; + if ($rs) { + $s = "\n
'; + $s .= $this->_ExpensiveSQL(); + return $s; + } + +} +?> \ No newline at end of file diff --git a/lib/adodb/perf/perf-postgres.inc.php b/lib/adodb/perf/perf-postgres.inc.php new file mode 100644 index 0000000000..57a99e39ad --- /dev/null +++ b/lib/adodb/perf/perf-postgres.inc.php @@ -0,0 +1,109 @@ + array('RATIO', + "select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ", + 'Value must be TRUE to enable hit ratio statistics (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'", + '=WarnCacheRatio'), + 'IO', + 'data reads' => array('IO', + 'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables', + ), + 'data writes' => array('IO', + 'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables', + 'Count of inserts/updates/deletes * coef'), + + 'Data Cache', + 'data cache buffers' => array('DATAC', + "select setting from pg_settings where name='shared_buffers'", + 'Number of cache buffers. Tuning'), + 'cache blocksize' => array('DATAC', + 'select 8192', + '(estimate)' ), + 'data cache size' => array( 'DATAC', + "select setting::integer*8192 from pg_settings where name='shared_buffers'", + '' ), + 'operating system cache size' => array( 'DATA', + "select setting::integer*8192 from pg_settings where name='effective_cache_size'", + '(effective cache size)' ), + 'Memory Usage', + 'sort buffer size' => array('CACHE', + "select setting::integer*1024 from pg_settings where name='sort_mem'", + 'Size of sort buffer (per query)' ), + 'Connections', + 'current connections' => array('SESS', + 'select count(*) from pg_stat_activity', + ''), + 'max connections' => array('SESS', + "select setting from pg_settings where name='max_connections'", + ''), + 'Parameters', + 'rollback buffers' => array('COST', + "select setting from pg_settings where name='wal_buffers'", + 'WAL buffers'), + 'random page cost' => array('COST', + "select setting from pg_settings where name='random_page_cost'", + 'Cost of doing a seek (default=4). See random_page_cost'), + false + ); + + function perf_postgres(&$conn) + { + $this->conn =& $conn; + } + + function Explain($sql) + { + $sql = str_replace('?',"''",$sql); + $save = $this->conn->LogSQL(false); + $s = '
Explain: '.htmlspecialchars($sql).'
'; + $rs = $this->conn->Execute('EXPLAIN '.$sql); + $this->conn->LogSQL($save); + $s .= ''; + if ($rs) + while (!$rs->EOF) { + $s .= reset($rs->fields)."\n"; + $rs->MoveNext(); + } + $s .= ''; + $s .= $this->Tracer($sql); + return $s; + } +} +?> \ No newline at end of file diff --git a/lib/adodb/pivottable.inc.php b/lib/adodb/pivottable.inc.php index 53230cabac..96317d33a2 100644 --- a/lib/adodb/pivottable.inc.php +++ b/lib/adodb/pivottable.inc.php @@ -1,163 +1,163 @@ -GetCol("select distinct $colfield from $tables $where order by 1"); - if (!$aggfield) $hidecnt = false; - - $sel = "$rowfields, "; - if (is_array($colfield)) { - foreach ($colfield as $k => $v) { - if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", "; - if ($aggfield) - $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", "; - } - } else { - foreach ($colarr as $v) { - if (!is_numeric($v)) $vq = $db->qstr($v); - else $vq = $v; - if (strlen($v) == 0 ) $v = 'null'; - if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", "; - if ($aggfield) { - if ($hidecnt) $label = $v; - else $label = "{$v}_$aggfield"; - $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", "; - } - } - } - if ($aggfield && $aggfield != '1'){ - $agg = "$aggfn($aggfield)"; - $sel .= "\n\t$agg as \"$sumlabel$aggfield\", "; - } - - if ($showcount) - $sel .= "\n\tSUM(1) as Total"; - - - $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields"; - return $sql; - } - -/* EXAMPLES USING MS NORTHWIND DATABASE */ -if (0) { - -# example1 -# -# Query the main "product" table -# Set the rows to CompanyName and QuantityPerUnit -# and the columns to the Categories -# and define the joins to link to lookup tables -# "categories" and "suppliers" -# - - $sql = PivotTableSQL( - $gDB, # adodb connection - 'products p ,categories c ,suppliers s', # tables - 'CompanyName,QuantityPerUnit', # row fields - 'CategoryName', # column fields - 'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where -); - print "
$sql"; - $rs = $gDB->Execute($sql); - rs2html($rs); - -/* -Generated SQL: - -SELECT CompanyName,QuantityPerUnit, - SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", - SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", - SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", - SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", - SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", - SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", - SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", - SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", - SUM(1) as Total -FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID -GROUP BY CompanyName,QuantityPerUnit -*/ -/* ===================================================================== */ - -# example2 -# -# Query the main "product" table -# Set the rows to CompanyName and QuantityPerUnit -# and the columns to the UnitsInStock for different ranges -# and define the joins to link to lookup tables -# "categories" and "suppliers" -# - $sql = PivotTableSQL( - $gDB, # adodb connection - 'products p ,categories c ,suppliers s', # tables - 'CompanyName,QuantityPerUnit', # row fields - # column ranges -array( -' 0 ' => 'UnitsInStock <= 0', -"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5', -"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10', -"11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15', -"16+" =>'15 < UnitsInStock' -), - ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where - 'UnitsInStock', # sum this field - 'Sum' # sum label prefix -); - print "$sql"; - $rs = $gDB->Execute($sql); - rs2html($rs); - /* - Generated SQL: - -SELECT CompanyName,QuantityPerUnit, - SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum 0 ", - SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", - SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", - SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", - SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+", - SUM(UnitsInStock) AS "Sum UnitsInStock", - SUM(1) as Total -FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID -GROUP BY CompanyName,QuantityPerUnit - */ -} +GetCol("select distinct $colfield from $tables $where order by 1"); + if (!$aggfield) $hidecnt = false; + + $sel = "$rowfields, "; + if (is_array($colfield)) { + foreach ($colfield as $k => $v) { + if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", "; + if ($aggfield) + $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", "; + } + } else { + foreach ($colarr as $v) { + if (!is_numeric($v)) $vq = $db->qstr($v); + else $vq = $v; + if (strlen($v) == 0 ) $v = 'null'; + if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", "; + if ($aggfield) { + if ($hidecnt) $label = $v; + else $label = "{$v}_$aggfield"; + $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", "; + } + } + } + if ($aggfield && $aggfield != '1'){ + $agg = "$aggfn($aggfield)"; + $sel .= "\n\t$agg as \"$sumlabel$aggfield\", "; + } + + if ($showcount) + $sel .= "\n\tSUM(1) as Total"; + + + $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields"; + return $sql; + } + +/* EXAMPLES USING MS NORTHWIND DATABASE */ +if (0) { + +# example1 +# +# Query the main "product" table +# Set the rows to CompanyName and QuantityPerUnit +# and the columns to the Categories +# and define the joins to link to lookup tables +# "categories" and "suppliers" +# + + $sql = PivotTableSQL( + $gDB, # adodb connection + 'products p ,categories c ,suppliers s', # tables + 'CompanyName,QuantityPerUnit', # row fields + 'CategoryName', # column fields + 'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where +); + print "$sql"; + $rs = $gDB->Execute($sql); + rs2html($rs); + +/* +Generated SQL: + +SELECT CompanyName,QuantityPerUnit, + SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", + SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", + SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", + SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", + SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", + SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", + SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", + SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", + SUM(1) as Total +FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID +GROUP BY CompanyName,QuantityPerUnit +*/ +//===================================================================== + +# example2 +# +# Query the main "product" table +# Set the rows to CompanyName and QuantityPerUnit +# and the columns to the UnitsInStock for different ranges +# and define the joins to link to lookup tables +# "categories" and "suppliers" +# + $sql = PivotTableSQL( + $gDB, # adodb connection + 'products p ,categories c ,suppliers s', # tables + 'CompanyName,QuantityPerUnit', # row fields + # column ranges +array( +' 0 ' => 'UnitsInStock <= 0', +"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5', +"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10', +"11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15', +"16+" =>'15 < UnitsInStock' +), + ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where + 'UnitsInStock', # sum this field + 'Sum' # sum label prefix +); + print "$sql"; + $rs = $gDB->Execute($sql); + rs2html($rs); + /* + Generated SQL: + +SELECT CompanyName,QuantityPerUnit, + SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum 0 ", + SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", + SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", + SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", + SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+", + SUM(UnitsInStock) AS "Sum UnitsInStock", + SUM(1) as Total +FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID +GROUP BY CompanyName,QuantityPerUnit + */ +} ?> \ No newline at end of file diff --git a/lib/adodb/readme.htm b/lib/adodb/readme.htm index 599d197703..15b158af95 100644 --- a/lib/adodb/readme.htm +++ b/lib/adodb/readme.htm @@ -12,12 +12,15 @@ADOdb Library for PHP
ADOdb is a suite of database libraries that allow you to connect to multiple - databases in a portable manner.
- -The ADOdb documentation has moved to docs-adodb.htm + databases in a portable manner. Download from http://php.weblogs.com/adodb. +
The ADOdb data dictionary docs are at docs-datadict.htm. +
"; - return; - } - $arr = $rs->GetArray(); - /* $db->debug = true; */ - - $start = microtime(); - for ($i=0; $i < $max; $i++) { - $rs = $db->Execute($sql); - $arr = $rs->GetArray(); - /* print $arr[0][1]; */ - } - $end = microtime(); - $start = explode(' ',$start); - $end = explode(' ',$end); - - print_r($start); - print_r($end); - - /* print_r($arr); */ - $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]); - printf ("
seconds = %8.2f for %d iterations each with %d records
",$total,$max, sizeof($arr)); - flush(); - -?> -"; + return; + } + $arr = $rs->GetArray(); + //$db->debug = true; + global $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $start = microtime(); + for ($i=0; $i < $max; $i++) { + $rs =& $db->Execute($sql); + $arr =& $rs->GetArray(); + // print $arr[0][1]; + } + $end = microtime(); + $start = explode(' ',$start); + $end = explode(' ',$end); + + //print_r($start); + //print_r($end); + + // print_r($arr); + $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]); + printf ("
seconds = %8.2f for %d iterations each with %d records
",$total,$max, sizeof($arr)); + flush(); + + + //$db->Close(); +} +include("testdatabases.inc.php"); + +?> + + + + diff --git a/lib/adodb/tests/client.php b/lib/adodb/tests/client.php index 903f00fc4f..d22489cc1d 100644 --- a/lib/adodb/tests/client.php +++ b/lib/adodb/tests/client.php @@ -1,194 +1,194 @@ - - -$url"; - $rs = csv2rs($url,$err); - if ($err) print $err; - return $rs; - } - - function print_pre($s) - { - print "";print_r($s);print ""; - } - - -$serverURL = 'http:/* localhost/php/phplens/adodb/server.php'; */ -$testhttp = false; - -$sql1 = "insertz into products (productname) values ('testprod 1')"; -$sql2 = "insert into products (productname) values ('testprod 1')"; -$sql3 = "insert into products (productname) values ('testprod 2')"; -$sql4 = "delete from products where productid>80"; -$sql5 = 'select * from products'; - -if ($testhttp) { - print "Client Driver Tests
"; - print "
";print_r($s);print ""; + } + + +$serverURL = 'http://localhost/php/phplens/adodb/server.php'; +$testhttp = false; + +$sql1 = "insertz into products (productname) values ('testprod 1')"; +$sql2 = "insert into products (productname) values ('testprod 1')"; +$sql3 = "insert into products (productname) values ('testprod 2')"; +$sql4 = "delete from products where productid>80"; +$sql5 = 'select * from products'; + +if ($testhttp) { + print "Client Driver Tests
"; + print "
"; - $db = NewADOConnection($dbType); - $dict = NewDataDictionary($db); - - if (!$dict) continue; - $dict->debug = 1; - - $opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS'); - -/* $flds = array( - array('id', 'I', - 'AUTO','KEY'), - - array('name' => 'firstname', 'type' => 'varchar','size' => 30, - 'DEFAULT'=>'Joan'), - - array('lastname','varchar',28, - 'DEFAULT'=>'Chen','key'), - - array('averylonglongfieldname','X',1024, - 'NOTNULL','default' => 'test'), - - array('price','N','7.2', - 'NOTNULL','default' => '0.00'), - - array('MYDATE', 'D', - 'DEFDATE'), - array('TS','T', - 'DEFTIMESTAMP') - );*/ - - $flds = " -ID I AUTO KEY, -FIRSTNAME VARCHAR(30) DEFAULT 'Joan', -LASTNAME VARCHAR(28) DEFAULT 'Chen' key, -averylonglongfieldname X(1024) DEFAULT 'test', -price N(7.2) DEFAULT '0.00', -MYDATE D DEFDATE, -BIGFELLOW X NOTNULL, -TS T DEFTIMESTAMP"; - - - $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'")); - $dict->SetSchema('KUTU'); - - $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts)); - $sqla = array_merge($sqla,$sqli); - - $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH')); - $sqla = array_merge($sqla,$sqli); - $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');/* ,array('BITMAP','FULLTEXT','CLUSTERED')); */ - $sqla = array_merge($sqla,$sqli); - - $addflds = array(array('height', 'F'),array('weight','F')); - $sqli = $dict->AddColumnSQL('testtable',$addflds); - $sqla = array_merge($sqla,$sqli); - $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL')); - $sqli = $dict->AlterColumnSQL('testtable',$addflds); - $sqla = array_merge($sqla,$sqli); - - - printsqla($dbType,$sqla); - - if ($dbType == 'mysql') { - $db->Connect('localhost', "root", "", "test"); - $dict->SetSchema(''); - $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds); - if ($sqla2) printsqla($dbType,$sqla2); - } - -} - -function printsqla($dbType,$sqla) -{ - print "
"; - /* print_r($dict->MetaTables()); */ - foreach($sqla as $s) { - $s = htmlspecialchars($s); - print "$s;\n"; - if ($dbType == 'oci8') print "/\n"; - } - print "
"; + $db = NewADOConnection($dbType); + $dict = NewDataDictionary($db); + + if (!$dict) continue; + $dict->debug = 1; + + $opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS'); + +/* $flds = array( + array('id', 'I', + 'AUTO','KEY'), + + array('name' => 'firstname', 'type' => 'varchar','size' => 30, + 'DEFAULT'=>'Joan'), + + array('lastname','varchar',28, + 'DEFAULT'=>'Chen','key'), + + array('averylonglongfieldname','X',1024, + 'NOTNULL','default' => 'test'), + + array('price','N','7.2', + 'NOTNULL','default' => '0.00'), + + array('MYDATE', 'D', + 'DEFDATE'), + array('TS','T', + 'DEFTIMESTAMP') + );*/ + + $flds = " +ID I AUTO KEY, +FIRSTNAME VARCHAR(30) DEFAULT 'Joan', +LASTNAME VARCHAR(28) DEFAULT 'Chen' key, +averylonglongfieldname X(1024) DEFAULT 'test', +price N(7.2) DEFAULT '0.00', +MYDATE D DEFDATE, +BIGFELLOW X NOTNULL, +TS T DEFTIMESTAMP"; + + + $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'")); + $dict->SetSchema('KUTU'); + + $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts)); + $sqla =& array_merge($sqla,$sqli); + + $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH')); + $sqla =& array_merge($sqla,$sqli); + $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED')); + $sqla =& array_merge($sqla,$sqli); + + $addflds = array(array('height', 'F'),array('weight','F')); + $sqli = $dict->AddColumnSQL('testtable',$addflds); + $sqla =& array_merge($sqla,$sqli); + $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL')); + $sqli = $dict->AlterColumnSQL('testtable',$addflds); + $sqla =& array_merge($sqla,$sqli); + + + printsqla($dbType,$sqla); + + if ($dbType == 'mysql') { + $db->Connect('localhost', "root", "", "test"); + $dict->SetSchema(''); + $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds); + if ($sqla2) printsqla($dbType,$sqla2); + } + if ($dbType == 'postgres') { + $db->Connect('localhost', "tester", "test", "test"); + $dict->SetSchema(''); + $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds); + if ($sqla2) printsqla($dbType,$sqla2); + } + +} + +function printsqla($dbType,$sqla) +{ + print "
"; + //print_r($dict->MetaTables()); + foreach($sqla as $s) { + $s = htmlspecialchars($s); + print "$s;\n"; + if ($dbType == 'oci8') print "/\n"; + } + print "
'; + echo $perf->HealthCheck(); + echo($perf->SuspiciousSQL()); + echo($perf->ExpensiveSQL()); + echo($perf->InvalidSQL()); + echo $perf->Tables(); + + echo "
"; + echo $perf->HealthCheckCLI(); + $perf->Poll(3); + die(); + } + + if ($perf) $perf->UI(3); +} + +?> diff --git a/lib/adodb/tests/test-xmlschema.php b/lib/adodb/tests/test-xmlschema.php new file mode 100644 index 0000000000..595fccd508 --- /dev/null +++ b/lib/adodb/tests/test-xmlschema.php @@ -0,0 +1,31 @@ +Connect( 'localhost', 'root', '', 'schematest' ); + +// To create a schema object and build the query array. +$schema = new adoSchema( $db ); + +// To upgrade an existing schema object, use the following +// To upgrade an existing database to the provided schema, +// uncomment the following line: +#$schema->upgradeSchema(); + +// Build the SQL array +$sql = $schema->ParseSchema( "xmlschema.xml" ); + +print "Here's the SQL to do the build:\n-Close(); - if ($rs2) $rs2->Close(); - if ($rs) $rs->Close(); - $db->Close(); - - if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)"); - - - printf(""; +print_r( $sql ); +print "\n"; + +// Execute the SQL on the database +//$result = $schema->ExecuteSchema( $sql ); + +// Finally, clean up after the XML parser +// (PHP won't do this for you!) +//$schema->Destroy(); +?> \ No newline at end of file diff --git a/lib/adodb/tests/test.php b/lib/adodb/tests/test.php index 936fddd11e..5d6d560691 100644 --- a/lib/adodb/tests/test.php +++ b/lib/adodb/tests/test.php @@ -1,1227 +1,1341 @@ -$msg
"; - flush(); -} - -function CheckWS($conn) -{ -global $ADODB_EXTENSION; - - include_once('../adodb-session.php'); - - $saved = $ADODB_EXTENSION; - $db = ADONewConnection($conn); - $ADODB_EXTENSION = $saved; - if (headers_sent()) { - print "White space detected in adodb-$conn.inc.php or include file...
"; - die(); - } -} - -function do_strtolower(&$arr) -{ - foreach($arr as $k => $v) { - $arr[$k] = strtolower($v); - } -} - - -function CountExecs($db, $sql, $inputarray) -{ -global $EXECS; $EXECS++; -} - -function CountCachedExecs($db, $secs2cache, $sql, $inputarray) -{ -global $CACHED; $CACHED++; -} - -/* the table creation code is specific to the database, so we allow the user */ -/* to define their own table creation stuff */ - -function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)") -{ -GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS; -?>
Total queries=%d; total cached=%d
",$EXECS+$CACHED, $CACHED); -} - -function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false) -{ -global $TESTERRS,$ERRNO; - - $ERRNO = $errno; - $TESTERRS += 1; - print "** $dbms ($fn): errno=$errno errmsg=$errmsg ($p1,$p2)"; -} -if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true; - - -foreach($HTTP_GET_VARS as $k=>$v) { - global $$k; - - $$k = $v; -} - - -?> - -
ADODB Database Library (c) 2000-2003 John Lim. All rights reserved. Released under BSD and LGPL.
- - +$msgWhite space detected in adodb-$conn.inc.php or include file...
"; + die(); + } +} + +function do_strtolower(&$arr) +{ + foreach($arr as $k => $v) { + $arr[$k] = strtolower($v); + } +} + + +function CountExecs($db, $sql, $inputarray) +{ +global $EXECS; $EXECS++; +} + +function CountCachedExecs($db, $secs2cache, $sql, $inputarray) +{ +global $CACHED; $CACHED++; +} + +// the table creation code is specific to the database, so we allow the user +// to define their own table creation stuff + +function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)") +{ +GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS; + +?> +Close(); + if ($rs2) $rs2->Close(); + if ($rs) $rs->Close(); + $db->Close(); + + if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)"); + + + printf("Total queries=%d; total cached=%d
",$EXECS+$CACHED, $CACHED); +} + +function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false) +{ +global $TESTERRS,$ERRNO; + + $ERRNO = $errno; + $TESTERRS += 1; + print "** $dbms ($fn): errno=$errno errmsg=$errmsg ($p1,$p2)"; +} +if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true; + + +foreach($HTTP_GET_VARS as $k=>$v) { + //global $$k; + $$k = $v; +} +if (strpos(PHP_VERSION,'5') === 0) { + //$testaccess=1; + //$testmssql = 1; + //$testsqlite=1; +} +?> + +
+ + + +
ADODB Database Library (c) 2000-2003 John Lim. All rights reserved. Released under BSD and LGPL.
+ + diff --git a/lib/adodb/tests/test2.php b/lib/adodb/tests/test2.php index cb8e2fcb17..c6492807fc 100644 --- a/lib/adodb/tests/test2.php +++ b/lib/adodb/tests/test2.php @@ -1,41 +1,41 @@ - */ - - - -"; -/* $rs->_array = false; */ -/* $rs->connection = false; */ -/* print_r($rs); */ -rs2html($rs); -?> - - - - + + + + +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); +?> + + + + diff --git a/lib/adodb/tests/test3.php b/lib/adodb/tests/test3.php index c9098baa54..9da45fa0d5 100644 --- a/lib/adodb/tests/test3.php +++ b/lib/adodb/tests/test3.php @@ -1,32 +1,32 @@ --PConnect("susetikus","tester","test","test")) - die("Cannot connect to database"); - -# select * from last table in DB -$rs = $c1->Execute("select * from adoxyz order by 1"); - -$i = 0; -$max = $rs->RecordCount(); -if ($max == -1) "RecordCount returns -1
"; -while (!$rs->EOF and $i < $max) { - $rs->Move($i); - print_r( $rs->fields); - print '
'; - $i++; -} -?> ++PConnect("susetikus","tester","test","test")) + die("Cannot connect to database"); + +# select * from last table in DB +$rs = $c1->Execute("select * from adoxyz order by 1"); + +$i = 0; +$max = $rs->RecordCount(); +if ($max == -1) "RecordCount returns -1
\ No newline at end of file diff --git a/lib/adodb/tests/test4.php b/lib/adodb/tests/test4.php index 62e17e0197..0ae650d677 100644 --- a/lib/adodb/tests/test4.php +++ b/lib/adodb/tests/test4.php @@ -1,85 +1,87 @@ -debug=1; -$conn->PConnect("localhost", "root", "", "test"); /* connect to MySQL, testdb */ -$conn->Execute("delete from adoxyz where lastname like 'Smith%'"); - -$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 */ -$record["firstname"] = "null"; -$record["lastname"] = "Smith\$@/* "; */ -$record["created"] = time(); -$record["id"] = -1; - -/* 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 lastname=".$conn->qstr($record['lastname']); -/* Select a record to update */ - -$rs = $conn->Execute($sql); /* Execute the query and get the existing record to update */ -if (!$rs) print "
"; +while (!$rs->EOF and $i < $max) { + $rs->Move($i); + print_r( $rs->fields); + print '
'; + $i++; +} +?>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"] = "Smithy"; /* Update Caroline's lastname from Miranda to Smith */ -$record["creAted"] = '2002-12-'.(rand()%30+1); - -/* 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. */ -/* If the data has not changed, no recordset is returned */ -$updateSQL = $conn->GetUpdateSQL($rs, $record); - -$conn->Execute($updateSQL); /* Update the record in the database */ -print "Rows Affected=".$conn->Affected_Rows()."
"; - -rs2html($conn->Execute("select * from adoxyz where lastname like 'Smith%'")); -} - - -testsql(); +debug=1; +$conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb +$conn->Execute("delete from adoxyz where lastname like 'Smith%'"); + +$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 +$record["firstname"] = 'null'; +$record["lastname"] = "Smith\$@//"; +$record["created"] = time(); +//$record["id"] = -1; + +// 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 lastname=".$conn->qstr($record['lastname']); +// 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!
"; +$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"] = "Smithy Jones"; // Update Caroline's lastname from Miranda to Smith +$record["creAted"] = '2002-12-'.(rand()%30+1); + +// 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. +// If the data has not changed, no recordset is returned +$updateSQL = $conn->GetUpdateSQL($rs, $record); + +$conn->Execute($updateSQL); // Update the record in the database +print "Rows Affected=".$conn->Affected_Rows()."
"; + +rs2html($conn->Execute("select * from adoxyz where lastname like 'Smith%'")); +} + + +testsql(); ?> \ No newline at end of file diff --git a/lib/adodb/tests/test5.php b/lib/adodb/tests/test5.php index b23f03bae0..e8bfe8769d 100644 --- a/lib/adodb/tests/test5.php +++ b/lib/adodb/tests/test5.php @@ -1,47 +1,47 @@ -debug=1; - $conn->PConnect("localhost","root","","xphplens"); - print $conn->databaseType.':'.$conn->GenID().'
'; -} - -if (0) { - $conn = &ADONewConnection("oci8"); /* create a connection */ - $conn->debug=1; - $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); /* connect to MySQL, testdb */ - print $conn->databaseType.':'.$conn->GenID(); -} - -if (0) { - $conn = &ADONewConnection("ibase"); /* create a connection */ - $conn->debug=1; - $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); /* connect to MySQL, testdb */ - print $conn->databaseType.':'.$conn->GenID().'
'; -} - -if (0) { - $conn = &ADONewConnection('postgres'); - $conn->debug=1; - @$conn->PConnect("susetikus","tester","test","test"); - print $conn->databaseType.':'.$conn->GenID().'
'; -} -?> +debug=1; + $conn->PConnect("localhost","root","","xphplens"); + print $conn->databaseType.':'.$conn->GenID().'
'; +} + +if (0) { + $conn = &ADONewConnection("oci8"); // create a connection + $conn->debug=1; + $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb + print $conn->databaseType.':'.$conn->GenID(); +} + +if (0) { + $conn = &ADONewConnection("ibase"); // create a connection + $conn->debug=1; + $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb + print $conn->databaseType.':'.$conn->GenID().'
'; +} + +if (0) { + $conn = &ADONewConnection('postgres'); + $conn->debug=1; + @$conn->PConnect("susetikus","tester","test","test"); + print $conn->databaseType.':'.$conn->GenID().'
'; +} +?> diff --git a/lib/adodb/tests/testcache.php b/lib/adodb/tests/testcache.php index 786282f8a0..0624ec9194 100644 --- a/lib/adodb/tests/testcache.php +++ b/lib/adodb/tests/testcache.php @@ -1,29 +1,29 @@ - - -PConnect('nwind'); -} else { - $db = ADONewConnection('mysql'); - $db->PConnect('mangrove','root','','xphplens'); -} -if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products'); -else $rs = $db->Execute('select * from products'); - -$arr = $rs->GetArray(); -print sizeof($arr); + + +PConnect('nwind'); +} else { + $db = ADONewConnection('mysql'); + $db->PConnect('mangrove','root','','xphplens'); +} +if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products'); +else $rs = $db->Execute('select * from products'); + +$arr = $rs->GetArray(); +print sizeof($arr); ?> \ No newline at end of file diff --git a/lib/adodb/tests/testdatabases.inc.php b/lib/adodb/tests/testdatabases.inc.php index ca9e802128..cb017c216f 100644 --- a/lib/adodb/tests/testdatabases.inc.php +++ b/lib/adodb/tests/testdatabases.inc.php @@ -1,235 +1,283 @@ -Connecting $db->databaseType..."; - if (@$db->PConnect("localhost","tester","test","test")) { - testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)"); - }else - print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.
".$db->ErrorMsg(); -} - -if (!empty($testpgodbc)) { - - $db = &ADONewConnection('odbc'); - $db->hasTransactions = false; - print "Connecting $db->databaseType...
"; - - if ($db->PConnect('Postgresql')) { - $db->hasTransactions = true; - testdb($db, - "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); - } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.
".$db->ErrorMsg(); -} - -if (!empty($testibase)) { - - $db = &ADONewConnection('firebird'); - print "Connecting $db->databaseType...
"; - if (@$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "")) - testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)"); - else print "ERROR: Interbase test requires a database called employee.gdb".'
'.$db->ErrorMsg(); - -} - -/* REQUIRES ODBC DSN CALLED nwind */ -if (!empty($testaccess)) { - $db = &ADONewConnection('access'); - print "Connecting $db->databaseType...
"; - - if (@$db->PConnect("nwind", "", "", "")) - testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); - else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver"; - -} - -if (!empty($testaccess) && !empty($testado)) { /* ADO ACCESS */ - - $db = &ADONewConnection("ado_access"); - print "Connecting $db->databaseType...
"; - - $access = 'd:\inetpub\wwwroot\php\NWIND.MDB'; - $myDSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;' - . 'DATA SOURCE=' . $access . ';'; - /* . 'USER ID=;PASSWORD=;'; */ - - if (@$db->PConnect($myDSN, "", "", "")) { - print "ADO version=".$db->_connectionID->version."
"; - testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); - } else print "ERROR: Access test requires a Access database $access".'
'.$db->ErrorMsg(); - -} - -if (!empty($testvfp)) { /* ODBC */ - $db = &ADONewConnection('vfp'); - print "Connecting $db->databaseType...
";flush(); - - if ( $db->PConnect("vfp-adoxyz")) { - testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)"); - } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver"; - -} - - -/* REQUIRES MySQL server at localhost with database 'test' */ -if (!empty($testmysql)) { /* MYSQL */ - - $db = &ADONewConnection('mysql'); - print "Connecting $db->databaseType...
"; - if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; - else $server = "mangrove"; - if ($db->PConnect($server, "root", "", "test")) { - /* $db->debug=1;$db->Execute('drop table ADOXYZ'); */ - testdb($db, - "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); - } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); -} - -/* REQUIRES MySQL server at localhost with database 'test' */ -if (!empty($testmysqlodbc)) { /* MYSQL */ - - $db = &ADONewConnection('odbc'); - $db->hasTransactions = false; - print "Connecting $db->databaseType...
"; - if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; - else $server = "mangrove"; - if ($db->PConnect('mysql', "root", "")) - testdb($db, - "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); - else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); -} - -if (!empty($testproxy)){ - $db = &ADONewConnection('proxy'); - print "Connecting $db->databaseType...
"; - if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; - - if ($db->PConnect('http:/* localhost/php/phplens/adodb/server.php')) */ - testdb($db, - "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); - else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); - -} - -ADOLoadCode('oci805'); -ADOLoadCode("oci8po"); -if (!empty($testoracle)) { - - $db = ADONewConnection('oci8po'); - print "Connecting $db->databaseType...
"; - if ($db->Connect('', "scott", "tiger",'')) - /* if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my")) */ - testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)"); - else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'
'.$db->ErrorMsg(); - -} -ADOLoadCode("oracle"); /* no longer supported */ -if (false && !empty($testoracle)) { - - $db = ADONewConnection(); - print "Connecting $db->databaseType...
"; - if ($db->PConnect("", "scott", "tiger", "natsoft.domain")) - testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)"); - else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'
'.$db->ErrorMsg(); - -} - -ADOLoadCode("db2"); /* no longer supported */ -if (!empty($testdb2)) { - - $db = ADONewConnection(); - print "Connecting $db->databaseType...
"; - if ($db->Connect("db2_sample", "", "", "")) - 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(); - -} - - - -ADOLoadCode("odbc_mssql"); -if (!empty($testmssql)) { /* MS SQL Server via ODBC */ - - $db = ADONewConnection(); - - print "Connecting $db->databaseType...
"; - if (@$db->PConnect("mssql-northwind", "adodb", "natsoft", "")) { - testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)"); - } - else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup"; - -} - -ADOLoadCode("ado_mssql"); - -if (!empty($testmssql) && !empty($testado) ) { /* ADO ACCESS MSSQL -- thru ODBC -- DSN-less */ - - $db = &ADONewConnection("ado_mssql"); - $db->debug=1; - print "Connecting DSN-less $db->databaseType...
"; - - $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};" - . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No" ; - - - if (@$db->PConnect($myDSN, "", "", "")) - testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)"); - else print "ERROR: MSSQL test 2 requires MS SQL 7"; - -} - - -ADOLoadCode("mssqlpo"); -if (!empty($testmssql)) { /* MS SQL Server -- the extension is buggy -- probably better to use ODBC */ - $db = ADONewConnection(); - $db->debug=1; - print "Connecting $db->databaseType...
"; - - $db->PConnect('tigress','adodb','natsoft','northwind'); - - if (true 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(); - -} - -if (!empty($testmssql) && !empty($testado)) { /* ADO ACCESS MSSQL with OLEDB provider */ - - $db = &ADONewConnection("ado_mssql"); - print "Connecting DSN-less OLEDB Provider $db->databaseType...
"; - $db->debug=1; - $myDSN="SERVER=(local)\NetSDK;DATABASE=northwind;Trusted_Connection=yes"; - /* $myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;'; */ - if ($db->PConnect($myDSN, "sa", "natsoft", 'SQLOLEDB')) - testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); - else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'"; - -} - - -print "Tests Completed
"; - -?> + + ++FETCH MODE IS NOT ADODB_FETCH_DEFAULT"; + +if (isset($nocountrecs)) $ADODB_COUNTRECS = false; + +// cannot test databases below, but we include them anyway to check +// if they parse ok... + +if (!strpos(PHP_VERSION,'5') === 0) { + ADOLoadCode("sybase"); + ADOLoadCode("postgres"); + ADOLoadCode("postgres7"); + ADOLoadCode("firebird"); + ADOLoadCode("borland_ibase"); + ADOLoadCode("informix"); + ADOLoadCode("sqlanywhere"); +} + + +flush(); +if (!empty($testpostgres)) { + //ADOLoadCode("postgres"); + + $db = &ADONewConnection('postgres'); + print "
+ Connecting $db->databaseType...
"; + if (@$db->Connect("localhost","tester","test","test")) { + testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)"); + }else + print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.
".$db->ErrorMsg(); +} + +if (!empty($testpgodbc)) { + + $db = &ADONewConnection('odbc'); + $db->hasTransactions = false; + print "Connecting $db->databaseType...
"; + + if ($db->PConnect('Postgresql')) { + $db->hasTransactions = true; + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); + } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.
".$db->ErrorMsg(); +} + +if (!empty($testibase)) { + + $db = &ADONewConnection('firebird'); + print "Connecting $db->databaseType...
"; + if (@$db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", "")) + testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)"); + else print "ERROR: Interbase test requires a database called employee.gdb".'
'.$db->ErrorMsg(); + +} + + +if (!empty($testsqlite)) { + $db = &ADONewConnection('sqlite'); + print "Connecting $db->databaseType...
"; + + if (@$db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", "")) + testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); + else print "ERROR: SQLite"; + +} + +// REQUIRES ODBC DSN CALLED nwind +if (!empty($testaccess)) { + $db = &ADONewConnection('access'); + print "Connecting $db->databaseType...
"; + + $dsn = "nwind"; + $driver = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\inetpub\adodb\northwind.mdb;Uid=Admin;Pwd=;"; + if (@$db->PConnect($dsn, "", "", "")) + testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); + else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver"; + +} + +if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS + + $db = &ADONewConnection("ado_access"); + print "Connecting $db->databaseType...
"; + + $access = 'd:\inetpub\wwwroot\php\NWIND.MDB'; + $myDSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;' + . 'DATA SOURCE=' . $access . ';'; + //. 'USER ID=;PASSWORD=;'; + + if (@$db->PConnect($myDSN, "", "", "")) { + print "ADO version=".$db->_connectionID->version."
"; + testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); + } else print "ERROR: Access test requires a Access database $access".'
'.$db->ErrorMsg(); + +} + +if (!empty($testvfp)) { // ODBC + $db = &ADONewConnection('vfp'); + print "Connecting $db->databaseType...
";flush(); + + if ( $db->PConnect("vfp-adoxyz")) { + testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)"); + } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver"; + +} + + +// REQUIRES MySQL server at localhost with database 'test' +if (!empty($testmysql)) { // MYSQL + + $db = &ADONewConnection('mysql'); + print "Connecting $db->databaseType...
"; + if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + else $server = "mangrove"; + if ($db->PConnect($server, "root", "", "northwind")) { + //$db->debug=1;$db->Execute('drop table ADOXYZ'); + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)"); + } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); +} + +// REQUIRES MySQL server at localhost with database 'test' +if (!empty($testmysqlodbc)) { // MYSQL + + $db = &ADONewConnection('odbc'); + $db->hasTransactions = false; + print "Connecting $db->databaseType...
"; + if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + else $server = "mangrove"; + if ($db->PConnect('mysql', "root", "")) + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); + else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); +} + +if (!empty($testproxy)){ + $db = &ADONewConnection('proxy'); + print "Connecting $db->databaseType...
"; + if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost'; + + if ($db->PConnect('http://localhost/php/phplens/adodb/server.php')) + testdb($db, + "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb"); + else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'
'.$db->ErrorMsg(); + +} + +ADOLoadCode('oci805'); +ADOLoadCode("oci8po"); +if (!empty($testoracle)) { + + $db = ADONewConnection('oci8po'); + print "Connecting $db->databaseType...
"; + if ($db->Connect('', "scott", "natsoft",'')) + //if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my")) + testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)"); + else print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'
'.$db->ErrorMsg(); + +} +ADOLoadCode("oracle"); // no longer supported +if (false && !empty($testoracle)) { + + $db = ADONewConnection(); + print "Connecting $db->databaseType...
"; + if ($db->PConnect("", "scott", "tiger", "natsoft.domain")) + testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)"); + else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'
'.$db->ErrorMsg(); + +} + +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(); + +} + + + +ADOLoadCode("odbc_mssql"); +if (!empty($testmssql)) { // MS SQL Server via ODBC + $db = ADONewConnection(); + + print "Connecting $db->databaseType...
"; + + $dsn = "mssql-northwind"; + $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;"; + + if (@$db->PConnect($dsn, "adodb", "natsoft", "")) { + testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)"); + } + else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup"; + +} + +ADOLoadCode("ado_mssql"); + +if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less + + $db = &ADONewConnection("ado_mssql"); + //$db->debug=1; + print "Connecting DSN-less $db->databaseType...
"; + + $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};" + . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No" ; + + + if (@$db->PConnect($myDSN, "", "", "")) + testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)"); + else print "ERROR: MSSQL test 2 requires MS SQL 7"; + +} + + +ADOLoadCode("mssqlpo"); +if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC + $db = ADONewConnection(); + //$db->debug=1; + print "Connecting $db->databaseType...
"; + + $db->PConnect('tigress','adodb','natsoft','northwind'); + + if (true 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(); + +} + +if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider + + $db = &ADONewConnection("ado_mssql"); + print "Connecting DSN-less OLEDB Provider $db->databaseType...
"; + //$db->debug=1; + $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes"; + //$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;'; + if ($db->PConnect($myDSN, "sa", "natsoft", 'SQLOLEDB')) + testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)"); + else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'"; + +} + + +print "Tests Completed
"; + +?> diff --git a/lib/adodb/tests/testgenid.php b/lib/adodb/tests/testgenid.php index 44311e8168..cbdd02b7b3 100644 --- a/lib/adodb/tests/testgenid.php +++ b/lib/adodb/tests/testgenid.php @@ -1,36 +1,36 @@ -Execute("drop table $table"); - /* $db->debug=true; */ - - $ctr = 5000; - $lastnum = 0; - - while (--$ctr >= 0) { - $num = $db->GenID($table); - if ($num === false) { - print "GenID returned false"; - break; - } - if ($lastnum + 1 == $num) print " $num "; - else { - print " $num "; - flush(); - } - $lastnum = $num; - } -} +Execute("drop table $table"); + //$db->debug=true; + + $ctr = 5000; + $lastnum = 0; + + while (--$ctr >= 0) { + $num = $db->GenID($table); + if ($num === false) { + print "GenID returned false"; + break; + } + if ($lastnum + 1 == $num) print " $num "; + else { + print " $num "; + flush(); + } + $lastnum = $num; + } +} ?> \ No newline at end of file diff --git a/lib/adodb/tests/testmssql.php b/lib/adodb/tests/testmssql.php index d43aef643f..3f2c1f110b 100644 --- a/lib/adodb/tests/testmssql.php +++ b/lib/adodb/tests/testmssql.php @@ -1,50 +1,62 @@ -Connect('mssql-northwind','sa','natsoft'); - -/* $conn = &ADONewConnection("mssql"); */ -/* $conn->Connect('mangrove','sa','natsoft','ai'); */ - -/* $conn->Connect('mangrove','sa','natsoft','ai'); */ -$conn->debug=1; -$conn->Execute('delete from blobtest'); - -$conn->Execute('insert into blobtest (id) values(1)'); -$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1'); -$rs = $conn->Execute('select b1 from blobtest where id=1'); - -$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; -print "Saving file $output, size=".strlen($rs->fields[0]).""; -$fd = fopen($output, "wb"); -fwrite($fd, $rs->fields[0]); -fclose($fd); - -print " View Image"; */ -/* $rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest'); */ -/* rs2html($rs); */ +Connect('localhost','sa','natsoft','northwind') or die('Fail'); + +$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)'); +echo "
"; +print_r($p); + +$conn->debug=1; +$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time()))); + +$p = $conn->Prepare('select * from products where productname like ?'); +$arr = $conn->getarray($p,array('V%')); +print_r($arr); +die(); + +//$conn = &ADONewConnection("mssql"); +//$conn->Connect('mangrove','sa','natsoft','ai'); + +//$conn->Connect('mangrove','sa','natsoft','ai'); +$conn->debug=1; +$conn->Execute('delete from blobtest'); + +$conn->Execute('insert into blobtest (id) values(1)'); +$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1'); +$rs = $conn->Execute('select b1 from blobtest where id=1'); + +$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; +print "Saving file $output, size=".strlen($rs->fields[0]).""; +$fd = fopen($output, "wb"); +fwrite($fd, $rs->fields[0]); +fclose($fd); + +print " View Image"; +//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest'); +//rs2html($rs); ?> \ No newline at end of file diff --git a/lib/adodb/tests/testoci8.php b/lib/adodb/tests/testoci8.php index 6885136a3c..f338dc0451 100644 --- a/lib/adodb/tests/testoci8.php +++ b/lib/adodb/tests/testoci8.php @@ -1,70 +1,70 @@ - -
-PConnect('','scott','tiger','natsoftmts'); - $db->debug = true; - - if (!empty($testblob)) { - $varHoldingBlob = 'ABC DEF GEF John TEST'; - $num = time()%10240; - /* create table atable (id integer, ablob blob); */ - $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())'); - $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB'); - - $rs = &$db->Execute('select * from atable'); - - if (!$rs) die("Empty RS"); - if ($rs->EOF) die("EOF RS"); - rs2html($rs); - } - $stmt = $db->Prepare('select * from adoxyz where id=?'); - for ($i = 1; $i <= 10; $i++) { - $rs = &$db->Execute( - $stmt, - array($i)); - - if (!$rs) die("Empty RS"); - if ($rs->EOF) die("EOF RS"); - rs2html($rs); - } -} -if (1) { - $db = ADONewConnection('oci8'); - $db->PConnect('','scott','tiger'); - $db->debug = true; - $db->Execute("delete from emp where ename='John'"); - print $db->Affected_Rows().'
'; - $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)'); - $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John')); - /* prepare not quite ready for prime time */ - /* $rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John')); */ - if (!$rs) die("Empty RS"); -} - -if (0) { - $db = ADONewConnection('odbc_oracle'); - if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect'); - $db->debug = true; - $rs = &$db->Execute( - 'select * from adoxyz where firstname=? and trim(lastname)=?', - array('first'=>'Caroline','last'=>'Miranda')); - if (!$rs) die("Empty RS"); - if ($rs->EOF) die("EOF RS"); - rs2html($rs); -} + + +PConnect('','scott','tiger'); + + if (!empty($testblob)) { + $varHoldingBlob = 'ABC DEF GEF John TEST'; + $num = time()%10240; + // create table atable (id integer, ablob blob); + $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())'); + $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB'); + + $rs = &$db->Execute('select * from atable'); + + if (!$rs) die("Empty RS"); + if ($rs->EOF) die("EOF RS"); + rs2html($rs); + } + $stmt = $db->Prepare('select * from adoxyz where id=?'); + for ($i = 1; $i <= 10; $i++) { + $rs = &$db->Execute( + $stmt, + array($i)); + + if (!$rs) die("Empty RS"); + if ($rs->EOF) die("EOF RS"); + rs2html($rs); + } +} +if (1) { + $db = ADONewConnection('oci8'); + $db->PConnect('','scott','tiger'); + $db->debug = true; + $db->Execute("delete from emp where ename='John'"); + print $db->Affected_Rows().'
'; + $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)'); + $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John')); + // prepare not quite ready for prime time + //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John')); + if (!$rs) die("Empty RS"); +} + +if (0) { + $db = ADONewConnection('odbc_oracle'); + if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect'); + $db->debug = true; + $rs = &$db->Execute( + 'select * from adoxyz where firstname=? and trim(lastname)=?', + array('first'=>'Caroline','last'=>'Miranda')); + if (!$rs) die("Empty RS"); + if ($rs->EOF) die("EOF RS"); + rs2html($rs); +} ?> \ No newline at end of file diff --git a/lib/adodb/tests/testoci8cursor.php b/lib/adodb/tests/testoci8cursor.php index 726ff9cde3..7bd6c1e6f3 100644 --- a/lib/adodb/tests/testoci8cursor.php +++ b/lib/adodb/tests/testoci8cursor.php @@ -1,82 +1,82 @@ -PConnect('','scott','tiger'); - $db->debug = true; - - - - #--------------------------------------------------------------- - # EXAMPLE 1 - # explicitly use Parameter function - #--------------------------------------------------------------- - $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'%'); END;"); - $db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR); - $rs = $db->Execute($stmt); - - if ($rs && !$rs->EOF) { - print "Test 1 RowCount: ".$rs->RecordCount().""; - } else { - print "Error in using Cursor Variables 1
"; - } - - #--------------------------------------------------------------- - # EXAMPLE 2 - # Equivalent of above example 1 using ExecuteCursor($sql,$rsname) - #--------------------------------------------------------------- - $rs = $db->ExecuteCursor( - "BEGIN adodb.open_tab(:RS,'%'); END;", # pl/sql script - 'RS'); # cursor name - - if ($rs && !$rs->EOF) { - print "Test 2 RowCount: ".$rs->RecordCount()."
"; - rs2html($rs); - } else { - print "Error in using Cursor Variables 2
"; - } - +PConnect('','scott','tiger'); + $db->debug = true; + + + + #--------------------------------------------------------------- + # EXAMPLE 1 + # explicitly use Parameter function + #--------------------------------------------------------------- + $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'%'); END;"); + $db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR); + $rs = $db->Execute($stmt); + + if ($rs && !$rs->EOF) { + print "Test 1 RowCount: ".$rs->RecordCount()."
"; + } else { + print "Error in using Cursor Variables 1
"; + } + + #--------------------------------------------------------------- + # EXAMPLE 2 + # Equivalent of above example 1 using ExecuteCursor($sql,$rsname) + #--------------------------------------------------------------- + $rs = $db->ExecuteCursor( + "BEGIN adodb.open_tab(:RS,'%'); END;", # pl/sql script + 'RS'); # cursor name + + if ($rs && !$rs->EOF) { + print "Test 2 RowCount: ".$rs->RecordCount()."
"; + rs2html($rs); + } else { + print "Error in using Cursor Variables 2
"; + } + ?> \ No newline at end of file diff --git a/lib/adodb/tests/testpaging.php b/lib/adodb/tests/testpaging.php index 7a2c4e4e3e..2f62da01ad 100644 --- a/lib/adodb/tests/testpaging.php +++ b/lib/adodb/tests/testpaging.php @@ -1,83 +1,83 @@ -PConnect('localhost','tester','test','test'); -} - -if ($driver == 'access') { - $db = NewADOConnection('access'); - $db->PConnect("nwind", "", "", ""); -} - -if ($driver == 'ibase') { - $db = NewADOConnection('ibase'); - $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", ""); - $sql = 'select distinct firstname, lastname from adoxyz order by firstname'; - -} -if ($driver == 'mssql') { - $db = NewADOConnection('mssql'); - $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind'); -} -if ($driver == 'oci8') { - $db = NewADOConnection('oci8'); - $db->Connect('','scott','tiger'); -} - -if ($driver == 'access') { - $db = NewADOConnection('access'); - $db->Connect('nwind'); -} - -if (empty($driver) or $driver == 'mysql') { - $db = NewADOConnection('mysql'); - $db->Connect('localhost','root','','xphplens'); -} - -/* $db->pageExecuteCountRows = false; */ - -$db->debug = true; - -if (0) { -$rs = &$db->Execute($sql); -include_once('../toexport.inc.php'); -print "
"; -print rs2csv($rs); # return a string - -print '"; -} - -$pager = new ADODB_Pager($db,$sql); -$pager->showPageLinks = true; -$pager->linksPerPage = 3; -$pager->cache = 60; -$pager->Render($rows=7); +PConnect('localhost','tester','test','test'); +} + +if ($driver == 'access') { + $db = NewADOConnection('access'); + $db->PConnect("nwind", "", "", ""); +} + +if ($driver == 'ibase') { + $db = NewADOConnection('ibase'); + $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", ""); + $sql = 'select distinct firstname, lastname from adoxyz order by firstname'; + +} +if ($driver == 'mssql') { + $db = NewADOConnection('mssql'); + $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind'); +} +if ($driver == 'oci8') { + $db = NewADOConnection('oci8'); + $db->Connect('','scott','natsoft'); +} + +if ($driver == 'access') { + $db = NewADOConnection('access'); + $db->Connect('nwind'); +} + +if (empty($driver) or $driver == 'mysql') { + $db = NewADOConnection('mysql'); + $db->Connect('localhost','root','','xphplens'); +} + +//$db->pageExecuteCountRows = false; + +$db->debug = true; + +if (0) { +$rs = &$db->Execute($sql); +include_once('../toexport.inc.php'); +print "
'; -$rs->MoveFirst(); # note, some databases do not support MoveFirst -print rs2tab($rs); # return a string - -print '
'; -$rs->MoveFirst(); -rs2tabout($rs); # send to stdout directly -print ""; +print rs2csv($rs); # return a string + +print '"; +} + +$pager = new ADODB_Pager($db,$sql); +$pager->showPageLinks = true; +$pager->linksPerPage = 3; +$pager->cache = 60; +$pager->Render($rows=7); ?> \ No newline at end of file diff --git a/lib/adodb/tests/testpear.php b/lib/adodb/tests/testpear.php index f6633e8692..161783736c 100644 --- a/lib/adodb/tests/testpear.php +++ b/lib/adodb/tests/testpear.php @@ -1,34 +1,34 @@ -setFetchMode(ADODB_FETCH_ASSOC); -$rs = $db->Query('select firstname,lastname from adoxyz'); -$cnt = 0; -while ($arr = $rs->FetchRow()) { - print_r($arr); - print "
'; +$rs->MoveFirst(); # note, some databases do not support MoveFirst +print rs2tab($rs); # return a string + +print '
'; +$rs->MoveFirst(); +rs2tabout($rs); # send to stdout directly +print "
"; - $cnt += 1; -} - -if ($cnt != 50) print "Error in \$cnt = $cnt"; +setFetchMode(ADODB_FETCH_ASSOC); +$rs = $db->Query('select firstname,lastname from adoxyz'); +$cnt = 0; +while ($arr = $rs->FetchRow()) { + print_r($arr); + print "
"; + $cnt += 1; +} + +if ($cnt != 50) print "Error in \$cnt = $cnt"; ?> \ No newline at end of file diff --git a/lib/adodb/tests/testsessions.php b/lib/adodb/tests/testsessions.php index c2c1e7786a..306616bfd0 100644 --- a/lib/adodb/tests/testsessions.php +++ b/lib/adodb/tests/testsessions.php @@ -1,40 +1,53 @@ -Notify Expiring=$ref, sessionkey=$key"; -} -$USER = 'JLIM'.rand(); -$ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire'); - -GLOBAL $HTTP_SESSION_VARS; - ob_start(); - error_reporting(E_ALL); - - $ADODB_SESS_DEBUG = true; - include('../adodb-cryptsession.php'); - session_start(); - - print "PHP ".PHP_VERSION."
"; - - $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41); - if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1; - - print "\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}
"; - - if (rand() % 10 == 0) { - print "Random session destroy
"; - session_destroy(); - } - print "
"; - print_r($HTTP_COOKIE_VARS); +Notify Expiring=$ref, sessionkey=$key"; +} + +//------------------------------------------------------------------- + + $ADODB_SESSION_DRIVER='oci8'; + $ADODB_SESSION_CONNECT=''; + $ADODB_SESSION_USER ='scott'; + $ADODB_SESSION_PWD ='natsoft'; + $ADODB_SESSION_DB =''; + + $USER = 'JLIM'.rand(); + $ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire'); + + GLOBAL $HTTP_SESSION_VARS; + ob_start(); + error_reporting(E_ALL); + + $ADODB_SESS_DEBUG = true; + include('../adodb-session.php'); + session_start(); + + print "PHP ".PHP_VERSION."
"; + + $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41); + if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1; + + print "\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}
"; + + if (rand() % 10 == 0) { + + print "GC
"; + adodb_sess_gc(10); + + print "Random session destroy
"; + session_destroy(); + } + print "
"; + print_r($HTTP_COOKIE_VARS); ?> \ No newline at end of file diff --git a/lib/adodb/tests/time.php b/lib/adodb/tests/time.php index f3a7d6b28c..e4474b1d84 100644 --- a/lib/adodb/tests/time.php +++ b/lib/adodb/tests/time.php @@ -1,5 +1,17 @@ - + \ No newline at end of file diff --git a/lib/adodb/tests/tmssql.php b/lib/adodb/tests/tmssql.php index a303b112b4..a3b743ca1f 100644 --- a/lib/adodb/tests/tmssql.php +++ b/lib/adodb/tests/tmssql.php @@ -30,7 +30,7 @@ include_once('DB.php'); $hostname = 'JAGUAR\vsdotnet'; $databasename = 'northwind'; - $dsn = "mssql:/* $username:$password@$hostname/$databasename"; */ + $dsn = "mssql://$username:$password@$hostname/$databasename"; $conn = &DB::connect($dsn); print "date=".$conn->GetOne('select getdate()')."
"; @$conn->query('create table tester (id integer)'); @@ -46,7 +46,7 @@ include_once('../adodb.inc.php'); print "ADOdb
"; $conn = NewADOConnection('mssql'); $conn->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind'); -/* $conn->debug=1; */ +// $conn->debug=1; print "date=".$conn->GetOne('select getdate()')."
"; $conn->Execute('create table tester (id integer)'); print "Delete
"; flush(); diff --git a/lib/adodb/tests/xmlschema.xml b/lib/adodb/tests/xmlschema.xml new file mode 100644 index 0000000000..acae10741a --- /dev/null +++ b/lib/adodb/tests/xmlschema.xml @@ -0,0 +1,29 @@ + ++ diff --git a/lib/adodb/tips_portable_sql.htm b/lib/adodb/tips_portable_sql.htm index d25d702713..e0dd414914 100644 --- a/lib/adodb/tips_portable_sql.htm +++ b/lib/adodb/tips_portable_sql.htm @@ -158,6 +158,57 @@ SELECT col1, col2, null FROM t1+
++ +An integer row that's a primary key and autoincrements ++ + + +A 16 character varchar row that can't be null ++ + +row1 + row2 + + +SQL to be executed only on specific platforms ++ insert into mytable ( row1, row2 ) values ( 12, 'stuff' ) + ++ insert into mytable ( row1, row2 ) values ( 12, 'different stuff' ) + ++
+
WHERE t1.col not in (select distinct colADOdb supports portable Prepare/Execute with:
$stmt = $db->Prepare('select * from customers where custid=? and state=?'); $rs = $db->Execute($stmt, array($id,'New York'));+Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates +the correct placeholder (available since ADOdb 3.92): +
$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')); ++Portable Native SQL
+ADOdb provides the following functions for portably generating SQL functions + as strings to be merged into your SQL statements (some are only available since + ADOdb 3.92):
++
++ +Function +Description ++ +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. +
DDL and Tuning
There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams.@@ -279,7 +330,7 @@ your data carefully. Understand how joins and indexes work and how they are used http://php.weblogs.com/sql_tutorial. Also read this article on Optimizing PHP.
-(c) 2002 John Lim. +(c) 2002-2003 John Lim. diff --git a/lib/adodb/toexport.inc.php b/lib/adodb/toexport.inc.php index 3b83bf12eb..b5bfbcfbec 100644 --- a/lib/adodb/toexport.inc.php +++ b/lib/adodb/toexport.inc.php @@ -1,130 +1,130 @@ -FieldTypesArray(); - foreach($fieldTypes as $o) { - - $v = $o->name; - if ($escquote) $v = str_replace($quote,$escquotequote,$v); - $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); - $elements[] = $v; - - } - $s .= implode($sep, $elements).$NEWLINE; - } - $hasNumIndex = isset($rs->fields[0]); - - $line = 0; - $max = $rs->FieldCount(); - - while (!$rs->EOF) { - $elements = array(); - $i = 0; - - if ($hasNumIndex) { - for ($j=0; $j < $max; $j++) { - $v = trim($rs->fields[$j]); - if ($escquote) $v = str_replace($quote,$escquotequote,$v); - $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); - - if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; - else $elements[] = $v; - } - } else { /* ASSOCIATIVE ARRAY */ - foreach($rs->fields as $v) { - if ($escquote) $v = str_replace($quote,$escquotequote,trim($v)); - $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); - - if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; - else $elements[] = $v; - } - } - $s .= implode($sep, $elements).$NEWLINE; - $rs->MoveNext(); - $line += 1; - if ($fp && ($line % $BUFLINES) == 0) { - if ($fp === true) echo $s; - else fwrite($fp,$s); - $s = ''; - } - } - - if ($fp) { - if ($fp === true) echo $s; - else fwrite($fp,$s); - $s = ''; - } - - return $s; -} +FieldTypesArray(); + foreach($fieldTypes as $o) { + + $v = $o->name; + if ($escquote) $v = str_replace($quote,$escquotequote,$v); + $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); + $elements[] = $v; + + } + $s .= implode($sep, $elements).$NEWLINE; + } + $hasNumIndex = isset($rs->fields[0]); + + $line = 0; + $max = $rs->FieldCount(); + + while (!$rs->EOF) { + $elements = array(); + $i = 0; + + if ($hasNumIndex) { + for ($j=0; $j < $max; $j++) { + $v = trim($rs->fields[$j]); + if ($escquote) $v = str_replace($quote,$escquotequote,$v); + $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); + + if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; + else $elements[] = $v; + } + } else { // ASSOCIATIVE ARRAY + foreach($rs->fields as $v) { + if ($escquote) $v = str_replace($quote,$escquotequote,trim($v)); + $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))); + + if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; + else $elements[] = $v; + } + } + $s .= implode($sep, $elements).$NEWLINE; + $rs->MoveNext(); + $line += 1; + if ($fp && ($line % $BUFLINES) == 0) { + if ($fp === true) echo $s; + else fwrite($fp,$s); + $s = ''; + } + } + + if ($fp) { + if ($fp === true) echo $s; + else fwrite($fp,$s); + $s = ''; + } + + return $s; +} ?> \ No newline at end of file diff --git a/lib/adodb/tohtml.inc.php b/lib/adodb/tohtml.inc.php index 216c69fccc..a6cc503c2f 100644 --- a/lib/adodb/tohtml.inc.php +++ b/lib/adodb/tohtml.inc.php @@ -1,154 +1,158 @@ - -*/ - -/* specific code for tohtml */ -GLOBAL $gSQLMaxRows,$gSQLBlockRows; - -$gSQLMaxRows = 1000; /* max no of rows to download */ -$gSQLBlockRows=20; /* max no of rows per table block */ - -/* RecordSet to HTML Table */ -/* ------------------------------------------------------------ */ -/* Convert a recordset to a html table. Multiple tables are generated */ -/* if the number of rows is > $gSQLBlockRows. This is because */ -/* web browsers normally require the whole table to be downloaded */ -/* before it can be rendered, so we break the output into several */ -/* smaller faster rendering tables. */ -/* */ -/* $rs: the recordset */ -/* $ztabhtml: the table tag attributes (optional) */ -/* $zheaderarray: contains the replacement strings for the headers (optional) */ -/* */ -/* USAGE: */ -/* include('adodb.inc.php'); */ -/* $db = ADONewConnection('mysql'); */ -/* $db->Connect('mysql','userid','password','database'); */ -/* $rs = $db->Execute('select col1,col2,col3 from table'); */ -/* rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3')); */ -/* $rs->Close(); */ -/* */ -/* RETURNS: number of rows displayed */ -function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true) -{ -$s ='';$rows=0;$docnt = false; -GLOBAL $gSQLMaxRows,$gSQLBlockRows; - - if (!$rs) { - printf(ADODB_BAD_RS,'rs2html'); - return false; - } - - if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'"; - /* else $docnt = true; */ - $typearr = array(); - $ncols = $rs->FieldCount(); - $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 (strlen($fname)==0) $fname = ' '; - $hdr .= "
\n\n"; - $s = $hdr; - } - } /* while */ - - print $s."$fname "; - } - - print $hdr."\n\n"; - /* smart algorithm - handles ADODB_FETCH_MODE's correctly! */ - $numoffset = isset($rs->fields[0]); - - while (!$rs->EOF) { - - $s .= "\n"; - - for ($i=0, $v=($numoffset) ? $rs->fields[0] : reset($rs->fields); - $i < $ncols; - $i++, $v = ($numoffset) ? @$rs->fields[$i] : next($rs->fields)) { - - $type = $typearr[$i]; - switch($type) { - case 'T': - $s .= " \n\n"; - - $rows += 1; - if ($rows >= $gSQLMaxRows) { - $rows = "".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ." \n"; - break; - case 'D': - $s .= "".$rs->UserDate($v,"D d, M Y") ." \n"; - break; - case 'I': - case 'N': - $s .= "".stripslashes((trim($v))) ." \n"; - - break; - default: - if ($htmlspecialchars) $v = htmlspecialchars($v); - $s .= "". str_replace("\n",' \n"; - - } - } /* for */ - $s .= "
',stripslashes((trim($v)))) ."Truncated at $gSQLMaxRows
"; - break; - } /* switch */ - - $rs->MoveNext(); - - /* additional EOF check to prevent a widow header */ - if (!$rs->EOF && $rows % $gSQLBlockRows == 0) { - - /* if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP */ - print $s . "
\n"; - $s .= "\n |
$fname | "; + } + + if ($echo) print $hdr."\n\n"; + else $html = $hdr; + + // smart algorithm - handles ADODB_FETCH_MODE's correctly! + $numoffset = isset($rs->fields[0]); + + while (!$rs->EOF) { + + $s .= "|||
---|---|---|---|
".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ." | \n"; + break; + case 'D': + $s .= "".$rs->UserDate($v,"D d, M Y") ." | \n"; + break; + case 'I': + case 'N': + $s .= "".stripslashes((trim($v))) ." | \n"; + + break; + default: + if ($htmlspecialchars) $v = htmlspecialchars(trim($v)); + $v = trim($v); + if (strlen($v) == 0) $v = ' '; + $s .= "". str_replace("\n",' ',stripslashes($v)) ." | \n";
+
+ }
+ } // for
+ $s .= "
\n"; + $s .= "\n |