MDL-19055 Upgrade to AdoDB 5.08 + local patches reapplied

This commit is contained in:
stronk7
2009-05-03 22:33:18 +00:00
parent d64514aab0
commit 2f326cef12
97 changed files with 10876 additions and 5504 deletions
+332 -29
View File
@@ -1,7 +1,7 @@
<?php
/*
@version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
@version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Latest version is available at http://adodb.sourceforge.net
Released under both BSD license and Lesser GPL library license.
@@ -10,12 +10,13 @@
Active Record implementation. Superset of Zend Framework's.
Version 0.08
Version 0.92
See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
for info on Ruby on Rails Active Record implementation
*/
global $_ADODB_ACTIVE_DBS;
global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
global $ACTIVE_RECORD_SAFETY; // set to false to disable safety checks
@@ -36,10 +37,15 @@ class ADODB_Active_Table {
var $flds; // assoc array of adofieldobjs, indexed by fieldname
var $keys; // assoc array of primary keys, indexed by fieldname
var $_created; // only used when stored as a cached file
var $_belongsTo = array();
var $_hasMany = array();
}
// $db = database connection
// $index = name of index - can be associative, for an example see
// http://phplens.com/lens/lensforum/msgs.php?id=17790
// returns index into $_ADODB_ACTIVE_DBS
function ADODB_SetDatabaseAdapter(&$db)
function ADODB_SetDatabaseAdapter(&$db, $index=false)
{
global $_ADODB_ACTIVE_DBS;
@@ -56,13 +62,18 @@ function ADODB_SetDatabaseAdapter(&$db)
$obj->db = $db;
$obj->tables = array();
$_ADODB_ACTIVE_DBS[] = $obj;
if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
$_ADODB_ACTIVE_DBS[$index] = $obj;
return sizeof($_ADODB_ACTIVE_DBS)-1;
}
class ADODB_Active_Record {
static $_changeNames = true; // dynamically pluralize table names
static $_foreignSuffix = '_id'; //
var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
var $_table; // tablename, if set in class definition then use it as table name
var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
@@ -70,7 +81,9 @@ class ADODB_Active_Record {
var $_saved = false; // indicates whether data is already inserted.
var $_lasterr = false; // last error message
var $_original = false; // the original values loaded or inserted, refreshed on update
var $foreignName; // CFR: class name when in a relationship
static function UseDefaultValues($bool=null)
{
global $ADODB_ACTIVE_DEFVALS;
@@ -79,9 +92,9 @@ class ADODB_Active_Record {
}
// should be static
static function SetDatabaseAdapter(&$db)
static function SetDatabaseAdapter(&$db, $index=false)
{
return ADODB_SetDatabaseAdapter($db);
return ADODB_SetDatabaseAdapter($db, $index);
}
@@ -105,16 +118,18 @@ class ADODB_Active_Record {
if (!empty($this->_table)) $table = $this->_table;
else $table = $this->_pluralize(get_class($this));
}
$this->foreignName = strtolower(get_class($this)); // CFR: default foreign name
if ($db) {
$this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
} else
$this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
} else if (!isset($this->_dbat)) {
if (sizeof($_ADODB_ACTIVE_DBS) == 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
end($_ADODB_ACTIVE_DBS);
$this->_dbat = key($_ADODB_ACTIVE_DBS);
}
$this->_table = $table;
$this->_tableat = $table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
$this->UpdateActiveTable($pkeyarr);
}
@@ -126,6 +141,8 @@ class ADODB_Active_Record {
function _pluralize($table)
{
if (!ADODB_Active_Record::$_changeNames) return $table;
$ut = strtoupper($table);
$len = strlen($table);
$lastc = $ut[$len-1];
@@ -145,13 +162,178 @@ class ADODB_Active_Record {
}
}
// CFR Lamest singular inflector ever - @todo Make it real!
// Note: There is an assumption here...and it is that the argument's length >= 4
function _singularize($tables)
{
if (!ADODB_Active_Record::$_changeNames) return $table;
$ut = strtoupper($tables);
$len = strlen($tables);
if($ut[$len-1] != 'S')
return $tables; // I know...forget oxen
if($ut[$len-2] != 'E')
return substr($tables, 0, $len-1);
switch($ut[$len-3])
{
case 'S':
case 'X':
return substr($tables, 0, $len-2);
case 'I':
return substr($tables, 0, $len-3) . 'y';
case 'H';
if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
return substr($tables, 0, $len-2);
default:
return substr($tables, 0, $len-1); // ?
}
}
function hasMany($foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new $foreignClass($foreignRef);
$ar->foreignName = $foreignRef;
$ar->UpdateActiveTable();
$ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
$table =& $this->TableInfo();
$table->_hasMany[$foreignRef] = $ar;
# $this->$foreignRef = $this->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
}
// use when you don't want ADOdb to auto-pluralize tablename
static function TableHasMany($table, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new ADODB_Active_Record($table);
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
// use when you don't want ADOdb to auto-pluralize tablename
static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
$ar = new ADODB_Active_Record($table,$tablePKey);
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
// use when you want ADOdb to auto-pluralize tablename for you. Note that the class must already be defined.
// e.g. class Person will generate relationship for table Persons
static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
$ar = new $parentclass();
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
function belongsTo($foreignRef,$foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
global $inflector;
$ar = new $parentClass($this->_pluralize($foreignRef));
$ar->foreignName = $foreignRef;
$ar->parentKey = $parentKey;
$ar->UpdateActiveTable();
$ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
$table =& $this->TableInfo();
$table->_belongsTo[$foreignRef] = $ar;
# $this->$foreignRef = $this->_belongsTo[$foreignRef];
}
static function ClassBelongsTo($class, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
$ar = new $class();
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
static function TableBelongsTo($table, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
$ar = new ADOdb_Active_Record($table);
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
$ar = new ADOdb_Active_Record($table, $tablePKey);
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
/**
* __get Access properties - used for lazy loading
*
* @param mixed $name
* @access protected
* @return mixed
*/
function __get($name)
{
return $this->LoadRelations($name, '', -1, -1);
}
/**
* @param string $name
* @param string $whereOrderBy : eg. ' AND field1 = value ORDER BY field2'
* @param offset
* @param limit
* @return mixed
*/
function LoadRelations($name, $whereOrderBy='', $offset=-1,$limit=-1)
{
$extras = array();
$table = $this->TableInfo();
if ($limit >= 0) $extras['limit'] = $limit;
if ($offset >= 0) $extras['offset'] = $offset;
if (strlen($whereOrderBy))
if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
$whereOrderBy = 'AND '.$whereOrderBy;
if(!empty($table->_belongsTo[$name]))
{
$obj = $table->_belongsTo[$name];
$columnName = $obj->foreignKey;
if(empty($this->$columnName))
$this->$name = null;
else
{
if ($obj->parentKey) $key = $obj->parentKey;
else $key = reset($table->keys);
$arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
if ($arrayOfOne) {
$this->$name = $arrayOfOne[0];
return $arrayOfOne[0];
}
}
}
if(!empty($table->_hasMany[$name]))
{
$obj = $table->_hasMany[$name];
$key = reset($table->keys);
$id = @$this->$key;
if (!is_numeric($id)) {
$db = $this->DB();
$id = $db->qstr($id);
}
$objs = $obj->Find($obj->foreignKey.'='.$id. ' '.$whereOrderBy,false,false,$extras);
if (!$objs) $objs = array();
$this->$name = $objs;
return $objs;
}
return array();
}
//////////////////////////////////
// update metadata
function UpdateActiveTable($pkeys=false,$forceUpdate=false)
{
global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
global $ADODB_ACTIVE_DEFVALS;
global $ADODB_ACTIVE_DEFVALS,$ADODB_FETCH_MODE;
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
@@ -169,7 +351,6 @@ class ADODB_Active_Record {
}
return;
}
$db = $activedb->db;
$fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
@@ -191,8 +372,15 @@ class ADODB_Active_Record {
$activetab = new ADODB_Active_Table();
$activetab->name = $table;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
$cols = $db->MetaColumns($table);
if (isset($savem)) $db->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$cols) {
$this->Error("Invalid table name: $table",'UpdateActiveTable');
return false;
@@ -270,6 +458,12 @@ class ADODB_Active_Record {
if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
adodb_write_file($fname,$s);
}
if (isset($activedb->tables[$table])) {
$oldtab = $activedb->tables[$table];
if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
}
$activedb->tables[$table] = $activetab;
}
@@ -338,15 +532,26 @@ class ADODB_Active_Record {
}
// retrieve ADODB_Active_Table
function TableInfo()
function &TableInfo()
{
global $_ADODB_ACTIVE_DBS;
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$table = $activedb->tables[$this->_tableat];
return $table;
}
// I have an ON INSERT trigger on a table that sets other columns in the table.
// So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
function Reload()
{
$db =& $this->DB(); if (!$db) return false;
$table =& $this->TableInfo();
$where = $this->GenWhere($db, $table);
return($this->Load($where));
}
// set a numeric array (using natural table field ordering) as object properties
function Set(&$row)
{
@@ -378,7 +583,8 @@ class ADODB_Active_Record {
# </AP>
}
else
$keys = array_keys($row);
$keys = array_keys($row);
# <AP>
reset($keys);
$this->_original = array();
@@ -388,6 +594,7 @@ class ADODB_Active_Record {
$this->_original[] = $value;
next($keys);
}
# </AP>
return true;
}
@@ -414,12 +621,15 @@ class ADODB_Active_Record {
case 'D':
case 'T':
if (empty($val)) return 'null';
case 'B':
case 'N':
case 'C':
case 'X':
if (is_null($val)) return 'null';
if (strncmp($val,"'",1) != 0 && substr($val,strlen($val)-1,1) != "'") {
if (strlen($val)>1 &&
(strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
return $db->qstr($val);
break;
}
@@ -447,18 +657,48 @@ class ADODB_Active_Record {
//------------------------------------------------------------ Public functions below
function Load($where,$bindarr=false)
function Load($where=null,$bindarr=false)
{
global $ADODB_FETCH_MODE;
$db = $this->DB(); if (!$db) return false;
$this->_where = $where;
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$row = $db->GetRow("select * from ".$this->_table.' WHERE '.$where,$bindarr);
$db->SetFetchMode($save);
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
$qry = "select * from ".$this->_table;
if($where) {
$qry .= ' WHERE '.$where;
}
$row = $db->GetRow($qry,$bindarr);
if (isset($savem)) $db->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
return $this->Set($row);
}
# useful for multiple record inserts
# see http://phplens.com/lens/lensforum/msgs.php?id=17795
function Reset()
{
$this->_where=null;
$this->_saved = false;
$this->_lasterr = false;
$this->_original = false;
$vars=get_object_vars($this);
foreach($vars as $k=>$v){
if(substr($k,0,1)!=='_'){
$this->{$k}=null;
}
}
$this->foreignName=strtolower(get_class($this));
return true;
}
// false on error
function Save()
{
@@ -481,7 +721,7 @@ class ADODB_Active_Record {
foreach($table->flds as $name=>$fld) {
$val = $this->$name;
if(!is_null($val) || !array_key_exists($name, $table->keys)) {
if(!is_array($val) || !is_null($val) || !array_key_exists($name, $table->keys)) {
$valarr[] = $val;
$names[] = $name;
$valstr[] = $db->Param($cnt);
@@ -532,10 +772,10 @@ class ADODB_Active_Record {
}
// returns an array of active record objects
function Find($whereOrderBy,$bindarr=false,$pkeysArr=false)
function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
{
$db = $this->DB(); if (!$db || empty($this->_table)) return false;
$arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr);
$arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
return $arr;
}
@@ -564,6 +804,9 @@ class ADODB_Active_Record {
if (is_null($val) && !empty($fld->auto_increment)) {
continue;
}
if (is_array($val)) continue;
$t = $db->MetaType($fld->type);
$arr[$name] = $this->doquote($db,$val,$t);
$valarr[] = $val;
@@ -623,9 +866,8 @@ class ADODB_Active_Record {
$val = $this->$name;
$neworig[] = $val;
if (isset($table->keys[$name])) {
if (isset($table->keys[$name]) || is_array($val))
continue;
}
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
@@ -665,4 +907,65 @@ class ADODB_Active_Record {
};
function adodb_GetActiveRecordsClass(&$db, $class, $table,$whereOrderBy,$bindarr, $primkeyArr,
$extra)
{
global $_ADODB_ACTIVE_DBS;
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$qry = "select * from ".$table;
if (!empty($whereOrderBy))
$qry .= ' WHERE '.$whereOrderBy;
if(isset($extra['limit']))
{
$rows = false;
if(isset($extra['offset'])) {
$rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
} else {
$rs = $db->SelectLimit($qry, $extra['limit']);
}
if ($rs) {
while (!$rs->EOF) {
$rows[] = $rs->fields;
$rs->MoveNext();
}
}
} else
$rows = $db->GetAll($qry,$bindarr);
$db->SetFetchMode($save);
$false = false;
if ($rows === false) {
return $false;
}
if (!class_exists($class)) {
$db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
return $false;
}
$arr = array();
// arrRef will be the structure that knows about our objects.
// It is an associative array.
// We will, however, return arr, preserving regular 0.. order so that
// obj[0] can be used by app developpers.
$arrRef = array();
$bTos = array(); // Will store belongTo's indices if any
foreach($rows as $row) {
$obj = new $class($table,$primkeyArr,$db);
if ($obj->ErrorNo()){
$db->_errorMsg = $obj->ErrorMsg();
return $false;
}
$obj->Set($row);
$arr[] = $obj;
} // foreach($rows as $row)
return $arr;
}
?>
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -8,7 +8,7 @@ $ADODB_INCLUDED_CSV = 1;
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -287,7 +287,7 @@ $ADODB_INCLUDED_CSV = 1;
fclose($fd);
if ($ok) {
chmod($tmpname,0644);
@chmod($tmpname,0644);
// the tricky moment
@unlink($filename);
if (!@rename($tmpname,$filename)) {
@@ -305,7 +305,7 @@ $ADODB_INCLUDED_CSV = 1;
if (fwrite( $fd, $contents )) $ok = true;
else $ok = false;
fclose($fd);
chmod($filename,0644);
@chmod($filename,0644);
}else {
fclose($fd);
if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
+14 -5
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -230,6 +230,7 @@ class ADODB_DataDict {
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
'VAR_STRING' => 'C', # mysql
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
@@ -257,6 +258,7 @@ class ADODB_DataDict {
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
'TIMESTAMPTZ' => 'T',
'SMALLDATETIME' => 'T',
'T' => 'T',
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
##
@@ -812,7 +814,7 @@ class ADODB_DataDict {
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
@@ -917,7 +919,7 @@ class ADODB_DataDict {
This function changes/adds new fields to your table. You don't
have to know if the col is new or not. It will check on its own.
*/
function ChangeTableSQL($tablename, $flds, $tableoptions = false)
function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false)
{
global $ADODB_FETCH_MODE;
@@ -950,13 +952,15 @@ class ADODB_DataDict {
$obj = $cols[$k];
if (isset($obj->not_null) && $obj->not_null)
$v = str_replace('NOT NULL','',$v);
if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT']))
$v = str_replace('AUTOINCREMENT','',$v);
$c = $cols[$k];
$ml = $c->max_length;
$mt = $this->MetaType($c->type,$ml);
if ($ml == -1) $ml = '';
if ($mt == 'X') $ml = $v['SIZE'];
if (($mt != $v['TYPE']) || $ml != $v['SIZE']) {
if (($mt != $v['TYPE']) || $ml != $v['SIZE'] || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
$holdflds[$k] = $v;
}
} else {
@@ -993,6 +997,11 @@ class ADODB_DataDict {
}
}
if ($dropOldFlds) {
foreach ( $cols as $id => $v )
if ( !isset($lines[$id]) )
$sql[] = $alter . $this->dropCol . ' ' . $v->name;
}
return $sql;
}
} // class
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+34 -23
View File
@@ -10,7 +10,7 @@ global $ADODB_INCLUDED_LIB;
$ADODB_INCLUDED_LIB = 1;
/*
@version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim\@natsoft.com.my). All rights reserved.
@version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim\@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -147,7 +147,7 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
if ($v === null) {
$v = 'NULL';
$fieldArray[$k] = $v;
} else if ($autoQuote && !is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ and strcasecmp($v,$zthis->null2null)!=0) {
} else if ($autoQuote && /*!is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ strcasecmp($v,$zthis->null2null)!=0) {
$v = $zthis->qstr($v);
$fieldArray[$k] = $v;
}
@@ -159,7 +159,7 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
} else
$uSet .= ",$k=$v";
}
$where = false;
foreach ($keyCol as $v) {
if (isset($fieldArray[$v])) {
@@ -542,7 +542,7 @@ function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
return $rsreturn;
}
// Ivn Oliva version
// Iván Oliva version
function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
{
@@ -999,15 +999,15 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
case "T":
$val = $zthis->DBTimeStamp($arrFields[$fname]);
break;
case "F": //Floating point number // Moodle added
break;
case "F": //Floating point number // Moodle added
case "N":
$val = $arrFields[$fname];
if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
break;
case "L": //Integer field suitable for storing booleans (0 or 1) // Moodle added
case "L": //Integer field suitable for storing booleans (0 or 1) // Moodle added
case "I":
case "R":
$val = $arrFields[$fname];
@@ -1055,11 +1055,13 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
$ss = '<code>'.htmlspecialchars($ss).'</code>';
}
if ($zthis->debug === -1)
ADOConnection::outp( "<br />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br />\n",false);
else
ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false);
ADOConnection::outp( "<br />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<br />\n",false); /// Moodle XHTML
else if ($zthis->debug !== -99)
ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false); /// Moodle XHTML
} else {
ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false);
$ss = "\n ".$ss;
if ($zthis->debug !== -99)
ADOConnection::outp("-----<hr />\n($dbt): ".$sqlTxt." $ss\n-----<hr />\n",false); /// Moodle XHTML
}
$qID = $zthis->_query($sql,$inputarr);
@@ -1070,10 +1072,21 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
*/
if ($zthis->databaseType == 'mssql') {
// ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
if($emsg = $zthis->ErrorMsg()) {
if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg);
if ($err = $zthis->ErrorNo()) {
if ($zthis->debug === -99)
ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false); /// Moodle XHTML
ADOConnection::outp($err.': '.$emsg);
}
}
} else if (!$qID) {
if ($zthis->debug === -99)
if ($inBrowser) ADOConnection::outp( "<hr />\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr />\n",false); /// Moodle XHTML
else ADOConnection::outp("-----<hr />\n($dbt): ".$sqlTxt."$ss\n-----<hr />\n",false);
ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
}
@@ -1082,20 +1095,18 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
}
# pretty print the debug_backtrace function
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
{
if (!function_exists('debug_backtrace')) return '';
$html = (isset($_SERVER['HTTP_USER_AGENT']));
// moodle change start - see readme_moodle.txt
$fmt = ($html) ? "</font><font color=\"#808080\" size=\"-1\"> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
// moodle change end
if ($ishtml === null) $html = (isset($_SERVER['HTTP_USER_AGENT']));
else $html = $ishtml;
$fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
$MAXSTRLEN = 128;
// moodle change start - see readme_moodle.txt
$s = ($html) ? '<pre align="left">' : '';
// moodle change end
$s = ($html) ? '<pre align=left>' : '';
if (is_array($printOrArr)) $traceArr = $printOrArr;
else $traceArr = debug_backtrace();
@@ -1121,7 +1132,7 @@ function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0)
else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
else {
$v = (string) @$v;
$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
$str = htmlspecialchars(str_replace(array("\r","\n"),' ',substr($v,0,$MAXSTRLEN)));
if (strlen($v) > $MAXSTRLEN) $str .= '...';
$args[] = $str;
}
@@ -1181,4 +1192,4 @@ function _adodb_find_from($sql)
}
*/
?>
?>
+162 -90
View File
@@ -6,113 +6,185 @@ if (!defined('ADODB_DIR')) die();
global $ADODB_INCLUDED_MEMCACHE;
$ADODB_INCLUDED_MEMCACHE = 1;
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
/*
V4.90 8 June 2006 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Usage:
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = array($ip1, $ip2, $ip3);
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
Note the memcache class is shared by all connections, is created during the first call to Connect/PConnect.
Class instance is stored in $ADODB_CACHE
*/
function getmemcache($key,&$err, $timeout=0, $host, $port)
{
$false = false;
$err = false;
if (!function_exists('memcache_pconnect')) {
$err = 'Memcache module PECL extension not found!';
return $false;
class ADODB_Cache_MemCache {
var $createdir = false; // create caching directory structure?
//-----------------------------
// memcache specific variables
var $hosts; // array of hosts
var $port = 11211;
var $compress = false; // memcache compression with zlib
var $_connected = false;
var $_memcache = false;
function ADODB_Cache_MemCache(&$obj)
{
$this->hosts = $obj->memCacheHost;
$this->port = $obj->memCachePort;
$this->compress = $obj->memCacheCompress;
}
// implement as lazy connection. The connection only occurs on CacheExecute call
function connect(&$err)
{
if (!function_exists('memcache_pconnect')) {
$err = 'Memcache module PECL extension not found!';
return false;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
$err = 'Can\'t connect to memcache server on: '.$host.':'.$port;
return $false;
$memcache = new MemCache;
if (!is_array($this->hosts)) $this->hosts = array($hosts);
$failcnt = 0;
foreach($this->hosts as $host) {
if (!@$memcache->addServer($host,$this->port,true)) {
$failcnt += 1;
}
}
if ($failcnt == sizeof($this->hosts)) {
$err = 'Can\'t connect to any memcache server';
return false;
}
$this->_connected = true;
$this->_memcache = $memcache;
return true;
}
$rs = $memcache->get($key);
if (!$rs) {
$err = 'Item with such key doesn\'t exists on the memcached server.';
return $false;
// returns true or false. true if successful save
function writecache($filename, $contents, $debug, $secs2cache)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
if (!$this->_memcache->set($filename, $contents, $this->compress, $secs2cache)) {
if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
return false;
}
return true;
}
$tdiff = intval($rs->timeCreated+$timeout - time());
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 15) == 0) {
$err = "Timeout 2";
// returns a recordset
function readcache($filename, &$err, $secs2cache, $rsClass)
{
$false = false;
if (!$this->_connected) $this->connect($err);
if (!$this->_memcache) return $false;
$rs = $this->_memcache->get($filename);
if (!$rs) {
$err = 'Item with such key doesn\'t exists on the memcached server.';
return $false;
}
// hack, should actually use _csv2rs
$rs = explode("\n", $rs);
unset($rs[0]);
$rs = join("\n", $rs);
$rs = unserialize($rs);
if (! is_object($rs)) {
$err = 'Unable to unserialize $rs';
return $false;
}
if ($rs->timeCreated == 0) return $rs; // apparently have been reports that timeCreated was set to 0 somewhere
$tdiff = intval($rs->timeCreated+$secs2cache - time());
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 15) == 0) {
$err = "Timeout 2";
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
$err = "Timeout 1";
return $false;
}
break;
default:
$err = "Timeout 0";
return $false;
}
break;
case 1:
if ((rand() & 3) == 0) {
$err = "Timeout 1";
return $false;
}
break;
default:
$err = "Timeout 0";
return $false;
}
}
return $rs;
}
function flushall($debug=false)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
$del = $this->_memcache->flush();
if ($debug)
if (!$del) ADOConnection::outp("flushall: failed!<br>\n");
else ADOConnection::outp("flushall: succeeded!<br>\n");
return $del;
}
function flushcache($filename, $debug=false)
{
if (!$this->_connected) {
$err = '';
if (!$this->connect($err) && $debug) ADOConnection::outp($err);
}
if (!$this->_memcache) return false;
$del = $this->_memcache->delete($filename);
if ($debug)
if (!$del) ADOConnection::outp("flushcache: $key entry doesn't exist on memcached server!<br>\n");
else ADOConnection::outp("flushcache: $key entry flushed from memcached server!<br>\n");
return $del;
}
// not used for memcache
function createdir($dir, $hash)
{
return true;
}
return $rs;
}
function putmemcache($key, $rs, $host, $port, $compress, $debug=false)
{
$false = false;
$true = true;
if (!function_exists('memcache_pconnect')) {
if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
return $false;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
return $false;
}
$rs->timeCreated = time();
if (!$memcache->set($key, $rs, $compress, 0)) {
if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
return $false;
}
return $true;
}
function flushmemcache($key=false, $host, $port, $debug=false)
{
if (!function_exists('memcache_pconnect')) {
if ($debug) ADOConnection::outp(" Memcache module PECL extension not found!<br>\n");
return;
}
$memcache = new Memcache;
if (!@$memcache->pconnect($host, $port)) {
if ($debug) ADOConnection::outp(" Can't connect to memcache server on: $host:$port<br>\n");
return;
}
if ($key) {
if (!$memcache->delete($key)) {
if ($debug) ADOConnection::outp("CacheFlush: $key entery doesn't exist on memcached server!<br>\n");
} else {
if ($debug) ADOConnection::outp("CacheFlush: $key entery flushed from memcached server!<br>\n");
}
} else {
if (!$memcache->flush()) {
if ($debug) ADOConnection::outp("CacheFlush: Failure flushing all enteries from memcached server!<br>\n");
} else {
if ($debug) ADOConnection::outp("CacheFlush: All enteries flushed from memcached server!<br>\n");
}
}
return;
}
?>
?>
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -60,7 +60,7 @@ class ADODB_Pager {
global $PHP_SELF;
$curr_page = $id.'_curr_page';
if (empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
if (!empty($PHP_SELF)) $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); // htmlspecialchars() to prevent XSS attacks
$this->sql = $sql;
$this->id = $id;
+2 -2
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
@@ -211,7 +211,7 @@ class DB
function isError($value)
{
if (!is_object($value)) return false;
$class = get_class($value);
$class = strtolower(get_class($value));
return $class == 'pear_error' || is_subclass_of($value, 'pear_error') ||
$class == 'db_error' || is_subclass_of($value, 'db_error');
}
+54 -41
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -70,9 +70,9 @@ function adodb_log_sql(&$connx,$sql,$inputarr)
{
$perf_table = adodb_perf::table();
$connx->fnExecute = false;
$t0 = microtime();
$a0 = microtime(true);
$rs = $connx->Execute($sql,$inputarr);
$t1 = microtime();
$a1 = microtime(true);
if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
global $ADODB_LOG_CONN;
@@ -91,12 +91,6 @@ function adodb_log_sql(&$connx,$sql,$inputarr)
$conn->_logsql = false; // disable logsql error simulation
$dbT = $conn->databaseType;
$a0 = split(' ',$t0);
$a0 = (float)$a0[1]+(float)$a0[0];
$a1 = split(' ',$t1);
$a1 = (float)$a1[1]+(float)$a1[0];
$time = $a1 - $a0;
if (!$rs) {
@@ -117,9 +111,9 @@ function adodb_log_sql(&$connx,$sql,$inputarr)
}
if (isset($_SERVER['HTTP_HOST'])) {
$tracer .= '<br>'.$_SERVER['HTTP_HOST'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= htmlspecialchars($_SERVER['PHP_SELF']);
} else
if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.htmlspecialchars($_SERVER['PHP_SELF']);
//$tracer .= (string) adodb_backtrace(false);
$tracer = (string) substr($tracer,0,500);
@@ -264,7 +258,7 @@ processes 69293
*/
// Algorithm is taken from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
// http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/414b0e1b-499c-411e-8a02-6a12e339c0f1/
if (strncmp(PHP_OS,'WIN',3)==0) {
if (PHP_VERSION == '5.0.0') return false;
if (PHP_VERSION == '5.0.1') return false;
@@ -272,14 +266,33 @@ processes 69293
if (PHP_VERSION == '5.0.3') return false;
if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
@$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
if (!$c) return false;
static $FAIL = false;
if ($FAIL) return false;
$objName = "winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\CIMV2";
$myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'";
try {
@$objWMIService = new COM($objName);
if (!$objWMIService) {
$FAIL = true;
return false;
}
$info[0] = -1;
$info[1] = 0;
$info[2] = 0;
$info[3] = 0;
foreach($objWMIService->ExecQuery($myQuery) as $objItem) {
$info[0] = $objItem->PercentProcessorTime();
}
} catch(Exception $e) {
$FAIL = true;
echo $e->getMessage();
return false;
}
$info[0] = $c->PercentProcessorTime;
$info[1] = 0;
$info[2] = 0;
$info[3] = $c->TimeStamp_Sys100NS;
//print_r($info);
return $info;
}
@@ -342,27 +355,26 @@ Committed_AS: 348732 kB
{
$info = $this->_CPULoad();
if (!$info) return false;
if (empty($this->_lastLoad)) {
sleep(1);
$this->_lastLoad = $info;
$info = $this->_CPULoad();
}
$last = $this->_lastLoad;
$this->_lastLoad = $info;
$d_user = $info[0] - $last[0];
$d_nice = $info[1] - $last[1];
$d_system = $info[2] - $last[2];
$d_idle = $info[3] - $last[3];
//printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
if (strncmp(PHP_OS,'WIN',3)==0) {
if ($d_idle < 1) $d_idle = 1;
return 100*(1-$d_user/$d_idle);
return (integer) $info[0];
}else {
if (empty($this->_lastLoad)) {
sleep(1);
$this->_lastLoad = $info;
$info = $this->_CPULoad();
}
$last = $this->_lastLoad;
$this->_lastLoad = $info;
$d_user = $info[0] - $last[0];
$d_nice = $info[1] - $last[1];
$d_system = $info[2] - $last[2];
$d_idle = $info[3] - $last[3];
//printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
$total=$d_user+$d_nice+$d_system+$d_idle;
if ($total<1) $total=1;
return 100*($d_user+$d_nice+$d_system)/$total;
@@ -727,8 +739,9 @@ Committed_AS: 348732 kB
echo $this->CheckMemory();
break;
case 'poll':
$self = htmlspecialchars($_SERVER['PHP_SELF']);
echo "<iframe width=720 height=80%
src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
src=\"{$self}?do=poll2&hidem=1\"></iframe>";
break;
case 'poll2':
echo "<pre>";
@@ -751,7 +764,7 @@ Committed_AS: 348732 kB
echo $this->Tables(); break;
}
global $ADODB_vers;
echo "<p><div class='mdl-align'><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
}
/*
@@ -905,7 +918,7 @@ Committed_AS: 348732 kB
{
$PHP_SELF = $_SERVER['PHP_SELF'];
$PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']);
$sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
@@ -1085,4 +1098,4 @@ Committed_AS: 348732 kB
// end hack
}
?>
?>
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
-1
View File
@@ -1006,7 +1006,6 @@ function adodb_tz_offset($gmt,$isphp5)
return sprintf('%s%02d%02d',($gmt<=0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
else
return sprintf('%s%02d%02d',($gmt<0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60);
break;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+221 -197
View File
@@ -12,9 +12,9 @@
*/
/**
\mainpage
\mainpage
@version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
@version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license. You can choose which license
you prefer.
@@ -54,9 +54,12 @@
$ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_EXTENSION, // ADODB extension installed
$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
$ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
//==============================================================================================
@@ -119,6 +122,7 @@
die("PHP5 or later required. You are running ".PHP_VERSION);
}
//if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
@@ -146,12 +150,16 @@
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_FETCH_MODE,
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_FORCE_TYPE,
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES;
if (empty($ADODB_CACHE_CLASS)) $ADODB_CACHE_CLASS = 'ADODB_Cache_File' ;
$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
$ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
$ADODB_GETONE_EOF = null;
if (!isset($ADODB_CACHE_DIR)) {
$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
@@ -169,7 +177,7 @@
/**
* ADODB version as a string.
*/
$ADODB_vers = 'V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
$ADODB_vers = 'V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
/**
* Determines whether recordset->RecordCount() is used.
@@ -208,7 +216,7 @@
*/
}
// for transaction handling
function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
{
@@ -220,6 +228,95 @@
}
}
//------------------
// class for caching
class ADODB_Cache_File {
var $createdir = true; // requires creation of temp dirs
function ADODB_Cache_File()
{
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
}
// write serialised recordset to cache item/file
function writecache($filename, $contents, $debug, $secs2cache)
{
return adodb_write_file($filename, $contents,$debug);
}
// load serialised recordset and unserialise it
function &readcache($filename, &$err, $secs2cache, $rsClass)
{
$rs = csv2rs($filename,$err,$secs2cache,$rsClass);
return $rs;
}
// flush all items in cache
function flushall($debug=false)
{
global $ADODB_CACHE_DIR;
$rez = false;
if (strlen($ADODB_CACHE_DIR) > 1) {
$rez = $this->_dirFlush($ADODB_CACHE_DIR);
if ($debug) ADOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
}
return $rez;
}
// flush one file in cache
function flushcache($f, $debug=false)
{
if (!@unlink($f)) {
if ($debug) ADOConnection::outp( "flushcache: failed for $f");
}
}
function getdirname($hash)
{
global $ADODB_CACHE_DIR;
if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
}
// create temp directories
function createdir($hash, $debug)
{
$dir = $this->getdirname($hash);
if ($this->notSafeMode && !file_exists($dir)) {
$oldu = umask(0);
if (!@mkdir($dir,0771)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
umask($oldu);
}
return $dir;
}
/**
* Private function to erase all of the files and subdirectories in a directory.
*
* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
* Note: $kill_top_level is used internally in the function to flush subdirectories.
*/
function _dirFlush($dir, $kill_top_level = false)
{
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
$f = $dir.'/'.$obj;
if (strpos($obj,'.cache')) @unlink($f);
if (is_dir($f)) $this->_dirFlush($f, true);
}
if ($kill_top_level === true) @rmdir($dir);
return true;
}
}
//==============================================================================================
// CLASS ADOConnection
//==============================================================================================
@@ -417,6 +514,10 @@
if ($argDatabaseName != "") $this->database = $argDatabaseName;
$this->_isPersistentConnection = false;
global $ADODB_CACHE;
if (empty($ADODB_CACHE)) $this->_CreateCache();
if ($forceNew) {
if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
} else {
@@ -472,6 +573,7 @@
*/
function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
{
if (defined('ADODB_NEVER_PERSIST'))
return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
@@ -481,6 +583,10 @@
if ($argDatabaseName != "") $this->database = $argDatabaseName;
$this->_isPersistentConnection = true;
global $ADODB_CACHE;
if (empty($ADODB_CACHE)) $this->_CreateCache();
if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
if (isset($rez)) {
$err = $this->ErrorMsg();
@@ -508,6 +614,21 @@
ADOConnection::outp($msg);
}
// create cache class. Code is backward compat with old memcache implementation
function _CreateCache()
{
global $ADODB_CACHE, $ADODB_CACHE_CLASS;
if ($this->memCache) {
global $ADODB_INCLUDED_MEMCACHE;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
$ADODB_CACHE = new ADODB_Cache_MemCache($this);
} else
$ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
@@ -745,7 +866,7 @@
{
if ($this->transOff > 0) {
$this->transOff += 1;
return;
return true;
}
$this->_oldRaiseFn = $this->raiseErrorFn;
@@ -753,8 +874,9 @@
$this->_transOK = true;
if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
$this->BeginTrans();
$ok = $this->BeginTrans();
$this->transOff = 1;
return $ok;
}
@@ -839,7 +961,7 @@
if (!is_array($sql) && !$this->_bindInputArray) {
$sqlarr = explode('?',$sql);
$nparams = sizeof($sqlarr)-1;
if (!$array_2d) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
@@ -864,7 +986,9 @@
else
$sql .= $v;
$i += 1;
}
if ($i == $nparams) break;
} // while
if (isset($sqlarr[$i])) {
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
@@ -1181,13 +1305,10 @@
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
if ($offset>0){
if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
else $rs = $this->Execute($sql,$inputarr);
} else {
if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
else $rs = $this->Execute($sql,$inputarr);
}
if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
else $rs = $this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $savec;
if ($rs && !$rs->EOF) {
$rs = $this->_rs2rs($rs,$nrows,$offset);
@@ -1300,14 +1421,14 @@
*/
function GetOne($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$ret = false;
$rs = $this->Execute($sql,$inputarr);
if ($rs) {
if ($rs->EOF) $ret = null;
if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
else $ret = reset($rs->fields);
$rs->Close();
@@ -1316,12 +1437,26 @@
return $ret;
}
// $where should include 'WHERE fld=value'
function GetMedian($table, $field,$where = '')
{
$total = $this->GetOne("select count(*) from $table $where");
if (!$total) return false;
$midrow = (integer) ($total/2);
$rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
if ($rs && !$rs->EOF) return reset($rs->fields);
return false;
}
function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
{
global $ADODB_GETONE_EOF;
$ret = false;
$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
if ($rs) {
if ($rs->EOF) $ret = null;
if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
else $ret = reset($rs->fields);
$rs->Close();
}
@@ -1456,7 +1591,7 @@
function GetRandRow($sql, $arr= false)
{
$rezarr = $this->GetAll($sql, $arr);
$sz = sizeof($rez);
$sz = sizeof($rezarr);
return $rezarr[abs(rand()) % $sz];
}
@@ -1573,103 +1708,17 @@
*/
function CacheFlush($sql=false,$inputarr=false)
{
global $ADODB_CACHE_DIR;
if ($this->memCache) {
global $ADODB_INCLUDED_MEMCACHE;
global $ADODB_CACHE_DIR, $ADODB_CACHE;
$key = false;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
return;
}
if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
/*if (strncmp(PHP_OS,'WIN',3) === 0)
$dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
else */
$dir = $ADODB_CACHE_DIR;
if ($this->debug) {
ADOConnection::outp( "CacheFlush: $dir<br><pre>\n". $this->_dirFlush($dir)."</pre>");
} else {
$this->_dirFlush($dir);
}
return;
}
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
$f = $this->_gencachename($sql.serialize($inputarr),false);
adodb_write_file($f,''); // is adodb_write_file needed?
if (!@unlink($f)) {
if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
}
}
/**
* Private function to erase all of the files and subdirectories in a directory.
*
* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
* Note: $kill_top_level is used internally in the function to flush subdirectories.
*
*/
function _dirFlush($dir, $kill_top_level = false)
{
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
$f = $dir.'/'.$obj;
if (strpos($obj,'.cache')) @unlink($f);
if (is_dir($f)) $this->_dirFlush($f, true);
}
if ($kill_top_level === true) @rmdir($dir);
return true;
}
// this only deletes .cache files
function xCacheFlush($sql=false,$inputarr=false)
{
global $ADODB_CACHE_DIR;
if ($this->memCache) {
global $ADODB_INCLUDED_MEMCACHE;
$key = false;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
flushmemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
return;
}
if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
if (strncmp(PHP_OS,'WIN',3) === 0) {
$cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
} else {
//$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
$cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';
// old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
}
if ($this->debug) {
ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
} else {
exec($cmd);
}
return;
}
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
if (!$sql) {
$ADODB_CACHE->flushall($this->debug);
return;
}
$f = $this->_gencachename($sql.serialize($inputarr),false);
adodb_write_file($f,''); // is adodb_write_file needed?
if (!@unlink($f)) {
if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
}
return $ADODB_CACHE->flushcache($f, $this->debug);
}
/**
* Private function to generate filename for caching.
@@ -1685,10 +1734,9 @@
* 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,$memcache=false)
function _gencachename($sql,$createdir)
{
global $ADODB_CACHE_DIR;
static $notSafeMode;
global $ADODB_CACHE, $ADODB_CACHE_DIR;
if ($this->fetchMode === false) {
global $ADODB_FETCH_MODE;
@@ -1697,17 +1745,10 @@
$mode = $this->fetchMode;
}
$m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
if ($memcache) return $m;
if (!$ADODB_CACHE->createdir) return $m;
if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
else $dir = $ADODB_CACHE->createdir($m, $this->debug);
if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
$dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
if ($createdir && $notSafeMode && !file_exists($dir)) {
$oldu = umask(0);
if (!@mkdir($dir,0771))
if(!is_dir($dir) && $this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
umask($oldu);
}
return $dir.'/adodb_'.$m.'.cache';
}
@@ -1723,6 +1764,8 @@
*/
function CacheExecute($secs2cache,$sql=false,$inputarr=false)
{
global $ADODB_CACHE;
if (!is_numeric($secs2cache)) {
$inputarr = $sql;
$sql = $secs2cache;
@@ -1735,30 +1778,19 @@
} else
$sqlparam = $sql;
if ($this->memCache) {
global $ADODB_INCLUDED_MEMCACHE;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
$md5file = $this->_gencachename($sql.serialize($inputarr),false,true);
} else {
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
$md5file = $this->_gencachename($sql.serialize($inputarr),true);
}
$md5file = $this->_gencachename($sql.serialize($inputarr),true);
$err = '';
if ($secs2cache > 0){
if ($this->memCache)
$rs = getmemCache($md5file,$err,$secs2cache, $this->memCacheHost, $this->memCachePort);
else
$rs = csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
$rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass);
$this->numCacheHits += 1;
} else {
$err='Timeout 1';
$rs = false;
$this->numCacheMisses += 1;
}
if (!$rs) {
// no cached rs found
if ($this->debug) {
@@ -1770,19 +1802,14 @@
$rs = $this->Execute($sqlparam,$inputarr);
if ($rs && $this->memCache) {
$rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
if(!putmemCache($md5file, $rs, $this->memCacheHost, $this->memCachePort, $this->memCacheCompress, $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");
}
} else if ($rs) {
if ($rs) {
$eof = $rs->EOF;
$rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
$rs->timeCreated = time(); // used by caching
$txt = _rs2serialize($rs,false,$sql); // serialize
$ok = adodb_write_file($md5file,$txt,$this->debug);
$ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache);
if (!$ok) {
if ($ok === false) {
$em = 'Cache write error';
@@ -1805,9 +1832,8 @@
$rs->connection = $this; // Pablo suggestion
}
} else
if (!$this->memCache)
@unlink($md5file);
} else if (!$this->memCache)
$ADODB_CACHE->flushcache($md5file);
} else {
$this->_errorMsg = '';
$this->_errorCode = 0;
@@ -2068,41 +2094,29 @@
}
}
function GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
/**
* GetActiveRecordsClass Performs an 'ALL' query
*
* @param mixed $class This string represents the class of the current active record
* @param mixed $table Table used by the active record object
* @param mixed $whereOrderBy Where, order, by clauses
* @param mixed $bindarr
* @param mixed $primkeyArr
* @param array $extra Query extras: limit, offset...
* @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo"
* @access public
* @return void
*/
function GetActiveRecordsClass(
$class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false,
$extra=array(),
$relations=array())
{
global $_ADODB_ACTIVE_DBS;
$save = $this->SetFetchMode(ADODB_FETCH_NUM);
if (empty($whereOrderBy)) $whereOrderBy = '1=1';
$rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
$this->SetFetchMode($save);
$false = false;
if ($rows === false) {
return $false;
}
if (!isset($_ADODB_ACTIVE_DBS)) {
include(ADODB_DIR.'/adodb-active-record.inc.php');
}
if (!class_exists($class)) {
$this->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
return $false;
}
$arr = array();
foreach($rows as $row) {
$obj = new $class($table,$primkeyArr,$this);
if ($obj->ErrorMsg()){
$this->_errorMsg = $obj->ErrorMsg();
return $false;
}
$obj->Set($row);
$arr[] = $obj;
}
return $arr;
## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
}
function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
@@ -2420,10 +2434,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
*
* @return date string in database date format
*/
function DBDate($d)
function DBDate($d, $isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return $d;
if (is_string($d) && !is_numeric($d)) {
if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
if ($this->isoDates) return "'$d'";
@@ -2457,10 +2472,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
*
* @return timestamp string in database timestamp format
*/
function DBTimeStamp($ts)
function DBTimeStamp($ts,$isfld=false)
{
if (empty($ts) && $ts !== 0) return 'null';
if ($isfld) return $ts;
# strlen(14) allows YYYYMMDDHHMMSS format
if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
return adodb_date($this->fmtTimeStamp,$ts);
@@ -2719,12 +2735,12 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
function key()
{
return $false;
return false;
}
function current()
{
return $false;
return false;
}
function next()
@@ -3670,6 +3686,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
'CHARACTER' => 'C',
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
'VAR_STRING' => 'C', # mysql
##
'LONGCHAR' => 'X',
'TEXT' => 'X',
@@ -3693,6 +3710,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
##
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
##
'SMALLDATETIME' => 'T',
'TIME' => 'T',
'TIMESTAMP' => 'T',
'DATETIME' => 'T',
@@ -4139,8 +4157,12 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
if (strncmp($origdsn,'pdo',3) == 0) {
$sch = explode('_',$dsna['scheme']);
if (sizeof($sch)>1) {
$dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
$dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
if ($sch[1] == 'sqlite')
$dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host']));
else
$dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
$dsna['scheme'] = 'pdo';
}
}
@@ -4172,7 +4194,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
if (!empty($ADODB_NEWCONNECTION)) {
$obj = $ADODB_NEWCONNECTION($db);
} else {
}
if(empty($obj)) {
if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
if (empty($db)) $db = $ADODB_LASTDB;
@@ -4347,13 +4371,13 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1
@param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
@param levels Number of levels to display
*/
function adodb_backtrace($printOrArr=true,$levels=9999)
function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null)
{
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
return _adodb_backtrace($printOrArr,$levels);
return _adodb_backtrace($printOrArr,$levels,0,$ishtml);
}
}
?>
?>
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -49,7 +49,7 @@ class ADODB2_access extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'COUNTER';
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -47,7 +47,7 @@ class ADODB2_db2 extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -93,7 +93,7 @@ class ADODB2_firebird extends ADODB_DataDict {
}
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -62,7 +62,7 @@ class ADODB2_informix extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'SERIAL';
+3 -3
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -69,7 +69,7 @@ class ADODB2_mssql extends ADODB_DataDict {
case 'TINYINT': return 'I1';
case 'SMALLINT': return 'I2';
case 'BIGINT': return 'I8';
case 'SMALLDATETIME': return 'T';
case 'REAL':
case 'FLOAT': return 'F';
default: return parent::MetaType($t,$len,$fieldobj);
@@ -151,7 +151,7 @@ class ADODB2_mssql extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
@@ -0,0 +1,282 @@
<?php
/**
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
/*
In ADOdb, named quotes for MS SQL Server use ". From the MSSQL Docs:
Note Delimiters are for identifiers only. Delimiters cannot be used for keywords,
whether or not they are marked as reserved in SQL Server.
Quoted identifiers are delimited by double quotation marks ("):
SELECT * FROM "Blanks in Table Name"
Bracketed identifiers are delimited by brackets ([ ]):
SELECT * FROM [Blanks In Table Name]
Quoted identifiers are valid only when the QUOTED_IDENTIFIER option is set to ON. By default,
the Microsoft OLE DB Provider for SQL Server and SQL Server ODBC driver set QUOTED_IDENTIFIER ON
when they connect.
In Transact-SQL, the option can be set at various levels using SET QUOTED_IDENTIFIER,
the quoted identifier option of sp_dboption, or the user options option of sp_configure.
When SET ANSI_DEFAULTS is ON, SET QUOTED_IDENTIFIER is enabled.
Syntax
SET QUOTED_IDENTIFIER { ON | OFF }
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
class ADODB2_mssqlnative extends ADODB_DataDict {
var $databaseType = 'mssqlnative';
var $dropIndex = 'DROP INDEX %2$s.%1$s';
var $renameTable = "EXEC sp_rename '%s','%s'";
var $renameColumn = "EXEC sp_rename '%s.%s','%s'";
var $typeX = 'TEXT'; ## Alternatively, set it to VARCHAR(4000)
var $typeXL = 'TEXT';
//var $alterCol = ' ALTER COLUMN ';
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'R':
case 'INT':
case 'INTEGER': return 'I';
case 'BIT':
case 'TINYINT': return 'I1';
case 'SMALLINT': return 'I2';
case 'BIGINT': return 'I8';
case 'REAL':
case 'FLOAT': return 'F';
default: return parent::MetaType($t,$len,$fieldobj);
}
}
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL': return (isset($this)) ? $this->typeXL : 'TEXT';
case 'X': return (isset($this)) ? $this->typeX : 'TEXT'; ## could be varchar(8000), but we want compat with oracle
case 'C2': return 'NVARCHAR';
case 'X2': return 'NTEXT';
case 'B': return 'IMAGE';
case 'D': return 'DATETIME';
case 'T': return 'DATETIME';
case 'L': return 'BIT';
case 'R':
case 'I': return 'INT';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INT';
case 'I8': return 'BIGINT';
case 'F': return 'REAL';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname $this->addCol";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
/*
function AlterColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
*/
function DropColumnSQL($tabname, $flds)
{
$tabname = $this->TableName ($tabname);
if (!is_array($flds))
$flds = explode(',',$flds);
$f = array();
$s = 'ALTER TABLE ' . $tabname;
foreach($flds as $v) {
$f[] = "\n$this->dropCol ".$this->NameQuote($v);
}
$s .= implode(', ',$f);
$sql[] = $s;
return $sql;
}
// return string must begin with space
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
if ($fnotnull) $suffix .= ' NOT NULL';
else if ($suffix == '') $suffix .= ' NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }
| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)
[ ON { filegroup | DEFAULT } ]
[ TEXTIMAGE_ON { filegroup | DEFAULT } ]
< column_definition > ::= { column_name data_type }
[ COLLATE < collation_name > ]
[ [ DEFAULT constant_expression ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL]
[ < column_constraint > ] [ ...n ]
< column_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[ WITH FILLFACTOR = fillfactor ]
[ON {filegroup | DEFAULT} ] ]
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
]
| CHECK [ NOT FOR REPLICATION ]
( logical_expression )
}
< table_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
{ ( column [ ASC | DESC ] [ ,...n ] ) }
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ]
( search_conditions )
}
*/
/*
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
[ WITH < index_option > [ ,...n] ]
[ ON filegroup ]
< index_option > :: =
{ PAD_INDEX |
FILLFACTOR = fillfactor |
IGNORE_DUP_KEY |
DROP_EXISTING |
STATISTICS_NORECOMPUTE |
SORT_IN_TEMPDB
}
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
$sql = array();
if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
$sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
if ( isset($idxoptions['DROP']) )
return $sql;
}
if ( empty ($flds) ) {
return $sql;
}
$unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
$clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
if ( is_array($flds) )
$flds = implode(', ',$flds);
$s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
if ( isset($idxoptions[$this->upperName]) )
$s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
function _GetSize($ftype, $ty, $fsize, $fprec)
{
switch ($ftype) {
case 'INT':
case 'SMALLINT':
case 'TINYINT':
case 'BIGINT':
return $ftype;
}
if ($ty == 'T') return $ftype;
return parent::_GetSize($ftype, $ty, $fsize, $fprec);
}
}
?>
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -107,7 +107,7 @@ class ADODB2_mysql extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
+10 -9
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -82,15 +82,16 @@ class ADODB2_oci8 extends ADODB_DataDict {
case 'D':
case 'T': return 'DATE';
case 'L': return 'DECIMAL(1)';
case 'I1': return 'DECIMAL(3)';
case 'I2': return 'DECIMAL(5)';
case 'L': return 'NUMBER(1)';
case 'I1': return 'NUMBER(3)';
case 'I2': return 'NUMBER(5)';
case 'I':
case 'I4': return 'DECIMAL(10)';
case 'I4': return 'NUMBER(10)';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'DECIMAL';
case 'N': return 'DECIMAL';
case 'I8': return 'NUMBER(20)';
case 'F': return 'NUMBER';
case 'N': return 'NUMBER';
case 'R': return 'NUMBER(20)';
default:
return $meta;
}
@@ -156,7 +157,7 @@ class ADODB2_oci8 extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -326,7 +326,7 @@ class ADODB2_postgres extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
if ($fautoinc) {
$ftype = 'SERIAL';
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V4.50 6 July 2004 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V4.50 6 July 2004 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -80,7 +80,7 @@ class ADODB2_sapdb extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
+2 -2
View File
@@ -1,7 +1,7 @@
<?php
/**
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -113,7 +113,7 @@ class ADODB2_sybase extends ADODB_DataDict {
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+21 -5
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -221,11 +221,27 @@ class ADODB_ado extends ADOConnection {
$oCmd->CommandText = $sql;
$oCmd->CommandType = 1;
foreach($inputarr as $val) {
// Map by http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthcreateparam.asp
// Check issue http://bugs.php.net/bug.php?id=40664 !!!
while(list(, $val) = each($inputarr)) {
$type = gettype($val);
$len=strlen($val);
if ($type == 'boolean')
$this->adoParameterType = 11;
else if ($type == 'integer')
$this->adoParameterType = 3;
else if ($type == 'double')
$this->adoParameterType = 5;
elseif ($type == 'string')
$this->adoParameterType = 202;
else if (($val === null) || (!defined($val)))
$len=1;
else
$this->adoParameterType = 130;
// name, type, direction 1 = input, len,
$this->adoParameterType = 130;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
//print $p->Type.' '.$p->value;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);
$oCmd->Parameters->Append($p);
}
$p = false;
+33 -7
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -70,7 +70,8 @@ class ADODB_ado extends ADOConnection {
} else {
$argDatabasename = '';
if ($argDBorProvider) $argProvider = $argDBorProvider;
else $argProvider = 'MSDASQL';
else if (stripos($argHostname,'PROVIDER') === false) /* full conn string is not in $argHostname */
$argProvider = 'MSDASQL';
}
@@ -117,6 +118,7 @@ class ADODB_ado extends ADOConnection {
$dbc->CursorLocation = $this->_cursor_location;
return $dbc->State > 0;
} catch (exception $e) {
if ($this->debug);echo "<pre>",$argHostname,"\n",$e,"</pre>\n";
}
return false;
@@ -244,13 +246,28 @@ class ADODB_ado extends ADOConnection {
$oCmd->CommandText = $sql;
$oCmd->CommandType = 1;
foreach($inputarr as $val) {
while(list(, $val) = each($inputarr)) {
$type = gettype($val);
$len=strlen($val);
if ($type == 'boolean')
$this->adoParameterType = 11;
else if ($type == 'integer')
$this->adoParameterType = 3;
else if ($type == 'double')
$this->adoParameterType = 5;
elseif ($type == 'string')
$this->adoParameterType = 202;
else if (($val === null) || (!defined($val)))
$len=1;
else
$this->adoParameterType = 130;
// name, type, direction 1 = input, len,
$this->adoParameterType = 130;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
//print $p->Type.' '.$p->value;
$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);
$oCmd->Parameters->Append($p);
}
$p = false;
$rs = $oCmd->Execute();
$e = $dbc->Errors;
@@ -375,6 +392,8 @@ class ADORecordSet_ado extends ADORecordSet {
$o= new ADOFieldObject();
$rs = $this->_queryID;
if (!$rs) return false;
$f = $rs->Fields($fieldOffset);
$o->name = $f->Name;
$t = $f->Type;
@@ -406,8 +425,12 @@ class ADORecordSet_ado extends ADORecordSet {
function _initrs()
{
$rs = $this->_queryID;
$this->_numOfRows = $rs->RecordCount;
try {
$this->_numOfRows = $rs->RecordCount;
} catch (Exception $e) {
$this->_numOfRows = -1;
}
$f = $rs->Fields;
$this->_numOfFields = $f->Count;
}
@@ -669,7 +692,10 @@ class ADORecordSet_ado extends ADORecordSet {
function _close() {
$this->_flds = false;
try {
@$this->_queryID->Close();// by Pete Dishman ([email protected])
} catch (Exception $e) {
}
$this->_queryID = false;
}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+7 -7
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2006 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.06 16 Oct 2008 (c) 2006 John Lim (jlim#natsoft.com). All rights reserved.
This is a version of the ADODB driver for DB2. It uses the 'ibm_db2' PECL extension
for PHP (http://pecl.php.net/package/ibm_db2), which in turn requires DB2 V8.2.2 or
@@ -33,7 +33,7 @@ class ADODB_db2 extends ADOConnection {
var $sysDate = 'CURRENT DATE';
var $sysTimeStamp = 'CURRENT TIMESTAMP';
var $fmtTimeStamp = "'Y-m-d-H:i:s'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $replaceQuote = "''"; // string to use to replace quotes
var $dataProvider = "db2";
var $hasAffectedRows = true;
@@ -44,7 +44,7 @@ class ADODB_db2 extends ADOConnection {
// breaking backward-compat
var $_bindInputArray = false;
var $_genIDSQL = "VALUES NEXTVAL FOR %s";
var $_genSeqSQL = "CREATE SEQUENCE %s START WITH 1 NO MAXVALUE NO CYCLE";
var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s NO MAXVALUE NO CYCLE";
var $_dropSeqSQL = "DROP SEQUENCE %s";
var $_autocommit = true;
var $_haserrorfunctions = true;
@@ -68,7 +68,7 @@ class ADODB_db2 extends ADOConnection {
global $php_errormsg;
if (!function_exists('db2_connect')) {
ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension.");
ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension which is not installed.");
return null;
}
// This needs to be set before the connect().
@@ -228,7 +228,7 @@ class ADODB_db2 extends ADOConnection {
function CreateSequence($seqname='adodbseq',$start=1)
{
if (empty($this->_genSeqSQL)) return false;
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$start));
if (!$ok) return false;
return true;
}
@@ -249,9 +249,9 @@ class ADODB_db2 extends ADOConnection {
{
// if you have to modify the parameter below, your database is overloaded,
// or you need to implement generation of id's yourself!
$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
$num = $this->GetOne("VALUES NEXTVAL FOR $seq");
return $num;
}
}
function ErrorMsg()
+2 -2
View File
@@ -1,6 +1,6 @@
<?php
/*
@version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
@version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -127,7 +127,7 @@ class ADODB_fbsql extends ADOConnection {
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
return fbsql_query("$sql;",$this->_connectionID);
}
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+2 -2
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -284,7 +284,7 @@ class ADODB_informix72 extends ADOConnection {
}
*/
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
+11 -7
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -55,13 +55,17 @@ class ADODB_ldap extends ADOConnection {
if ( !function_exists( 'ldap_connect' ) ) return null;
$conn_info = array( $host,$this->port);
if (strpos('ldap://',$host) === 0 || strpos('ldaps://',$host) === 0) {
$this->_connectionID = @ldap_connect($host);
} else {
$conn_info = array( $host,$this->port);
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
if ( strstr( $host, ':' ) ) {
$conn_info = split( ':', $host );
}
$this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] );
$this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] );
}
if (!$this->_connectionID) {
$e = 'Could not connect to ' . $conn_info[0];
$this->_errorMsg = $e;
@@ -150,7 +154,7 @@ class ADODB_ldap extends ADOConnection {
}
/* returns _queryID or false */
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$rs = @ldap_search( $this->_connectionID, $this->database, $sql );
$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql.': '.ldap_error($this->_connectionID);
+25 -15
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -103,6 +103,7 @@ class ADODB_mssql extends ADOConnection {
var $identitySQL = 'select SCOPE_IDENTITY()'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $uniqueOrderBy = true;
var $_bindInputArray = true;
var $forceNewConnect = false;
function ADODB_mssql()
{
@@ -156,7 +157,7 @@ class ADODB_mssql extends ADOConnection {
return $this->lastInsID; // InsID from sp_executesql call
} else {
return $this->GetOne($this->identitySQL);
}
}
}
function _affectedrows()
@@ -210,7 +211,11 @@ class ADODB_mssql extends ADOConnection {
if ($nrows > 0 && $offset <= 0) {
$sql = preg_replace(
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
$rs = $this->Execute($sql,$inputarr);
if ($secs2cache)
$rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
else
$rs = $this->Execute($sql,$inputarr);
} else
$rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
@@ -283,8 +288,8 @@ class ADODB_mssql extends ADOConnection {
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('BEGIN TRAN');
return true;
$ok = $this->Execute('BEGIN TRAN');
return $ok;
}
function CommitTrans($ok=true)
@@ -292,15 +297,15 @@ class ADODB_mssql extends ADOConnection {
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT TRAN');
return true;
$ok = $this->Execute('COMMIT TRAN');
return $ok;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK TRAN');
return true;
$ok = $this->Execute('ROLLBACK TRAN');
return $ok;
}
function SetTransactionMode( $transaction_mode )
@@ -365,7 +370,7 @@ class ADODB_mssql extends ADOConnection {
$indexes = array();
while ($row = $rs->FetchRow()) {
if (!$primary && $row[5]) continue;
if ($primary && !$row[5]) continue;
$indexes[$row[0]]['unique'] = $row[6];
$indexes[$row[0]]['columns'][] = $row[1];
@@ -508,11 +513,11 @@ order by constraint_name, referenced_table_name, keyno";
else return -1;
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
// returns true or false, newconnect supported since php 5.1.0.
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$newconnect=false)
{
if (!function_exists('mssql_pconnect')) return null;
$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
$this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword,$newconnect);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
@@ -535,6 +540,11 @@ order by constraint_name, referenced_table_name, keyno";
return true;
}
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
}
function Prepare($sql)
{
$sqlarr = explode('?',$sql);
@@ -659,7 +669,7 @@ order by constraint_name, referenced_table_name, keyno";
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$this->_errorMsg = false;
if (is_array($inputarr)) {
@@ -1051,4 +1061,4 @@ order by constraint_name, ordinal_position
http://www.databasejournal.com/scripts/article.php/1440551
*/
?>
?>
+2 -2
View File
@@ -9,7 +9,7 @@
// ADOdb - Database Abstraction Library for PHP //
// http://adodb.sourceforge.net/ //
// //
// Copyright (C) 2000-2008 John Lim (jlim\@natsoft.com.my) //
// Copyright (C) 2000-2009 John Lim (jlim\@natsoft.com.my) //
// All rights reserved. //
// Released under both BSD license and LGPL library license. //
// Whenever there is any discrepancy between the two licenses, //
@@ -58,7 +58,7 @@ class ADODB_mssql_n extends ADODB_mssql {
ADODB_mssql::ADODB_mssql();
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$sql = $this->_appendN($sql);
return ADODB_mssql::_query($sql,$inputarr);
+922
View File
@@ -0,0 +1,922 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Native mssql driver. Requires mssql client. Works on Windows.
http://www.microsoft.com/sql/technologies/php/default.mspx
To configure for Unix, see
http://phpbuilder.com/columns/alberto20000919.php3
$stream = sqlsrv_get_field($stmt, $index, SQLSRV_SQLTYPE_STREAM(SQLSRV_ENC_BINARY));
stream_filter_append($stream, "convert.iconv.ucs-2/utf-8"); // Voila, UTF-8 can be read directly from $stream
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
if (!function_exists('sqlsrv_configure')) {
die("mssqlnative extension not installed");
}
if (!function_exists('sqlsrv_set_error_handling')) {
function sqlsrv_set_error_handling($constant) {
sqlsrv_configure("WarningsReturnAsErrors", $constant);
}
}
if (!function_exists('sqlsrv_log_set_severity')) {
function sqlsrv_log_set_severity($constant) {
sqlsrv_configure("LogSeverity", $constant);
}
}
if (!function_exists('sqlsrv_log_set_subsystems')) {
function sqlsrv_log_set_subsystems($constant) {
sqlsrv_configure("LogSubsystems", $constant);
}
}
//----------------------------------------------------------------
// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002
// and this causes tons of problems because localized versions of
// MSSQL will return the dates in dmy or mdy order; and also the
// month strings depends on what language has been configured. The
// following two variables allow you to control the localization
// settings - Ugh.
//
// MORE LOCALIZATION INFO
// ----------------------
// To configure datetime, look for and modify sqlcommn.loc,
// typically found in c:\mssql\install
// Also read :
// http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918
// Alternatively use:
// CONVERT(char(12),datecol,120)
//
// Also if your month is showing as month-1,
// e.g. Jan 13, 2002 is showing as 13/0/2002, then see
// http://phplens.com/lens/lensforum/msgs.php?id=7048&x=1
// it's a localisation problem.
//----------------------------------------------------------------
// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc
if (ADODB_PHPVER >= 0x4300) {
// docs say 4.2.0, but testing shows only since 4.3.0 does it work!
ini_set('mssql.datetimeconvert',0);
} else {
global $ADODB_mssql_mths; // array, months must be upper-case
$ADODB_mssql_date_order = 'mdy';
$ADODB_mssql_mths = array(
'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
}
//---------------------------------------------------------------------------
// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,
// just after you connect to the database. Supports mdy and dmy only.
// Not required for PHP 4.2.0 and above.
function AutoDetect_MSSQL_Date_Order($conn)
{
global $ADODB_mssql_date_order;
$adate = $conn->GetOne('select getdate()');
if ($adate) {
$anum = (int) $adate;
if ($anum > 0) {
if ($anum > 31) {
//ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");
} else
$ADODB_mssql_date_order = 'dmy';
} else
$ADODB_mssql_date_order = 'mdy';
}
}
class ADODB_mssqlnative extends ADOConnection {
var $databaseType = "mssqlnative";
var $dataProvider = "mssqlnative";
var $replaceQuote = "''"; // string to use to replace quotes
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $substr = "substring";
var $length = 'len';
var $hasAffectedRows = true;
var $poorAffectedRows = false;
var $metaDatabasesSQL = "select name from sys.sysdatabases where name <> 'master'";
var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))";
var $metaColumnsSQL = # xtype==61 is datetime
"select c.name,t.name,c.length,
(case when c.xusertype=61 then 0 else c.xprec end),
(case when c.xusertype=61 then 0 else c.xscale end)
from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
var $hasGenID = true;
var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
var $sysTimeStamp = 'GetDate()';
var $maxParameterLen = 4000;
var $arrayClass = 'ADORecordSet_array_mssqlnative';
var $uniqueSort = true;
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; // for mssql7 or later
var $identitySQL = 'select SCOPE_IDENTITY()'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $uniqueOrderBy = true;
var $_bindInputArray = true;
var $_dropSeqSQL = "drop table %s";
function ADODB_mssqlnative()
{
if ($this->debug) {
error_log("<pre>");
sqlsrv_set_error_handling( SQLSRV_ERRORS_LOG_ALL );
sqlsrv_log_set_severity( SQLSRV_LOG_SEVERITY_ALL );
sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
sqlsrv_configure('warnings_return_as_errors', 0);
} else {
sqlsrv_set_error_handling(0);
sqlsrv_log_set_severity(0);
sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
sqlsrv_configure('warnings_return_as_errors', 0);
}
}
function ServerInfo()
{
global $ADODB_FETCH_MODE;
if ($this->fetchMode === false) {
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
} else
$savem = $this->SetFetchMode(ADODB_FETCH_NUM);
$arrServerInfo = sqlsrv_server_info($this->_connectionID);
$arr['description'] = $arrServerInfo['SQLServerName'].' connected to '.$arrServerInfo['CurrentDatabase'];
$arr['version'] = $arrServerInfo['SQLServerVersion'];//ADOConnection::_findvers($arr['description']);
return $arr;
}
function IfNull( $field, $ifNull )
{
return " ISNULL($field, $ifNull) "; // if MS SQL Server
}
function _insertid()
{
// SCOPE_IDENTITY()
// Returns the last IDENTITY value inserted into an IDENTITY column in
// the same scope. A scope is a module -- a stored procedure, trigger,
// function, or batch. Thus, two statements are in the same scope if
// they are in the same stored procedure, function, or batch.
return $this->GetOne($this->identitySQL);
}
function _affectedrows()
{
return sqlsrv_rows_affected($this->_queryID);
}
function CreateSequence($seq='adodbseq',$start=1)
{
if($this->debug) error_log("<hr>CreateSequence($seq,$start)");
sqlsrv_begin_transaction($this->_connectionID);
$start -= 1;
$this->Execute("create table $seq (id int)");//was float(53)
$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
if (!$ok) {
if($this->debug) error_log("<hr>Error: ROLLBACK");
sqlsrv_rollback($this->_connectionID);
return false;
}
sqlsrv_commit($this->_connectionID);
return true;
}
function GenID($seq='adodbseq',$start=1)
{
if($this->debug) error_log("<hr>GenID($seq,$start)");
sqlsrv_begin_transaction($this->_connectionID);
$ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
if (!$ok) {
$this->Execute("create table $seq (id int)");
$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
if (!$ok) {
if($this->debug) error_log("<hr>Error: ROLLBACK");
sqlsrv_rollback($this->_connectionID);
return false;
}
sqlsrv_commit($this->_connectionID);
return $start;
}
$num = $this->GetOne("select id from $seq");
sqlsrv_commit($this->_connectionID);
if($this->debug) error_log(" Returning: $num");
return $num;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '+';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "datename(yyyy,$col)";
break;
case 'M':
$s .= "convert(char(3),$col,0)";
break;
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
$s .= "datename(quarter,$col)";
break;
case 'D':
case 'd':
$s .= "replace(str(day($col),2),' ','0')";
break;
case 'h':
$s .= "substring(convert(char(14),$col,0),13,2)";
break;
case 'H':
$s .= "replace(str(datepart(hh,$col),2),' ','0')";
break;
case 'i':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
break;
case 's':
$s .= "replace(str(datepart(ss,$col),2),' ','0')";
break;
case 'a':
case 'A':
$s .= "substring(convert(char(19),$col,0),18,2)";
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $this->qstr($ch);
break;
}
}
return $s;
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
if ($this->debug) error_log('<hr>begin transaction');
sqlsrv_begin_transaction($this->_connectionID);
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if ($this->debug) error_log('<hr>commit transaction');
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
sqlsrv_commit($this->_connectionID);
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->debug) error_log('<hr>rollback transaction');
if ($this->transCnt) $this->transCnt -= 1;
sqlsrv_rollback($this->_connectionID);
return true;
}
function SetTransactionMode( $transaction_mode )
{
$this->_transmode = $transaction_mode;
if (empty($transaction_mode)) {
$this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
return;
}
if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
$this->Execute("SET TRANSACTION ".$transaction_mode);
}
/*
Usage:
$this->BeginTrans();
$this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables
# some operation on both tables table1 and table2
$this->CommitTrans();
See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
*/
function RowLock($tables,$where,$flds='top 1 null as ignore')
{
if (!$this->transCnt) $this->BeginTrans();
return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
}
function SelectDB($dbName)
{
$this->database = $dbName;
$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
if ($this->_connectionID) {
$rs = $this->Execute('USE '.$dbName);
if($rs) {
return true;
} else return false;
}
else return false;
}
function ErrorMsg()
{
$retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
if($retErrors != null) {
foreach($retErrors as $arrError) {
$this->_errorMsg .= "SQLState: ".$arrError[ 'SQLSTATE']."\n";
$this->_errorMsg .= "Error Code: ".$arrError[ 'code']."\n";
$this->_errorMsg .= "Message: ".$arrError[ 'message']."\n";
}
} else {
$this->_errorMsg = "No errors found";
}
return $this->_errorMsg;
}
function ErrorNo()
{
if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
$err = sqlsrv_errors(SQLSRV_ERR_ALL);
if($err[0]) return $err[0]['code'];
else return -1;
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!function_exists('sqlsrv_connect')) return null;
$connectionInfo = array("Database"=>$argDatabasename,'UID'=>$argUsername,'PWD'=>$argPassword);
if ($this->debug) error_log("<hr>connecting... hostname: $argHostname params: ".var_export($connectionInfo,true));
//if ($this->debug) error_log("<hr>_connectionID before: ".serialize($this->_connectionID));
if(!($this->_connectionID = sqlsrv_connect($argHostname,$connectionInfo))) {
if ($this->debug) error_log( "<hr><b>errors</b>: ".print_r( sqlsrv_errors(), true));
return false;
}
//if ($this->debug) error_log(" _connectionID after: ".serialize($this->_connectionID));
//if ($this->debug) error_log("<hr>defined functions: <pre>".var_export(get_defined_functions(),true)."</pre>");
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
//return null;//not implemented. NOTE: Persistent connections have no effect if PHP is used as a CGI program. (FastCGI!)
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function Prepare($sql)
{
$stmt = sqlsrv_prepare( $this->_connectionID, $sql);
if (!$stmt) return $sql;
return array($sql,$stmt);
}
// returns concatenated string
// MSSQL requires integers to be cast as strings
// automatically cast every datatype to VARCHAR(255)
// @author David Rogers (introspectshun)
function Concat()
{
$s = "";
$arr = func_get_args();
// Split single record on commas, if possible
if (sizeof($arr) == 1) {
foreach ($arr as $arg) {
$args = explode(',', $arg);
}
$arr = $args;
}
array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";'));
$s = implode('+',$arr);
if (sizeof($arr) > 0) return "$s";
return '';
}
/*
Unfortunately, it appears that mssql cannot handle varbinary > 255 chars
So all your blobs must be of type "image".
Remember to set in php.ini the following...
; Valid range 0 - 2147483647. Default = 4096.
mssql.textlimit = 0 ; zero to pass through
; Valid range 0 - 2147483647. Default = 4096.
mssql.textsize = 0 ; zero to pass through
*/
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
{
if (strtoupper($blobtype) == 'CLOB') {
$sql = "UPDATE $table SET $column='" . $val . "' WHERE $where";
return $this->Execute($sql) != false;
}
$sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";
return $this->Execute($sql) != false;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr=false)
{
$this->_errorMsg = false;
if (is_array($inputarr)) {
$rez = sqlsrv_query($this->_connectionID,$sql,$inputarr);
} else if (is_array($sql)) {
$rez = sqlsrv_query($this->_connectionID,$sql[1],$inputarr);
} else {
$rez = sqlsrv_query($this->_connectionID,$sql);
}
if ($this->debug) error_log("<hr>running query: ".var_export($sql,true)."<hr>input array: ".var_export($inputarr,true)."<hr>result: ".var_export($rez,true));//"<hr>connection: ".serialize($this->_connectionID)
//fix for returning true on anything besides select statements
if (is_array($sql)) $sql = $sql[1];
$sql = ltrim($sql);
if(stripos($sql, 'SELECT') !== 0 && $rez !== false) {
if ($this->debug) error_log(" isn't a select query, returning boolean true");
return true;
}
//end fix
if(!$rez) $rez = false;
return $rez;
}
// returns true or false
function _close()
{
if ($this->transCnt) $this->RollbackTrans();
$rez = @sqlsrv_close($this->_connectionID);
$this->_connectionID = false;
return $rez;
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
return ADORecordSet_array_mssql::UnixDate($v);
}
static function UnixTimeStamp($v)
{
return ADORecordSet_array_mssql::UnixTimeStamp($v);
}
function &MetaIndexes($table,$primary=false)
{
$table = $this->qstr($table);
$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
ORDER BY O.name, I.Name, K.keyno";
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$rs = $this->Execute($sql);
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
}
$indexes = array();
while ($row = $rs->FetchRow()) {
if (!$primary && $row[5]) continue;
$indexes[$row[0]]['unique'] = $row[6];
$indexes[$row[0]]['columns'][] = $row[1];
}
return $indexes;
}
function MetaForeignKeys($table, $owner=false, $upper=false)
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$table = $this->qstr(strtoupper($table));
$sql =
"select object_name(constid) as constraint_name,
col_name(fkeyid, fkey) as column_name,
object_name(rkeyid) as referenced_table_name,
col_name(rkeyid, rkey) as referenced_column_name
from sysforeignkeys
where upper(object_name(fkeyid)) = $table
order by constraint_name, referenced_table_name, keyno";
$constraints =& $this->GetArray($sql);
$ADODB_FETCH_MODE = $save;
$arr = false;
foreach($constraints as $constr) {
//print_r($constr);
$arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3];
}
if (!$arr) return false;
$arr2 = false;
foreach($arr as $k => $v) {
foreach($v as $a => $b) {
if ($upper) $a = strtoupper($a);
$arr2[$a] = $b;
}
}
return $arr2;
}
//From: Fernando Moreira <[email protected]>
function MetaDatabases()
{
$this->SelectDB("master");
$rs =& $this->Execute($this->metaDatabasesSQL);
$rows = $rs->GetRows();
$ret = array();
for($i=0;$i<count($rows);$i++) {
$ret[] = $rows[$i][0];
}
$this->SelectDB($this->database);
if($ret)
return $ret;
else
return false;
}
// "Stein-Aksel Basma" <[email protected]>
// tested with MSSQL 2000
function &MetaPrimaryKeys($table)
{
global $ADODB_FETCH_MODE;
$schema = '';
$this->_findschema($table,$schema);
if (!$schema) $schema = $this->database;
if ($schema) $schema = "and k.table_catalog like '$schema%'";
$sql = "select distinct k.column_name,ordinal_position from information_schema.key_column_usage k,
information_schema.table_constraints tc
where tc.constraint_name = k.constraint_name and tc.constraint_type =
'PRIMARY KEY' and k.table_name = '$table' $schema order by ordinal_position ";
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$a = $this->GetCol($sql);
$ADODB_FETCH_MODE = $savem;
if ($a && sizeof($a)>0) return $a;
$false = false;
return $false;
}
function &MetaTables($ttype=false,$showSchema=false,$mask=false)
{
if ($mask) {
$save = $this->metaTablesSQL;
$mask = $this->qstr(($mask));
$this->metaTablesSQL .= " AND name like $mask";
}
$ret =& ADOConnection::MetaTables($ttype,$showSchema);
if ($mask) {
$this->metaTablesSQL = $save;
}
return $ret;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_mssqlnative extends ADORecordSet {
var $databaseType = "mssqlnative";
var $canSeek = false;
var $fieldOffset = 0;
// _mths works only in non-localised system
function ADORecordset_mssqlnative($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
}
function _initrs()
{
global $ADODB_COUNTRECS;
if ($this->connection->debug) error_log("(before) ADODB_COUNTRECS: {$ADODB_COUNTRECS} _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}");
/*$retRowsAff = sqlsrv_rows_affected($this->_queryID);//"If you need to determine the number of rows a query will return before retrieving the actual results, appending a SELECT COUNT ... query would let you get that information, and then a call to next_result would move you to the "real" results."
error_log("rowsaff: ".serialize($retRowsAff));
$this->_numOfRows = ($ADODB_COUNTRECS)? $retRowsAff:-1;*/
$this->_numOfRows = -1;//not supported
$fieldmeta = sqlsrv_field_metadata($this->_queryID);
$this->_numOfFields = ($fieldmeta)? count($fieldmeta):-1;
if ($this->connection->debug) error_log("(after) _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}");
}
//Contributed by "Sven Axelsson" <[email protected]>
// get next resultset - requires PHP 4.0.5 or later
function NextRecordSet()
{
if (!sqlsrv_next_result($this->_queryID)) return false;
$this->_inited = false;
$this->bind = false;
$this->_currentRow = -1;
$this->Init();
return true;
}
/* Use associative array to get fields array */
function Fields($colname)
{
if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function &FetchField($fieldOffset = -1)
{
if ($this->connection->debug) error_log("<hr>fetchfield: $fieldOffset, fetch array: <pre>".print_r($this->fields,true)."</pre> backtrace: ".adodb_backtrace(false));
if ($fieldOffset != -1) $this->fieldOffset = $fieldOffset;
$arrKeys = array_keys($this->fields);
if(array_key_exists($this->fieldOffset,$arrKeys) && !array_key_exists($arrKeys[$this->fieldOffset],$this->fields)) {
$f = false;
} else {
$f = $this->fields[ $arrKeys[$this->fieldOffset] ];
if($fieldOffset == -1) $this->fieldOffset++;
}
if (empty($f)) {
$f = false;//PHP Notice: Only variable references should be returned by reference
}
return $f;
}
function _seek($row)
{
return false;//There is no support for cursors in the driver at this time. All data is returned via forward-only streams.
}
// speedup
function MoveNext()
{
if ($this->connection->debug) error_log("movenext()");
//if ($this->connection->debug) error_log("eof (beginning): ".$this->EOF);
if ($this->EOF) return false;
$this->_currentRow++;
if ($this->connection->debug) error_log("_currentRow: ".$this->_currentRow);
if ($this->_fetch()) return true;
$this->EOF = true;
//if ($this->connection->debug) error_log("eof (end): ".$this->EOF);
return false;
}
// INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4
// also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!
function _fetch($ignore_fields=false)
{
if ($this->connection->debug) error_log("_fetch()");
if ($this->fetchMode & ADODB_FETCH_ASSOC) {
if ($this->fetchMode & ADODB_FETCH_NUM) {
if ($this->connection->debug) error_log("fetch mode: both");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_BOTH);
} else {
if ($this->connection->debug) error_log("fetch mode: assoc");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_ASSOC);
}
if (ADODB_ASSOC_CASE == 0) {
foreach($this->fields as $k=>$v) {
$this->fields[strtolower($k)] = $v;
}
} else if (ADODB_ASSOC_CASE == 1) {
foreach($this->fields as $k=>$v) {
$this->fields[strtoupper($k)] = $v;
}
}
} else {
if ($this->connection->debug) error_log("fetch mode: num");
$this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_NUMERIC);
}
if(is_array($this->fields) && array_key_exists(1,$this->fields) && !array_key_exists(0,$this->fields)) {//fix fetch numeric keys since they're not 0 based
$arrFixed = array();
foreach($this->fields as $key=>$value) {
if(is_numeric($key)) {
$arrFixed[$key-1] = $value;
} else {
$arrFixed[$key] = $value;
}
}
//if($this->connection->debug) error_log("<hr>fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true));
$this->fields = $arrFixed;
}
if(is_array($this->fields)) {
foreach($this->fields as $key=>$value) {
if (is_object($value) && method_exists($value, 'format')) {//is DateTime object
$this->fields[$key] = $value->format("Y-m-d\TH:i:s\Z");
}
}
}
if($this->fields === null) $this->fields = false;
if ($this->connection->debug) error_log("<hr>after _fetch, fields: <pre>".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false));
return $this->fields;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
$rez = sqlsrv_free_stmt($this->_queryID);
$this->_queryID = false;
return $rez;
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
return ADORecordSet_array_mssqlnative::UnixDate($v);
}
static function UnixTimeStamp($v)
{
return ADORecordSet_array_mssqlnative::UnixTimeStamp($v);
}
}
class ADORecordSet_array_mssqlnative extends ADORecordSet_array {
function ADORecordSet_array_mssqlnative($id=-1,$mode=false)
{
$this->ADORecordSet_array($id,$mode);
}
// mssql uses a default date like Dec 30 2000 12:00AM
static function UnixDate($v)
{
if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
global $ADODB_mssql_mths,$ADODB_mssql_date_order;
//Dec 30 2000 12:00AM
if ($ADODB_mssql_date_order == 'dmy') {
if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
return parent::UnixDate($v);
}
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[1];
$themth = substr(strtoupper($rr[2]),0,3);
} else {
if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
return parent::UnixDate($v);
}
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[2];
$themth = substr(strtoupper($rr[1]),0,3);
}
$themth = $ADODB_mssql_mths[$themth];
if ($themth <= 0) return false;
// h-m-s-MM-DD-YY
return mktime(0,0,0,$themth,$theday,$rr[3]);
}
static function UnixTimeStamp($v)
{
if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
global $ADODB_mssql_mths,$ADODB_mssql_date_order;
//Dec 30 2000 12:00AM
if ($ADODB_mssql_date_order == 'dmy') {
if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[1];
$themth = substr(strtoupper($rr[2]),0,3);
} else {
if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$theday = $rr[2];
$themth = substr(strtoupper($rr[1]),0,3);
}
$themth = $ADODB_mssql_mths[$themth];
if ($themth <= 0) return false;
switch (strtoupper($rr[6])) {
case 'P':
if ($rr[4]<12) $rr[4] += 12;
break;
case 'A':
if ($rr[4]==12) $rr[4] = 0;
break;
default:
break;
}
// h-m-s-MM-DD-YY
return mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);
}
}
/*
Code Example 1:
select object_name(constid) as constraint_name,
object_name(fkeyid) as table_name,
col_name(fkeyid, fkey) as column_name,
object_name(rkeyid) as referenced_table_name,
col_name(rkeyid, rkey) as referenced_column_name
from sysforeignkeys
where object_name(fkeyid) = x
order by constraint_name, table_name, referenced_table_name, keyno
Code Example 2:
select constraint_name,
column_name,
ordinal_position
from information_schema.key_column_usage
where constraint_catalog = db_name()
and table_name = x
order by constraint_name, ordinal_position
http://www.databasejournal.com/scripts/article.php/1440551
*/
?>
+2 -2
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
@@ -45,7 +45,7 @@ class ADODB_mssqlpo extends ADODB_mssql {
return array($sql,$stmt);
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_mssql::_query($sql,$inputarr);
+13 -8
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -447,7 +447,7 @@ class ADODB_mysql extends ADOConnection {
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($type,'blob') !== false);
$fld->binary = (strpos($type,'blob') !== false || strpos($type,'binary') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
$fld->zerofill = (strpos($type,'zerofill') !== false);
@@ -499,7 +499,7 @@ class ADODB_mysql extends ADOConnection {
}
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
//global $ADODB_COUNTRECS;
//if($ADODB_COUNTRECS)
@@ -559,8 +559,9 @@ class ADODB_mysql extends ADOConnection {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
if ($associative) {
$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} else $create_sql = $a_create_table[1];
$matches = array();
@@ -576,9 +577,12 @@ class ADODB_mysql extends ADOConnection {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$ref_table])) {
$foreign_keys[$ref_table] = array();
}
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
@@ -733,6 +737,7 @@ class ADORecordSet_mysql extends ADORecordSet{
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
case 'BINARY':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
+65 -12
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -491,8 +491,9 @@ class ADODB_mysqli extends ADOConnection {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) $create_sql = $a_create_table["Create Table"];
else $create_sql = $a_create_table[1];
if ($associative) {
$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} else $create_sql = $a_create_table[1];
$matches = array();
@@ -508,8 +509,11 @@ class ADODB_mysqli extends ADOConnection {
$ref_table = strtoupper($ref_table);
}
$foreign_keys[$ref_table] = array();
$num_fields = count($my_field);
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$ref_table])) {
$foreign_keys[$ref_table] = array();
}
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
@@ -558,8 +562,8 @@ class ADODB_mysqli extends ADOConnection {
$fld->type = $query_array[1];
$arr = explode(",",$query_array[2]);
$fld->enums = $arr;
$fld->max_length = max(array_map("strlen",explode(",",$query_array[2]))) - 2; // PHP >= 4.0.6
$fld->max_length = ($fld->max_length == 0 ? 1 : $fld->max_length);
$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
$fld->max_length = ($zlen > 0) ? $zlen : 1;
} else {
$fld->type = $type;
$fld->max_length = -1;
@@ -632,7 +636,6 @@ class ADODB_mysqli extends ADOConnection {
function Prepare($sql)
{
return $sql;
$stmt = $this->_connectionID->prepare($sql);
if (!$stmt) {
echo $this->ErrorMsg();
@@ -646,8 +649,18 @@ class ADODB_mysqli extends ADOConnection {
function _query($sql, $inputarr)
{
global $ADODB_COUNTRECS;
// Move to the next recordset, or return false if there is none. In a stored proc
// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
// returns false. I think this is because the last "recordset" is actually just the
// return value of the stored proc (ie the number of rows affected).
// Commented out for reasons of performance. You should retrieve every recordset yourself.
// if (!mysqli_next_result($this->connection->_connectionID)) return false;
if (is_array($sql)) {
// Prepare() not supported because mysqli_stmt_execute does not return a recordset, but
// returns as bound variables.
$stmt = $sql[1];
$a = '';
foreach($inputarr as $k => $v) {
@@ -658,16 +671,28 @@ class ADODB_mysqli extends ADOConnection {
$fnarr = array_merge( array($stmt,$a) , $inputarr);
$ret = call_user_func_array('mysqli_stmt_bind_param',$fnarr);
$ret = mysqli_stmt_execute($stmt);
return $ret;
}
/*
if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
return false;
}
return $mysql_res;
*/
if( $rs = mysqli_multi_query($this->_connectionID, $sql.';') )//Contributed by "Geisel Sierote" <geisel#4up.com.br>
{
$rs = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->_connectionID ) : @mysqli_use_result( $this->_connectionID );
return $rs ? $rs : true; // mysqli_more_results( $this->_connectionID )
} else {
if($this->debug)
ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
return false;
}
}
/* Returns: the last error message from previous database operation */
@@ -821,9 +846,10 @@ class ADORecordSet_mysqli extends ADORecordSet{
{
$fieldnr = $fieldOffset;
if ($fieldOffset != -1) {
$fieldOffset = mysqli_field_seek($this->_queryID, $fieldnr);
$fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
}
$o = mysqli_fetch_field($this->_queryID);
$o = @mysqli_fetch_field($this->_queryID);
if (!$o) return false;
/* Properties of an ADOFieldObject as set by MetaColumns */
$o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
$o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
@@ -872,6 +898,33 @@ class ADORecordSet_mysqli extends ADORecordSet{
return true;
}
function NextRecordSet()
{
global $ADODB_COUNTRECS;
mysqli_free_result($this->_queryID);
$this->_queryID = -1;
// Move to the next recordset, or return false if there is none. In a stored proc
// call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
// returns false. I think this is because the last "recordset" is actually just the
// return value of the stored proc (ie the number of rows affected).
if(!mysqli_next_result($this->connection->_connectionID)) {
return false;
}
// CD: There is no $this->_connectionID variable, at least in the ADO version I'm using
$this->_queryID = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->connection->_connectionID )
: @mysqli_use_result( $this->connection->_connectionID );
if(!$this->_queryID) {
return false;
}
$this->_inited = false;
$this->bind = false;
$this->_currentRow = -1;
$this->Init();
return true;
}
// 10% speedup to move MoveNext to child class
// This is the only implementation that works now (23-10-2003).
// Other functions return no or the wrong results.
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+5 -5
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -62,18 +62,18 @@ class ADODB_mysqlt extends ADODB_mysql {
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$ok = $this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
return $ok ? true : false;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$ok = $this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
return $ok ? true : false;
}
function RowLock($tables,$where='',$flds='1 as adodb_ignore')
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
First cut at the Netezza Driver by Josh Eldridge joshuae74#hotmail.com
Based on the previous postgres drivers.
+53 -17
View File
@@ -1,7 +1,7 @@
<?php
/*
version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim. All rights reserved.
version V5.06 16 Oct 2008 (c) 2000-2009 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
@@ -81,7 +81,7 @@ class ADODB_oci8 extends ADOConnection {
var $leftOuter = ''; // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
var $session_sharing_force_blob = false; // alter session on updateblob if set to true
var $firstrows = true; // enable first rows optimization on SelectLimit()
var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.
var $selectOffsetAlg1 = 1000; // when to use 1st algorithm of selectlimit.
var $NLS_DATE_FORMAT = 'YYYY-MM-DD'; // To include time, use 'RRRR-MM-DD HH24:MI:SS'
var $dateformat = 'YYYY-MM-DD'; // DBDate format
var $useDBDateFormatForTextInput=false;
@@ -184,7 +184,7 @@ NATSOFT.DOMAIN =
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
{
if (!function_exists('OCIPLogon')) return null;
#adodb_backtrace();
$this->_errorMsg = false;
$this->_errorCode = false;
@@ -200,6 +200,11 @@ NATSOFT.DOMAIN =
$argHostport = empty($this->port)? "1521" : $this->port;
}
if (strncasecmp($argDatabasename,'SID=',4) == 0) {
$argDatabasename = substr($argDatabasename,4);
$this->connectSID = true;
}
if ($this->connectSID) {
$argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
.")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
@@ -272,10 +277,10 @@ NATSOFT.DOMAIN =
}
// format and return date string in database date format
function DBDate($d)
function DBDate($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return 'TO_DATE('.$d.",'".$this->dateformat."')";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->dateformat."')";
}
@@ -297,9 +302,10 @@ NATSOFT.DOMAIN =
}
// format and return date string in database timestamp format
function DBTimeStamp($ts)
function DBTimeStamp($ts,$isfld=false)
{
if (empty($ts) && $ts !== 0) return 'null';
if ($isfld) return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')";
if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
return 'TO_DATE('.adodb_date("'Y-m-d H:i:s'",$ts).",'RRRR-MM-DD, HH24:MI:SS')";
}
@@ -399,8 +405,10 @@ NATSOFT.DOMAIN =
$this->autoCommit = false;
$this->_commit = OCI_DEFAULT;
if ($this->_transmode) $this->Execute("SET TRANSACTION ".$this->_transmode);
return true;
if ($this->_transmode) $ok = $this->Execute("SET TRANSACTION ".$this->_transmode);
else $ok = true;
return $ok ? true : false;
}
function CommitTrans($ok=true)
@@ -573,7 +581,7 @@ NATSOFT.DOMAIN =
$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
}
if ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000) {
if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) {
if ($nrows > 0) {
if ($offset > 0) $nrows += $offset;
//$inputarr['adodb_rownum'] = $nrows;
@@ -595,14 +603,14 @@ NATSOFT.DOMAIN =
// Let Oracle return the name of the columns
$q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
$false = false;
if (! $stmt_arr = $this->Prepare($q_fields)) {
return $false;
}
$stmt = $stmt_arr[1];
if (is_array($inputarr)) {
if (is_array($inputarr)) {
foreach($inputarr as $k => $v) {
if (is_array($v)) {
if (sizeof($v) == 2) // suggested by g.giunta@libero.
@@ -616,6 +624,7 @@ NATSOFT.DOMAIN =
$bindarr[$k] = $v;
} else { // dynamic sql, so rebind every time
OCIBindByName($stmt,":$k",$inputarr[$k],$len);
}
}
}
@@ -634,16 +643,17 @@ NATSOFT.DOMAIN =
OCIFreeStatement($stmt);
$fields = implode(',', $cols);
$nrows += $offset;
if ($nrows <= 0) $nrows = 999999999999;
else $nrows += $offset;
$offset += 1; // in Oracle rownum starts at 1
if ($this->databaseType == 'oci8po') {
$sql = "SELECT $fields FROM".
$sql = "SELECT /*+ FIRST_ROWS */ $fields FROM".
"(SELECT rownum as adodb_rownum, $fields FROM".
" ($sql) WHERE rownum <= ?".
") WHERE adodb_rownum >= ?";
} else {
$sql = "SELECT $fields FROM".
$sql = "SELECT /*+ FIRST_ROWS */ $fields FROM".
"(SELECT rownum as adodb_rownum, $fields FROM".
" ($sql) WHERE rownum <= :adodb_nrows".
") WHERE adodb_rownum >= :adodb_offset";
@@ -710,7 +720,7 @@ NATSOFT.DOMAIN =
}
/**
* Usage: store file pointed to by $var in a blob
* Usage: store file pointed to by $val in a blob
*/
function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
{
@@ -945,7 +955,7 @@ NATSOFT.DOMAIN =
if ($isOutput == false) {
$var = $this->BlobEncode($var);
$tmp->WriteTemporary($var);
$this->_refLOBs[$numlob]['VAR'] = $var;
$this->_refLOBs[$numlob]['VAR'] = &$var;
if ($this->debug) {
ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
}
@@ -1010,7 +1020,7 @@ NATSOFT.DOMAIN =
$db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
$db->execute($stmt);
*/
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_array($sql)) { // is prepared sql
$stmt = $sql[1];
@@ -1122,6 +1132,32 @@ NATSOFT.DOMAIN =
return false;
}
// From Oracle Whitepaper: PHP Scalability and High Availability
function IsConnectionError($err)
{
switch($err) {
case 378: /* buffer pool param incorrect */
case 602: /* core dump */
case 603: /* fatal error */
case 609: /* attach failed */
case 1012: /* not logged in */
case 1033: /* init or shutdown in progress */
case 1043: /* Oracle not available */
case 1089: /* immediate shutdown in progress */
case 1090: /* shutdown in progress */
case 1092: /* instance terminated */
case 3113: /* disconnect */
case 3114: /* not connected */
case 3122: /* closing window */
case 3135: /* lost contact */
case 12153: /* TNS: not connected */
case 27146: /* fatal or instance terminated */
case 28511: /* Lost RPC */
return true;
}
return false;
}
// returns true or false
function _close()
{
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+4 -3
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -50,7 +50,7 @@ class ADODB_oci8po extends ADODB_oci8 {
}
// emulate handling of parameters ? ?, replacing with :bind0 :bind1
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_array($inputarr)) {
$i = 0;
@@ -102,7 +102,8 @@ class ADORecordset_oci8po extends ADORecordset_oci8 {
{
$fld = new ADOFieldObject;
$fieldOffset += 1;
$fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
$fld->name = OCIcolumnname($this->_queryID, $fieldOffset);
if (ADODB_ASSOC_CASE == 0) $fld->name = strtolower($fld->name);
$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
if ($fld->type == 'NUMBER') {
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+2 -2
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -177,7 +177,7 @@ order by constraint_name, referenced_table_name, keyno";
return $indexes;
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_odbc::_query($sql,$inputarr);
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+95 -2
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -45,16 +45,39 @@ class ADODB_odbtp extends ADOConnection{
function ErrorMsg()
{
if ($this->_errorMsg !== false) return $this->_errorMsg;
if (empty($this->_connectionID)) return @odbtp_last_error();
return @odbtp_last_error($this->_connectionID);
}
function ErrorNo()
{
if ($this->_errorCode !== false) return $this->_errorCode;
if (empty($this->_connectionID)) return @odbtp_last_error_state();
return @odbtp_last_error_state($this->_connectionID);
}
/*
function DBDate($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return "convert(date, $d, 120)";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
$d = adodb_date($this->fmtDate,$d);
return "convert(date, $d, 120)";
}
function DBTimeStamp($d,$isfld=false)
{
if (empty($d) && $d !== 0) return 'null';
if ($isfld) return "convert(datetime, $d, 120)";
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
$d = adodb_date($this->fmtDate,$d);
return "convert(datetime, $d, 120)";
}
*/
function _insertid()
{
// SCOPE_IDENTITY()
@@ -437,6 +460,10 @@ class ADODB_odbtp extends ADOConnection{
function Prepare($sql)
{
if (! $this->_bindInputArray) return $sql; // no binding
$this->_errorMsg = false;
$this->_errorCode = false;
$stmt = @odbtp_prepare($sql,$this->_connectionID);
if (!$stmt) {
// print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
@@ -449,6 +476,9 @@ class ADODB_odbtp extends ADOConnection{
{
if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures
$this->_errorMsg = false;
$this->_errorCode = false;
$stmt = @odbtp_prepare_proc($sql,$this->_connectionID);
if (!$stmt) return false;
return array($sql,$stmt);
@@ -511,6 +541,56 @@ class ADODB_odbtp extends ADOConnection{
return @odbtp_execute( $stmt ) != false;
}
function MetaIndexes($table,$primary=false)
{
switch ( $this->odbc_driver) {
case ODB_DRIVER_MSSQL:
return $this->MetaIndexes_mssql($table, $primary);
default:
return array();
}
}
function MetaIndexes_mssql($table,$primary=false)
{
$table = strtolower($this->qstr($table));
$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND lower(O.Name) = $table
ORDER BY O.name, I.Name, K.keyno";
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$rs = $this->Execute($sql);
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return FALSE;
}
$indexes = array();
while ($row = $rs->FetchRow()) {
if ($primary && !$row[5]) continue;
$indexes[$row[0]]['unique'] = $row[6];
$indexes[$row[0]]['columns'][] = $row[1];
}
return $indexes;
}
function IfNull( $field, $ifNull )
{
switch( $this->odbc_driver ) {
@@ -526,6 +606,9 @@ class ADODB_odbtp extends ADOConnection{
{
global $php_errormsg;
$this->_errorMsg = false;
$this->_errorCode = false;
if ($inputarr) {
if (is_array($sql)) {
$stmtid = $sql[1];
@@ -537,10 +620,20 @@ class ADODB_odbtp extends ADOConnection{
}
}
$num_params = @odbtp_num_params( $stmtid );
/*
for( $param = 1; $param <= $num_params; $param++ ) {
@odbtp_input( $stmtid, $param );
@odbtp_set( $stmtid, $param, $inputarr[$param-1] );
}*/
$param = 1;
foreach($inputarr as $v) {
@odbtp_input( $stmtid, $param );
@odbtp_set( $stmtid, $param, $v );
$param += 1;
if ($param > $num_params) break;
}
if (!@odbtp_execute($stmtid) ) {
return false;
}
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+56 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -158,6 +158,7 @@ class ADODB_pdo extends ADOConnection {
case 'mysql':
case 'pgsql':
case 'mssql':
case 'sqlite':
include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
break;
}
@@ -174,6 +175,15 @@ class ADODB_pdo extends ADOConnection {
return false;
}
function Concat()
{
$args = func_get_args();
if(method_exists($this->_driver, 'Concat'))
return call_user_func_array(array($this->_driver, 'Concat'), $args);
return call_user_func_array(array($this,'parent::Concat'), $args);
}
// returns true or false
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
@@ -216,6 +226,10 @@ class ADODB_pdo extends ADOConnection {
else $obj->bindParam($name, $var);
}
function OffsetDate($dayFraction,$date=false)
{
return $this->_driver->OffsetDate($dayFraction,$date);
}
function ErrorMsg()
{
@@ -248,8 +262,19 @@ class ADODB_pdo extends ADOConnection {
return $err;
}
function SetTransactionMode($transaction_mode)
{
if(method_exists($this->_driver, 'SetTransactionMode'))
return $this->_driver->SetTransactionMode($transaction_mode);
return parent::SetTransactionMode($seqname);
}
function BeginTrans()
{
if(method_exists($this->_driver, 'BeginTrans'))
return $this->_driver->BeginTrans();
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
$this->transCnt += 1;
@@ -260,6 +285,9 @@ class ADODB_pdo extends ADOConnection {
function CommitTrans($ok=true)
{
if(method_exists($this->_driver, 'CommitTrans'))
return $this->_driver->CommitTrans($ok);
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
@@ -273,6 +301,9 @@ class ADODB_pdo extends ADOConnection {
function RollbackTrans()
{
if(method_exists($this->_driver, 'RollbackTrans'))
return $this->_driver->RollbackTrans();
if (!$this->hasTransactions) return false;
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
@@ -299,6 +330,30 @@ class ADODB_pdo extends ADOConnection {
return $obj;
}
function CreateSequence($seqname='adodbseq',$startID=1)
{
if(method_exists($this->_driver, 'CreateSequence'))
return $this->_driver->CreateSequence($seqname, $startID);
return parent::CreateSequence($seqname, $startID);
}
function DropSequence($seqname='adodbseq')
{
if(method_exists($this->_driver, 'DropSequence'))
return $this->_driver->DropSequence($seqname);
return parent::DropSequence($seqname);
}
function GenID($seqname='adodbseq',$startID=1)
{
if(method_exists($this->_driver, 'GenID'))
return $this->_driver->GenID($seqname, $startID);
return parent::GenID($seqname, $startID);
}
/* returns queryID or false */
function _query($sql,$inputarr=false)
+3 -3
View File
@@ -2,7 +2,7 @@
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -47,12 +47,12 @@ class ADODB_pdo_mssql extends ADODB_pdo {
$this->Execute("SET TRANSACTION ".$transaction_mode);
}
function MetaTables()
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
return false;
}
function MetaColumns()
function MetaColumns($table,$normalize=true)
{
return false;
}
+14 -4
View File
@@ -2,7 +2,7 @@
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -18,14 +18,14 @@ class ADODB_pdo_mysql extends ADODB_pdo {
var $hasGenID = true;
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_dropSeqSQL = "drop table %s";
var $fmtTimeStamp = "'Y-m-d, H:i:s'";
var $nameQuote = '`';
function _init($parentDriver)
{
$parentDriver->hasTransactions = false;
$parentDriver->_bindInputArray = false;
#$parentDriver->_bindInputArray = false;
$parentDriver->hasInsertID = true;
$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
}
@@ -41,6 +41,16 @@ class ADODB_pdo_mysql extends ADODB_pdo {
// return "from_unixtime(unix_timestamp($date)+$fraction)";
}
function Concat()
{
$s = "";
$arr = func_get_args();
// suggestion by andrew005#mnogo.ru
$s = implode(',',$arr);
if (strlen($s) > 0) return "CONCAT($s)"; return '';
}
function ServerInfo()
{
$arr['description'] = ADOConnection::GetOne("select version()");
@@ -76,7 +86,7 @@ class ADODB_pdo_mysql extends ADODB_pdo {
$this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
}
function MetaColumns($table)
function MetaColumns($table,$normalize=true)
{
$this->_findschema($table,$schema);
if ($schema) {
+2 -2
View File
@@ -2,7 +2,7 @@
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -47,7 +47,7 @@ class ADODB_pdo_oci extends ADODB_pdo_base {
return $ret;
}
function MetaColumns($table)
function MetaColumns($table,$normalize=true)
{
global $ADODB_FETCH_MODE;
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+190
View File
@@ -0,0 +1,190 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Thanks Diogo Toscano (diogo#scriptcase.net) for the code.
And also Sid Dunayer [sdunayer#interserv.com] for extensive fixes.
*/
class ADODB_pdo_sqlite extends ADODB_pdo {
var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table'";
var $sysDate = 'current_date';
var $sysTimeStamp = 'current_timestamp';
var $nameQuote = '`';
var $replaceQuote = "''";
var $hasGenID = true;
var $_genIDSQL = "UPDATE %s SET id=id+1 WHERE id=%s";
var $_genSeqSQL = "CREATE TABLE %s (id integer)";
var $_genSeqCountSQL = 'SELECT COUNT(*) FROM %s';
var $_genSeq2SQL = 'INSERT INTO %s VALUES(%s)';
var $_dropSeqSQL = 'DROP TABLE %s';
var $concat_operator = '||';
var $pdoDriver = false;
function _init($parentDriver)
{
$this->pdoDriver = $parentDriver;
$parentDriver->_bindInputArray = true;
$parentDriver->hasTransactions = true;
$parentDriver->hasInsertID = true;
}
function ServerInfo()
{
$parent = $this->pdoDriver;
@($ver = array_pop($parent->GetCol("SELECT sqlite_version()")));
@($end = array_pop($parent->GetCol("PRAGMA encoding")));
$arr['version'] = $ver;
$arr['description'] = 'SQLite ';
$arr['encoding'] = $enc;
return $arr;
}
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
{
$parent = $this->pdoDriver;
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
if ($secs2cache)
$rs = $parent->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
else
$rs = $parent->Execute($sql."$limitStr$offsetStr",$inputarr);
return $rs;
}
function GenID($seq='adodbseq',$start=1)
{
$parent = $this->pdoDriver;
// if you have to modify the parameter below, your database is overloaded,
// or you need to implement generation of id's yourself!
$MAXLOOPS = 100;
while (--$MAXLOOPS>=0) {
@($num = array_pop($parent->GetCol("SELECT id FROM {$seq}")));
if ($num === false || !is_numeric($num)) {
@$parent->Execute(sprintf($this->_genSeqSQL ,$seq));
$start -= 1;
$num = '0';
$cnt = $parent->GetOne(sprintf($this->_genSeqCountSQL,$seq));
if (!$cnt) {
$ok = $parent->Execute(sprintf($this->_genSeq2SQL,$seq,$start));
}
if (!$ok) return false;
}
$parent->Execute(sprintf($this->_genIDSQL,$seq,$num));
if ($parent->affected_rows() > 0) {
$num += 1;
$parent->genID = intval($num);
return intval($num);
}
}
if ($fn = $parent->raiseErrorFn) {
$fn($parent->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
}
return false;
}
function CreateSequence($seqname='adodbseq',$start=1)
{
$parent = $this->pdoDriver;
$ok = $parent->Execute(sprintf($this->_genSeqSQL,$seqname));
if (!$ok) return false;
$start -= 1;
return $parent->Execute("insert into $seqname values($start)");
}
function SetTransactionMode($transaction_mode)
{
$parent = $this->pdoDriver;
$parent->_transmode = strtoupper($transaction_mode);
}
function BeginTrans()
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
$parent->transCnt += 1;
$parent->_autocommit = false;
return $parent->Execute("BEGIN {$parent->_transmode}");
}
function CommitTrans($ok=true)
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
if (!$ok) return $parent->RollbackTrans();
if ($parent->transCnt) $parent->transCnt -= 1;
$parent->_autocommit = true;
$ret = $parent->Execute('COMMIT');
return $ret;
}
function RollbackTrans()
{
$parent = $this->pdoDriver;
if ($parent->transOff) return true;
if ($parent->transCnt) $parent->transCnt -= 1;
$parent->_autocommit = true;
$ret = $parent->Execute('ROLLBACK');
return $ret;
}
// mark newnham
function MetaColumns($tab,$normalize=true))
{
global $ADODB_FETCH_MODE;
$parent = $this->pdoDriver;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if ($parent->fetchMode !== false) $savem = $parent->SetFetchMode(false);
$rs = $parent->Execute("PRAGMA table_info('$tab')");
if (isset($savem)) $parent->SetFetchMode($savem);
if (!$rs) {
$ADODB_FETCH_MODE = $save;
return $false;
}
$arr = array();
while ($r = $rs->FetchRow()) {
$type = explode('(',$r['type']);
$size = '';
if (sizeof($type)==2)
$size = trim($type[1],')');
$fn = strtoupper($r['name']);
$fld = new ADOFieldObject;
$fld->name = $r['name'];
$fld->type = $type[0];
$fld->max_length = $size;
$fld->not_null = $r['notnull'];
$fld->primary_key = $r['pk'];
$fld->default_value = $r['dflt_value'];
$fld->scale = 0;
if ($save == ADODB_FETCH_NUM) $arr[] = $fld;
else $arr[strtoupper($fld->name)] = $fld;
}
$rs->Close();
$ADODB_FETCH_MODE = $save;
return $arr;
}
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$parent = $this->pdoDriver;
return $parent->GetCol($this->metaTablesSQL);
}
}
?>
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+5 -2
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -236,6 +236,8 @@ select viewname,'V' from pg_views where viewname like $mask";
// if magic quotes disabled, use pg_escape_string()
function qstr($s,$magic_quotes=false)
{
if (is_bool($s)) return $s ? 'true' : 'false';
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x5200) {
return "'".pg_escape_string($this->_connectionID,$s)."'";
@@ -713,7 +715,7 @@ WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))';
// returns queryID or false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
$this->_errorMsg = false;
if ($inputarr) {
@@ -943,6 +945,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{
function _decode($blob)
{
if ($blob === NULL) return NULL;
eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
return $realblob;
}
+53 -4
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -56,9 +56,58 @@ class ADODB_postgres7 extends ADODB_postgres64 {
}
*/
// from Edward Jaramilla, improved version - works on pg 7.4
/*
I discovered that the MetaForeignKeys method no longer worked for Postgres 8.3.
I went ahead and modified it to work for both 8.2 and 8.3.
Please feel free to include this change in your next release of adodb.
William Kolodny [William.Kolodny#gt-t.net]
*/
function MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql="
SELECT fum.ftblname AS lookup_table, split_part(fum.rf, ')'::text, 1) AS lookup_field,
fum.ltable AS dep_table, split_part(fum.lf, ')'::text, 1) AS dep_field
FROM (
SELECT fee.ltable, fee.ftblname, fee.consrc, split_part(fee.consrc,'('::text, 2) AS lf,
split_part(fee.consrc, '('::text, 3) AS rf
FROM (
SELECT foo.relname AS ltable, foo.ftblname,
pg_get_constraintdef(foo.oid) AS consrc
FROM (
SELECT c.oid, c.conname AS name, t.relname, ft.relname AS ftblname
FROM pg_constraint c
JOIN pg_class t ON (t.oid = c.conrelid)
JOIN pg_class ft ON (ft.oid = c.confrelid)
JOIN pg_namespace nft ON (nft.oid = ft.relnamespace)
LEFT JOIN pg_description ds ON (ds.objoid = c.oid)
JOIN pg_namespace n ON (n.oid = t.relnamespace)
WHERE c.contype = 'f'::\"char\"
ORDER BY t.relname, n.nspname, c.conname, c.oid
) foo
) fee) fum
WHERE fum.ltable='".strtolower($table)."'
ORDER BY fum.ftblname, fum.ltable, split_part(fum.lf, ')'::text, 1)
";
$rs = $this->Execute($sql);
if (!$rs || $rs->EOF) return false;
$a = array();
while (!$rs->EOF) {
if ($upper) {
$a[strtoupper($rs->Fields('lookup_table'))][] = strtoupper(str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field')));
} else {
$a[$rs->Fields('lookup_table')][] = str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field'));
}
$rs->MoveNext();
}
return $a;
}
// from Edward Jaramilla, improved version - works on pg 7.4
function _old_MetaForeignKeys($table, $owner=false, $upper=false)
{
$sql = 'SELECT t.tgargs as args
FROM
@@ -91,7 +140,7 @@ class ADODB_postgres7 extends ADODB_postgres64 {
return $a;
}
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
if (! $this->_bindInputArray) {
// We don't have native support for parameterized queries, so let's emulate it at the parent
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
version V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights
version V5.06 16 Oct 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights
reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+26 -16
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim. All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
@@ -123,6 +123,12 @@ class ADODB_sybase extends ADOConnection {
{
if (!function_exists('sybase_connect')) return null;
if ($this->charSet) {
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword, $this->charSet);
} else {
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
}
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
@@ -133,14 +139,18 @@ class ADODB_sybase extends ADOConnection {
{
if (!function_exists('sybase_connect')) return null;
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
if ($this->charSet) {
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword, $this->charSet);
} else {
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
}
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
function _query($sql,$inputarr=false)
{
global $ADODB_COUNTRECS;
@@ -177,12 +187,12 @@ class ADODB_sybase extends ADOConnection {
return @sybase_close($this->_connectionID);
}
function UnixDate($v)
static function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
@@ -211,7 +221,7 @@ class ADODB_sybase extends ADOConnection {
$s .= "convert(char(3),$col,0)";
break;
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
$s .= "str_replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
@@ -219,21 +229,21 @@ class ADODB_sybase extends ADOConnection {
break;
case 'D':
case 'd':
$s .= "replace(str(datepart(dd,$col),2),' ','0')";
$s .= "str_replace(str(datepart(dd,$col),2),' ','0')";
break;
case 'h':
$s .= "substring(convert(char(14),$col,0),13,2)";
break;
case 'H':
$s .= "replace(str(datepart(hh,$col),2),' ','0')";
$s .= "str_replace(str(datepart(hh,$col),2),' ','0')";
break;
case 'i':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
$s .= "str_replace(str(datepart(mi,$col),2),' ','0')";
break;
case 's':
$s .= "replace(str(datepart(ss,$col),2),' ','0')";
$s .= "str_replace(str(datepart(ss,$col),2),' ','0')";
break;
case 'a':
case 'A':
@@ -353,12 +363,12 @@ class ADORecordset_sybase extends ADORecordSet {
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
static function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
@@ -371,12 +381,12 @@ class ADORecordSet_array_sybase extends ADORecordSet_array {
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
static function UnixDate($v)
{
global $ADODB_sybase_mths;
//Dec 30 2000 12:00AM
if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
if (!preg_match( "/([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})/"
,$v, $rr)) return parent::UnixDate($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
@@ -388,12 +398,12 @@ class ADORecordSet_array_sybase extends ADORecordSet_array {
return mktime(0,0,0,$themth,$rr[2],$rr[3]);
}
function UnixTimeStamp($v)
static function UnixTimeStamp($v)
{
global $ADODB_sybase_mths;
//11.02.2001 Toni Tunkkari [email protected]
//Changed [0-9] to [0-9 ] in day conversion
if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
if (!preg_match( "/([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})/"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
+35
View File
@@ -0,0 +1,35 @@
<?php
/* Farsi - by "Peyman Hooshmandi Raad" <phooshmand#gmail.com> */
$ADODB_LANG_ARRAY = array (
'LANG' => 'fa',
DB_ERROR => 'خطای ناشناخته',
DB_ERROR_ALREADY_EXISTS => 'وجود دارد',
DB_ERROR_CANNOT_CREATE => 'امکان create وجود ندارد',
DB_ERROR_CANNOT_DELETE => 'امکان حذف وجود ندارد',
DB_ERROR_CANNOT_DROP => 'امکان drop وجود ندارد',
DB_ERROR_CONSTRAINT => 'نقض شرط',
DB_ERROR_DIVZERO => 'تقسیم بر صفر',
DB_ERROR_INVALID => 'نامعتبر',
DB_ERROR_INVALID_DATE => 'زمان یا تاریخ نامعتبر',
DB_ERROR_INVALID_NUMBER => 'عدد نامعتبر',
DB_ERROR_MISMATCH => 'عدم مطابقت',
DB_ERROR_NODBSELECTED => 'بانک اطلاعاتی انتخاب نشده است',
DB_ERROR_NOSUCHFIELD => 'چنین ستونی وجود ندارد',
DB_ERROR_NOSUCHTABLE => 'چنین جدولی وجود ندارد',
DB_ERROR_NOT_CAPABLE => 'backend بانک اطلاعاتی قادر نیست',
DB_ERROR_NOT_FOUND => 'پیدا نشد',
DB_ERROR_NOT_LOCKED => 'قفل نشده',
DB_ERROR_SYNTAX => 'خطای دستوری',
DB_ERROR_UNSUPPORTED => 'پشتیبانی نمی شود',
DB_ERROR_VALUE_COUNT_ON_ROW => 'شمارش مقادیر روی ردیف',
DB_ERROR_INVALID_DSN => 'DSN نامعتبر',
DB_ERROR_CONNECT_FAILED => 'ارتباط برقرار نشد',
0 => 'بدون خطا', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'داده ناکافی است',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extension پیدا نشد',
DB_ERROR_NOSUCHDB => 'چنین بانک اطلاعاتی وجود ندارد',
DB_ERROR_ACCESS_VIOLATION => 'حق دسترسی ناکافی'
);
?>
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+164
View File
@@ -0,0 +1,164 @@
<?php
/*
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://adodb.sourceforge.net
Library for basic performance monitoring and tuning
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
/*
MSSQL has moved most performance info to Performance Monitor
*/
class perf_mssqlnative extends adodb_perf{
var $sql1 = 'cast(sql1 as text)';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 varchar(4000) NOT NULL,
params varchar(3000) NOT NULL,
tracer varchar(500) NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'data cache hit ratio' => array('RATIO',
"select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",
'=WarnCacheRatio'),
'prepared sql hit ratio' => array('RATIO',
array('dbcc cachestats','Prepared',1,100),
''),
'adhoc sql hit ratio' => array('RATIO',
array('dbcc cachestats','Adhoc',1,100),
''),
'IO',
'data reads' => array('IO',
"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),
'data writes' => array('IO',
"select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),
'Data Cache',
'data cache size' => array('DATAC',
"select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",
'' ),
'data cache blocksize' => array('DATAC',
"select 8192",'page size'),
'Connections',
'current connections' => array('SESS',
'=sp_who',
''),
'max connections' => array('SESS',
"SELECT @@MAX_CONNECTIONS",
''),
false
);
function perf_mssqlnative(&$conn)
{
if ($conn->dataProvider == 'odbc') {
$this->sql1 = 'sql1';
//$this->explain = false;
}
$this->conn =& $conn;
}
function Explain($sql,$partial=false)
{
$save = $this->conn->LogSQL(false);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
if ($arr) {
foreach($arr as $row) {
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
$this->conn->Execute("SET SHOWPLAN_ALL ON;");
$sql = str_replace('?',"''",$sql);
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$rs =& $this->conn->Execute($sql);
//adodb_printr($rs);
$ADODB_FETCH_MODE = $save;
if ($rs) {
$rs->MoveNext();
$s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>';
while (!$rs->EOF) {
$s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!
$rs->MoveNext();
}
$s .= '</table>';
$rs->NextRecordSet();
}
$this->conn->Execute("SET SHOWPLAN_ALL OFF;");
$this->conn->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
//$this->conn->debug=1;
$s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';
$rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");
if ($rs1) {
while (!$rs1->EOF) {
$tab = $rs1->fields[0];
$tabq = $this->conn->qstr($tab);
$rs2 = $this->conn->Execute("sp_spaceused $tabq");
if ($rs2) {
$s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';
$rs2->Close();
}
$rs1->MoveNext();
}
$rs1->Close();
}
$ADODB_FETCH_MODE = $save;
return $s.'</table>';
}
function sp_who()
{
$arr = $this->conn->GetArray('sp_who');
return sizeof($arr);
}
function HealthCheck($cli=false)
{
$this->conn->Execute('dbcc traceon(3604)');
$html = adodb_perf::HealthCheck($cli);
$this->conn->Execute('dbcc traceoff(3604)');
return $html;
}
}
?>
+267 -266
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -16,270 +16,271 @@ V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights re
if (!defined('ADODB_DIR')) die();
class perf_mysql extends adodb_perf{
var $tablesSQL = 'show table status';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 text NOT NULL,
params text NOT NULL,
tracer text NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'MyISAM cache hit ratio' => array('RATIO',
'=GetKeyHitRatio',
'=WarnCacheRatio'),
'InnoDB cache hit ratio' => array('RATIO',
'=GetInnoDBHitRatio',
'=WarnCacheRatio'),
'data cache hit ratio' => array('HIDE', # only if called
'=FindDBHitRatio',
'=WarnCacheRatio'),
'sql cache hit ratio' => array('RATIO',
'=GetQHitRatio',
''),
'IO',
'data reads' => array('IO',
'=GetReads',
'Number of selects (Key_reads is not accurate)'),
'data writes' => array('IO',
'=GetWrites',
'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
'Data Cache',
'MyISAM data cache size' => array('DATAC',
array("show variables", 'key_buffer_size'),
'' ),
'BDB data cache size' => array('DATAC',
array("show variables", 'bdb_cache_size'),
'' ),
'InnoDB data cache size' => array('DATAC',
array("show variables", 'innodb_buffer_pool_size'),
'' ),
'Memory Usage',
'read buffer size' => array('CACHE',
array("show variables", 'read_buffer_size'),
'(per session)'),
'sort buffer size' => array('CACHE',
array("show variables", 'sort_buffer_size'),
'Size of sort buffer (per session)' ),
'table cache' => array('CACHE',
array("show variables", 'table_cache'),
'Number of tables to keep open'),
'Connections',
'current connections' => array('SESS',
array('show status','Threads_connected'),
''),
'max connections' => array( 'SESS',
array("show variables",'max_connections'),
''),
false
);
function perf_mysql(&$conn)
{
$this->conn = $conn;
}
function Explain($sql,$partial=false)
{
if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';
$save = $this->conn->LogSQL(false);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
if ($arr) {
foreach($arr as $row) {
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$sql = str_replace('?',"''",$sql);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");
}
$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
$rs = $this->conn->Execute('EXPLAIN '.$sql);
$s .= rs2html($rs,false,false,false,false);
$this->conn->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
if (!$this->tablesSQL) return false;
$rs = $this->conn->Execute($this->tablesSQL);
if (!$rs) return false;
$html = rs2html($rs,false,false,false,false);
return $html;
}
function GetReads()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$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;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$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;
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show table status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return '';
$type = strtoupper($rs->fields[1]);
$rs->Close();
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 round(($hits*100)/$total,2);
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 $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show innodb status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs || $rs->EOF) return 0;
$stat = $rs->fields[0];
$rs->Close();
$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];
$_SESSION['INNODB_HIT_PCT'] = $val;
return round($val,2);
} else {
if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT'];
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 round(($hits/($reqs+$hits))*100,2);
}
var $tablesSQL = 'show table status';
var $createTableSQL = "CREATE TABLE adodb_logsql (
created datetime NOT NULL,
sql0 varchar(250) NOT NULL,
sql1 text NOT NULL,
params text NOT NULL,
tracer text NOT NULL,
timer decimal(16,6) NOT NULL
)";
var $settings = array(
'Ratios',
'MyISAM cache hit ratio' => array('RATIO',
'=GetKeyHitRatio',
'=WarnCacheRatio'),
'InnoDB cache hit ratio' => array('RATIO',
'=GetInnoDBHitRatio',
'=WarnCacheRatio'),
'data cache hit ratio' => array('HIDE', # only if called
'=FindDBHitRatio',
'=WarnCacheRatio'),
'sql cache hit ratio' => array('RATIO',
'=GetQHitRatio',
''),
'IO',
'data reads' => array('IO',
'=GetReads',
'Number of selects (Key_reads is not accurate)'),
'data writes' => array('IO',
'=GetWrites',
'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
'Data Cache',
'MyISAM data cache size' => array('DATAC',
array("show variables", 'key_buffer_size'),
'' ),
'BDB data cache size' => array('DATAC',
array("show variables", 'bdb_cache_size'),
'' ),
'InnoDB data cache size' => array('DATAC',
array("show variables", 'innodb_buffer_pool_size'),
'' ),
'Memory Usage',
'read buffer size' => array('CACHE',
array("show variables", 'read_buffer_size'),
'(per session)'),
'sort buffer size' => array('CACHE',
array("show variables", 'sort_buffer_size'),
'Size of sort buffer (per session)' ),
'table cache' => array('CACHE',
array("show variables", 'table_cache'),
'Number of tables to keep open'),
'Connections',
'current connections' => array('SESS',
array('show status','Threads_connected'),
''),
'max connections' => array( 'SESS',
array("show variables",'max_connections'),
''),
false
);
function perf_mysql(&$conn)
{
$this->conn = $conn;
}
function Explain($sql,$partial=false)
{
if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';
$save = $this->conn->LogSQL(false);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
if ($arr) {
foreach($arr as $row) {
$sql = reset($row);
if (crc32($sql) == $partial) break;
}
}
}
$sql = str_replace('?',"''",$sql);
if ($partial) {
$sqlq = $this->conn->qstr($sql.'%');
$sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");
}
$s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
$rs = $this->conn->Execute('EXPLAIN '.$sql);
$s .= rs2html($rs,false,false,false,false);
$this->conn->LogSQL($save);
$s .= $this->Tracer($sql);
return $s;
}
function Tables()
{
if (!$this->tablesSQL) return false;
$rs = $this->conn->Execute($this->tablesSQL);
if (!$rs) return false;
$html = rs2html($rs,false,false,false,false);
return $html;
}
function GetReads()
{
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$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;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return 0;
$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;
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show table status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs) return '';
$type = strtoupper($rs->fields[1]);
$rs->Close();
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 round(($hits*100)/$total,2);
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 $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
$rs = $this->conn->Execute('show innodb status');
if (isset($savem)) $this->conn->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!$rs || $rs->EOF) return 0;
$stat = $rs->fields[0];
$rs->Close();
$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];
$_SESSION['INNODB_HIT_PCT'] = $val;
return round($val,2);
} else {
if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['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 round(($hits/($reqs+$hits))*100,2);
}
// start hack
var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK';
var $optimizeTableHigh = 'OPTIMIZE TABLE %s';
@@ -311,4 +312,4 @@ class perf_mysql extends adodb_perf{
}
// end hack
}
?>
?>
+23 -3
View File
@@ -1,6 +1,6 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
@@ -16,11 +16,14 @@ V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights re
if (!defined('ADODB_DIR')) die();
class perf_oci8 extends ADODB_perf{
var $noShowIxora = 15; // if the sql for suspicious sql is taking too long, then disable ixora
var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents
group by segment_name,tablespace_name";
var $version;
var $createTableSQL = "CREATE TABLE adodb_logsql (
created date NOT NULL,
sql0 varchar(250) NOT NULL,
@@ -68,6 +71,7 @@ AND b.name = 'sorts (memory)'",
"select value from v\$sysstat where name='physical writes'"),
'Data Cache',
'data cache buffers' => array( 'DATAC',
"select a.value/b.value from v\$parameter a, v\$parameter b
where a.name = 'db_cache_size' and b.name= 'db_block_size'",
@@ -75,8 +79,15 @@ AND b.name = 'sorts (memory)'",
'data cache blocksize' => array('DATAC',
"select value from v\$parameter where name='db_block_size'",
'' ),
'Memory Pools',
'data cache size' => array('DATAC',
'SGA Max Size' => array( 'DATAC',
"select value from v\$parameter where name = 'sga_max_size'",
'The sga_max_size is the maximum value to which sga_target can be set.' ),
'SGA target' => array( 'DATAC',
"select value from v\$parameter where name = 'sga_target'",
'If sga_target is defined then data cache, shared, java and large pool size can be 0. This is because all these pools are consolidated into one sga_target.' ),
'data cache size' => array('DATAC',
"select value from v\$parameter where name = 'db_cache_size'",
'db_cache_size' ),
'shared pool size' => array('DATAC',
@@ -430,7 +441,11 @@ order by
if (isset($_GET['sql'])) return $this->_SuspiciousSQL($numsql);
$s = '';
$timer = time();
$s .= $this->_SuspiciousSQL($numsql);
$timer = time() - $timer;
if ($timer > $this->noShowIxora) return $s;
$s .= '<p>';
$save = $ADODB_CACHE_MODE;
@@ -502,7 +517,11 @@ order by
}
$s = '';
$timer = time();
$s .= $this->_ExpensiveSQL($numsql);
$timer = time() - $timer;
if ($timer > $this->noShowIxora) return $s;
$s .= '<p>';
$save = $ADODB_CACHE_MODE;
$ADODB_CACHE_MODE = ADODB_FETCH_NUM;
@@ -536,11 +555,12 @@ BEGIN
LOOP
cnt := cnt + 1;
DELETE FROM $perf_table WHERE ROWID=rec.rr;
IF cnt = 10000 THEN
IF cnt = 1000 THEN
COMMIT;
cnt := 0;
END IF;
END LOOP;
commit;
END;";
$ok = $this->conn->Execute($sql);
+1 -1
View File
@@ -1,7 +1,7 @@
<?php
/*
V5.04a 25 Mar 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V4.93 10 Oct 2006 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V4.93 10 Oct 2006 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+3 -11
View File
@@ -1,4 +1,4 @@
Description of ADODB V5.04a library import into Moodle
Description of ADODB V5.08 library import into Moodle
Removed:
* contrib/
@@ -13,20 +13,12 @@ Added:
* index.html - prevent directory browsing on misconfigured servers
* readme_moodle.txt - this file ;-)
Our changes:
Our changes: /// Look for "moodle" in adodb code
* adodb-lib.inc.php - added support for "F" and "L" types in _adodb_column_sql()
* adodb-lib.inc.php - modify some debug output to be correct XHTML. MDL-12378.
Reported to ADOdb at: http://phplens.com/lens/lensforum/msgs.php?id=17133
Once fixed by adodb guys, we'll return to their official distro.
* drivers/adodb-mysqli.inc.php - fixed problem with driver not detecting enums
in the MetaColumns() function. MDL-14215.
Reported to ADOdb at: http://phplens.com/lens/lensforum/msgs.php?id=17383
Once fixed by adodb guys, we'll return to their official distro.
* drivers/adodb-mssql.ic.php - fixed problem with insert statements using placeholders
not able to return the Insert_ID() at all. MDL-14886.
Reported to ADOdb at: http://phplens.com/lens/lensforum/msgs.php?id=17068
Once fixed by adodb guys, we'll return to their official distro.
skodak, iarenaza, moodler, stronk7
$Id$
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
/**
* @version V4.93 10 Oct 2006 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V4.93 10 Oct 2006 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
+4 -3
View File
@@ -1,7 +1,7 @@
<?php
/**
* @version V4.93 10 Oct 2006 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
* @version V4.93 10 Oct 2006 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
@@ -73,9 +73,10 @@ function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote =
if ($addtitles) {
$fieldTypes = $rs->FieldTypesArray();
reset($fieldTypes);
$i = 0;
while(list(,$o) = each($fieldTypes)) {
if (!$o) $v = '';
else $v = $o->name;
$v = ($o) ? $o->name : 'Field'.($i++);
if ($escquote) $v = str_replace($quote,$escquotequote,$v);
$v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
$elements[] = $v;
+14 -8
View File
@@ -1,13 +1,13 @@
<?php
/*
V4.93 10 Oct 2006 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
V4.93 10 Oct 2006 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Some pretty-printing by Chris Oxenreider <[email protected]>
*/
// specific code for tohtml
GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
@@ -84,14 +84,18 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
$type = $typearr[$i];
switch($type) {
case 'D':
if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
else if (!strpos($v,':')) {
$s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";
if (strpos($v,':') !== false);
else {
if (empty($v)) {
$s .= "<TD> &nbsp; </TD>\n";
} else {
$s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."</TD>\n";
}
break;
}
break;
case 'T':
if (empty($v)) $s .= "<TD> &nbsp; </TD>\n";
else $s .= " <TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";
else $s .= " <TD>".$rs->UserTimeStamp($v,"D d, M Y, H:i:s") ."</TD>\n";
break;
case 'N':
@@ -100,7 +104,9 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND;
else
$v = round($v,$ADODB_ROUND);
case 'I':
$s .= " <TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";
$vv = stripslashes((trim($v)));
if (strlen($vv) == 0) $vv .= '&nbsp;';
$s .= " <TD align=right>".$vv ."</TD>\n";
break;
/*