3 V4.98 13 Feb 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
4 Released under both BSD license and Lesser GPL library license.
5 Whenever there is any discrepancy between the two licenses,
6 the BSD license will take precedence. See License.txt.
7 Set tabs to 4 for best viewing.
8 Latest version is available at http://adodb.sourceforge.net
10 // Code contributed by "stefan bogdan" <sbogdan#rsb.ro>
12 // security - hide paths
13 if (!defined('ADODB_DIR')) die();
15 define("_ADODB_ODBTP_LAYER", 2 );
17 class ADODB_odbtp
extends ADOConnection
{
18 var $databaseType = "odbtp";
19 var $dataProvider = "odbtp";
20 var $fmtDate = "'Y-m-d'";
21 var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
22 var $replaceQuote = "''"; // string to use to replace quotes
24 var $hasAffectedRows = true;
25 var $hasInsertID = false;
27 var $hasMoveFirst = true;
29 var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)";
30 var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'";
31 var $_bindInputArray = false;
32 var $_useUnicodeSQL = false;
33 var $_canPrepareSP = false;
34 var $_dontPoolDBC = true;
36 function ADODB_odbtp()
42 return array('description' => @odbtp_get_attr
( ODB_ATTR_DBMSNAME
, $this->_connectionID
),
43 'version' => @odbtp_get_attr
( ODB_ATTR_DBMSVER
, $this->_connectionID
));
48 if (empty($this->_connectionID
)) return @odbtp_last_error
();
49 return @odbtp_last_error
($this->_connectionID
);
54 if (empty($this->_connectionID
)) return @odbtp_last_error_state
();
55 return @odbtp_last_error_state
($this->_connectionID
);
61 // Returns the last IDENTITY value inserted into an IDENTITY column in
62 // the same scope. A scope is a module -- a stored procedure, trigger,
63 // function, or batch. Thus, two statements are in the same scope if
64 // they are in the same stored procedure, function, or batch.
65 return $this->GetOne($this->identitySQL
);
68 function _affectedrows()
70 if ($this->_queryID
) {
71 return @odbtp_affected_rows
($this->_queryID
);
76 function CreateSequence($seqname='adodbseq',$start=1)
79 $num = $this->GetOne("select seq_value from adodb_seq");
81 if( $this->odbc_driver
== ODB_DRIVER_FOXPRO
) {
82 $path = @odbtp_get_attr
( ODB_ATTR_DATABASENAME
, $this->_connectionID
);
83 //if using vfp dbc file
84 if( !strcasecmp(strrchr($path, '.'), '.dbc') )
85 $path = substr($path,0,strrpos($path,'\/'));
86 $seqtab = $path . '/' . $seqtab;
89 if (empty($this->_genSeqSQL
)) return false;
90 $ok = $this->Execute(sprintf($this->_genSeqSQL
,$seqtab));
92 $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'");
97 return $this->Execute("insert into adodb_seq values('$seqname',$start)");
100 function DropSequence($seqname)
102 if (empty($this->_dropSeqSQL
)) return false;
103 return $this->Execute(sprintf($this->_dropSeqSQL
,$seqname));
106 function GenID($seq='adodbseq',$start=1)
109 if( $this->odbc_driver
== ODB_DRIVER_FOXPRO
) {
110 $path = @odbtp_get_attr
( ODB_ATTR_DATABASENAME
, $this->_connectionID
);
111 //if using vfp dbc file
112 if( !strcasecmp(strrchr($path, '.'), '.dbc') )
113 $path = substr($path,0,strrpos($path,'\/'));
114 $seqtab = $path . '/' . $seqtab;
117 while (--$MAXLOOPS>=0) {
118 $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'");
119 if ($num === false) {
120 //verify if abodb_seq table exist
121 $ok = $this->GetOne("select seq_value from adodb_seq ");
123 //creating the sequence table adodb_seq
124 $this->Execute(sprintf($this->_genSeqSQL
,$seqtab));
128 $ok = $this->Execute("insert into adodb_seq values('$seq',$start)");
129 if (!$ok) return false;
131 $ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'");
138 if ($fn = $this->raiseErrorFn
) {
139 $fn($this->databaseType
,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
144 //example for $UserOrDSN
145 //for visual fox : DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=c:\YourDbfFileDir;EXCLUSIVE=NO;
146 //for visual fox dbc: DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBC;SOURCEDB=c:\YourDbcFileDir\mydb.dbc;EXCLUSIVE=NO;
147 //for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=;
148 //for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest;
149 //if uid & pwd can be separate
150 function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
152 $this->_connectionID
= odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
153 if ($this->_connectionID
=== false) {
154 $this->_errorMsg
= $this->ErrorMsg() ;
158 odbtp_convert_datetime($this->_connectionID
,true);
160 if ($this->_dontPoolDBC
) {
161 if (function_exists('odbtp_dont_pool_dbc'))
162 @odbtp_dont_pool_dbc
($this->_connectionID
);
165 $this->_dontPoolDBC
= true;
167 $this->odbc_driver
= @odbtp_get_attr
(ODB_ATTR_DRIVER
, $this->_connectionID
);
168 $dbms = strtolower(@odbtp_get_attr
(ODB_ATTR_DBMSNAME
, $this->_connectionID
));
169 $this->odbc_name
= $dbms;
171 // Account for inconsistent DBMS names
172 if( $this->odbc_driver
== ODB_DRIVER_ORACLE
)
174 else if( $this->odbc_driver
== ODB_DRIVER_SYBASE
)
177 // Set DBMS specific attributes
179 case 'microsoft sql server':
180 $this->databaseType
= 'odbtp_mssql';
181 $this->fmtDate
= "'Y-m-d'";
182 $this->fmtTimeStamp
= "'Y-m-d h:i:sA'";
183 $this->sysDate
= 'convert(datetime,convert(char,GetDate(),102),102)';
184 $this->sysTimeStamp
= 'GetDate()';
185 $this->ansiOuter
= true;
186 $this->leftOuter
= '*=';
187 $this->rightOuter
= '=*';
188 $this->hasTop
= 'top';
189 $this->hasInsertID
= true;
190 $this->hasTransactions
= true;
191 $this->_bindInputArray
= true;
192 $this->_canSelectDb
= true;
193 $this->substr
= "substring";
194 $this->length
= 'len';
195 $this->identitySQL
= 'select SCOPE_IDENTITY()';
196 $this->metaDatabasesSQL
= "select name from master..sysdatabases where name <> 'master'";
197 $this->_canPrepareSP
= true;
200 $this->databaseType
= 'odbtp_access';
201 $this->fmtDate
= "#Y-m-d#";
202 $this->fmtTimeStamp
= "#Y-m-d h:i:sA#";
203 $this->sysDate
= "FORMAT(NOW,'yyyy-mm-dd')";
204 $this->sysTimeStamp
= 'NOW';
205 $this->hasTop
= 'top';
206 $this->hasTransactions
= false;
207 $this->_canPrepareSP
= true; // For MS Access only.
209 case 'visual foxpro':
210 $this->databaseType
= 'odbtp_vfp';
211 $this->fmtDate
= "{^Y-m-d}";
212 $this->fmtTimeStamp
= "{^Y-m-d, h:i:sA}";
213 $this->sysDate
= 'date()';
214 $this->sysTimeStamp
= 'datetime()';
215 $this->ansiOuter
= true;
216 $this->hasTop
= 'top';
217 $this->hasTransactions
= false;
218 $this->replaceQuote
= "'+chr(39)+'";
220 $this->false = '.F.';
224 $this->databaseType
= 'odbtp_oci8';
225 $this->fmtDate
= "'Y-m-d 00:00:00'";
226 $this->fmtTimeStamp
= "'Y-m-d h:i:sA'";
227 $this->sysDate
= 'TRUNC(SYSDATE)';
228 $this->sysTimeStamp
= 'SYSDATE';
229 $this->hasTransactions
= true;
230 $this->_bindInputArray
= true;
231 $this->concat_operator
= '||';
234 $this->databaseType
= 'odbtp_sybase';
235 $this->fmtDate
= "'Y-m-d'";
236 $this->fmtTimeStamp
= "'Y-m-d H:i:s'";
237 $this->sysDate
= 'GetDate()';
238 $this->sysTimeStamp
= 'GetDate()';
239 $this->leftOuter
= '*=';
240 $this->rightOuter
= '=*';
241 $this->hasInsertID
= true;
242 $this->hasTransactions
= true;
243 $this->identitySQL
= 'select SCOPE_IDENTITY()';
246 $this->databaseType
= 'odbtp';
247 if( @odbtp_get_attr
(ODB_ATTR_TXNCAPABLE
, $this->_connectionID
) )
248 $this->hasTransactions
= true;
250 $this->hasTransactions
= false;
252 @odbtp_set_attr
(ODB_ATTR_FULLCOLINFO
, TRUE, $this->_connectionID
);
254 if ($this->_useUnicodeSQL
)
255 @odbtp_set_attr
(ODB_ATTR_UNICODESQL
, TRUE, $this->_connectionID
);
260 function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
262 $this->_dontPoolDBC
= false;
263 return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase);
266 function SelectDB($dbName)
268 if (!@odbtp_select_db
($dbName, $this->_connectionID
)) {
271 $this->database
= $dbName;
272 $this->databaseName
= $dbName; # obsolete, retained for compat with older adodb versions
276 function &MetaTables($ttype='',$showSchema=false,$mask=false)
278 global $ADODB_FETCH_MODE;
280 $savem = $ADODB_FETCH_MODE;
281 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
282 if ($this->fetchMode
!== false) $savefm = $this->SetFetchMode(false);
284 $arr =& $this->GetArray("||SQLTables||||$ttype");
286 if (isset($savefm)) $this->SetFetchMode($savefm);
287 $ADODB_FETCH_MODE = $savem;
290 for ($i=0; $i < sizeof($arr); $i++
) {
291 if ($arr[$i][3] == 'SYSTEM TABLE' ) continue;
293 $arr2[] = $showSchema && $arr[$i][1]?
$arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];
298 function &MetaColumns($table,$upper=true)
300 global $ADODB_FETCH_MODE;
303 $this->_findschema($table,$schema);
304 if ($upper) $table = strtoupper($table);
306 $savem = $ADODB_FETCH_MODE;
307 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
308 if ($this->fetchMode
!== false) $savefm = $this->SetFetchMode(false);
310 $rs = $this->Execute( "||SQLColumns||$schema|$table" );
312 if (isset($savefm)) $this->SetFetchMode($savefm);
313 $ADODB_FETCH_MODE = $savem;
315 if (!$rs ||
$rs->EOF
) {
321 //print_r($rs->fields);
322 if (strtoupper($rs->fields
[2]) == $table) {
323 $fld = new ADOFieldObject();
324 $fld->name
= $rs->fields
[3];
325 $fld->type
= $rs->fields
[5];
326 $fld->max_length
= $rs->fields
[6];
327 $fld->not_null
= !empty($rs->fields
[9]);
328 $fld->scale
= $rs->fields
[7];
329 if (isset($rs->fields
[12])) // vfp does not have field 12
330 if (!is_null($rs->fields
[12])) {
331 $fld->has_default
= true;
332 $fld->default_value
= $rs->fields
[12];
334 $retarr[strtoupper($fld->name
)] = $fld;
335 } else if (!empty($retarr))
344 function &MetaPrimaryKeys($table, $owner='')
346 global $ADODB_FETCH_MODE;
348 $savem = $ADODB_FETCH_MODE;
349 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
350 $arr =& $this->GetArray("||SQLPrimaryKeys||$owner|$table");
351 $ADODB_FETCH_MODE = $savem;
355 for ($i=0; $i < sizeof($arr); $i++
) {
356 if ($arr[$i][3]) $arr2[] = $arr[$i][3];
361 function &MetaForeignKeys($table, $owner='', $upper=false)
363 global $ADODB_FETCH_MODE;
365 $savem = $ADODB_FETCH_MODE;
366 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
367 $constraints =& $this->GetArray("||SQLForeignKeys|||||$owner|$table");
368 $ADODB_FETCH_MODE = $savem;
371 foreach($constraints as $constr) {
373 $arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3];
382 foreach($arr as $k => $v) {
383 foreach($v as $a => $b) {
384 if ($upper) $a = strtoupper($a);
391 function BeginTrans()
393 if (!$this->hasTransactions
) return false;
394 if ($this->transOff
) return true;
395 $this->transCnt +
= 1;
396 $this->autoCommit
= false;
397 if (defined('ODB_TXN_DEFAULT'))
398 $txn = ODB_TXN_DEFAULT
;
400 $txn = ODB_TXN_READUNCOMMITTED
;
401 $rs = @odbtp_set_attr
(ODB_ATTR_TRANSACTIONS
,$txn,$this->_connectionID
);
402 if(!$rs) return false;
406 function CommitTrans($ok=true)
408 if ($this->transOff
) return true;
409 if (!$ok) return $this->RollbackTrans();
410 if ($this->transCnt
) $this->transCnt
-= 1;
411 $this->autoCommit
= true;
412 if( ($ret = @odbtp_commit
($this->_connectionID
)) )
413 $ret = @odbtp_set_attr
(ODB_ATTR_TRANSACTIONS
, ODB_TXN_NONE
, $this->_connectionID
);//set transaction off
417 function RollbackTrans()
419 if ($this->transOff
) return true;
420 if ($this->transCnt
) $this->transCnt
-= 1;
421 $this->autoCommit
= true;
422 if( ($ret = @odbtp_rollback
($this->_connectionID
)) )
423 $ret = @odbtp_set_attr
(ODB_ATTR_TRANSACTIONS
, ODB_TXN_NONE
, $this->_connectionID
);//set transaction off
427 function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
429 // TOP requires ORDER BY for Visual FoxPro
430 if( $this->odbc_driver
== ODB_DRIVER_FOXPRO
) {
431 if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
433 $ret =& ADOConnection
::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
437 function Prepare($sql)
439 if (! $this->_bindInputArray
) return $sql; // no binding
440 $stmt = @odbtp_prepare
($sql,$this->_connectionID
);
442 // print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
445 return array($sql,$stmt,false);
448 function PrepareSP($sql)
450 if (!$this->_canPrepareSP
) return $sql; // Can't prepare procedures
452 $stmt = @odbtp_prepare_proc
($sql,$this->_connectionID
);
453 if (!$stmt) return false;
454 return array($sql,$stmt);
459 $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
461 # note that the parameter does not have @ in front!
462 $db->Parameter($stmt,$id,'myid');
463 $db->Parameter($stmt,$group,'group',false,64);
464 $db->Parameter($stmt,$group,'photo',false,100000,ODB_BINARY);
467 @param $stmt Statement returned by Prepare() or PrepareSP().
468 @param $var PHP variable to bind to. Can set to null (for isNull support).
469 @param $name Name of stored procedure variable name to bind to.
470 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in odbtp.
471 @param [$maxLen] Holds an maximum length of the variable.
472 @param [$type] The data type of $var. Legal values depend on driver.
474 See odbtp_attach_param documentation at http://odbtp.sourceforge.net.
476 function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0)
478 if ( $this->odbc_driver
== ODB_DRIVER_JET
) {
479 $name = '['.$name.']';
480 if( !$type && $this->_useUnicodeSQL
481 && @odbtp_param_bindtype
($stmt[1], $name) == ODB_CHAR
)
489 return @odbtp_attach_param
($stmt[1], $name, $var, $type, $maxLen);
493 Insert a null into the blob field of the table first.
494 Then use UpdateBlob to store the blob.
498 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
499 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
502 function UpdateBlob($table,$column,$val,$where,$blobtype='image')
504 $sql = "UPDATE $table SET $column = ? WHERE $where";
505 if( !($stmt = @odbtp_prepare
($sql, $this->_connectionID
)) )
507 if( !@odbtp_input
( $stmt, 1, ODB_BINARY
, 1000000, $blobtype ) )
509 if( !@odbtp_set
( $stmt, 1, $val ) )
511 return @odbtp_execute
( $stmt ) != false;
514 function IfNull( $field, $ifNull )
516 switch( $this->odbc_driver
) {
517 case ODB_DRIVER_MSSQL
:
518 return " ISNULL($field, $ifNull) ";
520 return " IIF(IsNull($field), $ifNull, $field) ";
522 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
525 function _query($sql,$inputarr=false)
527 global $php_errormsg;
530 if (is_array($sql)) {
533 $stmtid = @odbtp_prepare
($sql,$this->_connectionID
);
534 if ($stmtid == false) {
535 $this->_errorMsg
= $php_errormsg;
539 $num_params = @odbtp_num_params
( $stmtid );
540 for( $param = 1; $param <= $num_params; $param++
) {
541 @odbtp_input
( $stmtid, $param );
542 @odbtp_set
( $stmtid, $param, $inputarr[$param-1] );
544 if (!@odbtp_execute
($stmtid) ) {
547 } else if (is_array($sql)) {
549 if (!@odbtp_execute
($stmtid)) {
553 $stmtid = odbtp_query($sql,$this->_connectionID
);
555 $this->_lastAffectedRows
= 0;
557 $this->_lastAffectedRows
= @odbtp_affected_rows
($stmtid);
564 $ret = @odbtp_close
($this->_connectionID
);
565 $this->_connectionID
= false;
570 class ADORecordSet_odbtp
extends ADORecordSet
{
572 var $databaseType = 'odbtp';
575 function ADORecordSet_odbtp($queryID,$mode=false)
577 if ($mode === false) {
578 global $ADODB_FETCH_MODE;
579 $mode = $ADODB_FETCH_MODE;
581 $this->fetchMode
= $mode;
582 $this->ADORecordSet($queryID);
587 $this->_numOfFields
= @odbtp_num_fields
($this->_queryID
);
588 if (!($this->_numOfRows
= @odbtp_num_rows
($this->_queryID
)))
589 $this->_numOfRows
= -1;
591 if (!$this->connection
->_useUnicodeSQL
) return;
593 if ($this->connection
->odbc_driver
== ODB_DRIVER_JET
) {
594 if (!@odbtp_get_attr
(ODB_ATTR_MAPCHARTOWCHAR
,
595 $this->connection
->_connectionID
))
597 for ($f = 0; $f < $this->_numOfFields
; $f++
) {
598 if (@odbtp_field_bindtype
($this->_queryID
, $f) == ODB_CHAR
)
599 @odbtp_bind_field
($this->_queryID
, $f, ODB_WCHAR
);
605 function &FetchField($fieldOffset = 0)
607 $off=$fieldOffset; // offsets begin at 0
608 $o= new ADOFieldObject();
609 $o->name
= @odbtp_field_name
($this->_queryID
,$off);
610 $o->type
= @odbtp_field_type
($this->_queryID
,$off);
611 $o->max_length
= @odbtp_field_length
($this->_queryID
,$off);
612 if (ADODB_ASSOC_CASE
== 0) $o->name
= strtolower($o->name
);
613 else if (ADODB_ASSOC_CASE
== 1) $o->name
= strtoupper($o->name
);
619 return @odbtp_data_seek
($this->_queryID
, $row);
622 function fields($colname)
624 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) return $this->fields
[$colname];
627 $this->bind
= array();
628 for ($i=0; $i < $this->_numOfFields
; $i++
) {
629 $name = @odbtp_field_name
( $this->_queryID
, $i );
630 $this->bind
[strtoupper($name)] = $i;
633 return $this->fields
[$this->bind
[strtoupper($colname)]];
636 function _fetch_odbtp($type=0)
638 switch ($this->fetchMode
) {
639 case ADODB_FETCH_NUM
:
640 $this->fields
= @odbtp_fetch_row
($this->_queryID
, $type);
642 case ADODB_FETCH_ASSOC
:
643 $this->fields
= @odbtp_fetch_assoc
($this->_queryID
, $type);
646 $this->fields
= @odbtp_fetch_array
($this->_queryID
, $type);
648 if ($this->databaseType
= 'odbtp_vfp') {
650 foreach($this->fields
as $k => $v) {
651 if (strncmp($v,'1899-12-30',10) == 0) $this->fields
[$k] = '';
654 return is_array($this->fields
);
659 return $this->_fetch_odbtp();
664 if (!$this->_fetch_odbtp(ODB_FETCH_FIRST
)) return false;
666 $this->_currentRow
= 0;
672 if (!$this->_fetch_odbtp(ODB_FETCH_LAST
)) return false;
674 $this->_currentRow
= $this->_numOfRows
- 1;
678 function NextRecordSet()
680 if (!@odbtp_next_result
($this->_queryID
)) return false;
681 $this->_inited
= false;
683 $this->_currentRow
= -1;
690 return @odbtp_free_query
($this->_queryID
);
694 class ADORecordSet_odbtp_mssql
extends ADORecordSet_odbtp
{
696 var $databaseType = 'odbtp_mssql';
698 function ADORecordSet_odbtp_mssql($id,$mode=false)
700 return $this->ADORecordSet_odbtp($id,$mode);
704 class ADORecordSet_odbtp_access
extends ADORecordSet_odbtp
{
706 var $databaseType = 'odbtp_access';
708 function ADORecordSet_odbtp_access($id,$mode=false)
710 return $this->ADORecordSet_odbtp($id,$mode);
714 class ADORecordSet_odbtp_vfp
extends ADORecordSet_odbtp
{
716 var $databaseType = 'odbtp_vfp';
718 function ADORecordSet_odbtp_vfp($id,$mode=false)
720 return $this->ADORecordSet_odbtp($id,$mode);
724 class ADORecordSet_odbtp_oci8
extends ADORecordSet_odbtp
{
726 var $databaseType = 'odbtp_oci8';
728 function ADORecordSet_odbtp_oci8($id,$mode=false)
730 return $this->ADORecordSet_odbtp($id,$mode);
734 class ADORecordSet_odbtp_sybase
extends ADORecordSet_odbtp
{
736 var $databaseType = 'odbtp_sybase';
738 function ADORecordSet_odbtp_sybase($id,$mode=false)
740 return $this->ADORecordSet_odbtp($id,$mode);