3 V4.22 15 Apr 2004 (c) 2000-2004 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.
8 Latest version is available at http://php.weblogs.com/
10 Interbase data driver. Requires interbase client. Works on Windows and Unix.
12 3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>
13 changed transaction handling and added experimental blob stuff
15 Docs to interbase at the website
16 http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html
19 http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen
21 $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');
23 $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");
26 class ADODB_ibase extends ADOConnection {
27 var $databaseType = "ibase";
28 var $dataProvider = "ibase";
29 var $replaceQuote = "''"; // string to use to replace quotes
30 var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
31 var $fmtDate = "'Y-m-d'";
32 var $fmtTimeStamp = "'Y-m-d, H:i:s'";
33 var $concat_operator='||';
35 var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
37 var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";
41 var $_bindInputArray = true;
44 var $sysDate = "cast('TODAY' as date)";
45 var $sysTimeStamp = "cast('NOW' as timestamp)";
46 var $ansiOuter = true;
47 var $hasAffectedRows = false;
48 var $poorAffectedRows = true;
49 var $blobEncodeType = 'C';
51 function ADODB_ibase()
53 if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
56 function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
58 if ($internalKey) return array('RDB$DB_KEY');
60 $table = strtoupper($table);
62 $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
63 FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
64 WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
65 ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
67 $a = $this->GetCol($sql,false,true);
68 if ($a && sizeof($a)>0) return $a;
74 $arr['dialect'] = $this->dialect;
75 switch($arr['dialect']) {
77 case '1': $s = 'Interbase 5.5 or earlier'; break;
78 case '2': $s = 'Interbase 5.6'; break;
80 case '3': $s = 'Interbase 6.0'; break;
82 $arr['version'] = ADOConnection::_findvers($s);
83 $arr['description'] = $s;
89 if ($this->transOff) return true;
91 $this->autoCommit = false;
92 $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
93 return $this->_transactionID;
96 function CommitTrans($ok=true)
98 if (!$ok) return $this->RollbackTrans();
99 if ($this->transOff) return true;
100 if ($this->transCnt) $this->transCnt -= 1;
102 $this->autoCommit = true;
103 if ($this->_transactionID) {
105 $ret = ibase_commit($this->_transactionID);
107 $this->_transactionID = false;
111 function RollbackTrans()
113 if ($this->transOff) return true;
114 if ($this->transCnt) $this->transCnt -= 1;
116 $this->autoCommit = true;
117 if ($this->_transactionID)
118 $ret = ibase_rollback($this->_transactionID);
119 $this->_transactionID = false;
124 function &MetaIndexes ($table, $primary = FALSE, $owner=false)
126 // save old fetch mode
127 global $ADODB_FETCH_MODE;
129 $save = $ADODB_FETCH_MODE;
130 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
131 if ($this->fetchMode !== FALSE) {
132 $savem = $this->SetFetchMode(FALSE);
134 $table = strtoupper($table);
135 $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
137 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
139 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
142 $rs = $this->Execute($sql);
143 if (!is_object($rs)) {
146 $this->SetFetchMode($savem);
148 $ADODB_FETCH_MODE = $save;
153 while ($row = $rs->FetchRow()) {
155 if (!isset($indexes[$index])) {
156 if (is_null($row[3])) {$row[3] = 0;}
157 $indexes[$index] = array(
158 'unique' => ($row[3] == 1),
162 $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";
163 $rs1 = $this->Execute($sql);
164 while ($row1 = $rs1->FetchRow()) {
165 $indexes[$index]['columns'][$row1[2]] = $row1[1];
170 $this->SetFetchMode($savem);
172 $ADODB_FETCH_MODE = $save;
177 // See http://community.borland.com/article/0,1410,25844,00.html
178 function RowLock($tables,$where,$col)
180 if ($this->autoCommit) $this->BeginTrans();
181 $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
185 function CreateSequence($seqname,$startID=1)
187 $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
188 if (!$ok) return false;
189 return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
192 function DropSequence($seqname)
194 $seqname = strtoupper($seqname);
195 $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
198 function GenID($seqname='adodbseq',$startID=1)
200 $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
201 $rs = @$this->Execute($getnext);
203 $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
204 $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
205 $rs = $this->Execute($getnext);
207 if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
208 else $this->genID = 0; // false
210 if ($rs) $rs->Close();
215 function SelectDB($dbName)
220 function _handleerror()
222 $this->_errorMsg = ibase_errmsg();
227 if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
233 return $this->_errorMsg;
236 // returns true or false
237 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
239 if (!function_exists('ibase_pconnect')) return false;
240 if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
241 $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
242 if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
243 $this->replaceQuote = "''";
245 if ($this->_connectionID === false) {
246 $this->_handleerror();
250 ibase_timefmt($this->ibase_timefmt);
253 // returns true or false
254 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
256 if (!function_exists('ibase_pconnect')) return false;
257 if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
258 $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
259 if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
260 $this->replaceQuote = "''";
262 if ($this->_connectionID === false) {
263 $this->_handleerror();
267 ibase_timefmt($this->ibase_timefmt);
271 function Prepare($sql)
273 $stmt = ibase_prepare($this->_connectionID,$sql);
274 if (!$stmt) return false;
275 return array($sql,$stmt);
278 // returns query ID if successful, otherwise false
279 // there have been reports of problems with nested queries - the code is probably not re-entrant?
280 function _query($sql,$iarr=false)
283 if (!$this->autoCommit && $this->_transactionID) {
284 $conn = $this->_transactionID;
287 $conn = $this->_connectionID;
290 if (is_array($sql)) {
291 $fn = 'ibase_execute';
294 if (is_array($iarr)) {
295 if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
296 if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
297 $fnarr =& array_merge( array($sql) , $iarr);
298 $ret = call_user_func_array($fn,$fnarr);
300 switch(sizeof($iarr)) {
301 case 1: $ret = $fn($sql,$iarr[0]); break;
302 case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
303 case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
304 case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
305 case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
306 case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
307 case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
308 default: ADOConnection::outp( "Too many parameters to ibase query $sql");
309 case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
312 } else $ret = $fn($sql);
316 if (is_array($iarr)) {
317 if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
318 if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
319 $fnarr =& array_merge( array($conn,$sql) , $iarr);
320 $ret = call_user_func_array($fn,$fnarr);
322 switch(sizeof($iarr)) {
323 case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
324 case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
325 case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
326 case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
327 case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
328 case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
329 case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
330 default: ADOConnection::outp( "Too many parameters to ibase query $sql");
331 case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
334 } else $ret = $fn($conn,$sql);
336 if ($docommit && $ret === true) ibase_commit($this->_connectionID);
338 $this->_handleerror();
342 // returns true or false
345 if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
346 return @ibase_close($this->_connectionID);
350 function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)
352 $fscale = abs($fscale);
353 $fld->max_length = $flen;
361 $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
364 $fld->type = 'numeric';
365 $fld->max_length = $fprecision;
366 $fld->scale = $fscale;
369 $fld->type = 'decimal';
370 $fld->max_length = $fprecision;
371 $fld->scale = $fscale;
376 $fld->type = 'decimal';
377 $fld->scale = $fscale;
378 $fld->max_length = ($ftype == 7 ? 4 : 9);
380 $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
388 $fld->type = 'decimal';
389 $fld->max_length = 18;
393 $fld->type = 'numeric';
394 $fld->max_length = $fprecision;
395 $fld->scale = $fscale;
398 $fld->type = 'decimal';
399 $fld->max_length = $fprecision;
400 $fld->scale = $fscale;
406 $fld->type = 'float';
413 $fld->type = 'decimal';
414 $fld->max_length = 15;
417 $fld->type = 'double';
422 $fld->type = 'timestamp';
432 $fld->type = 'varchar';
435 $fld->type = 'cstring';
439 $fld->max_length = -1;
444 // returns array of ADOFieldObjects for current table
445 function &MetaColumns($table)
447 global $ADODB_FETCH_MODE;
449 if ($this->metaColumnsSQL) {
451 $save = $ADODB_FETCH_MODE;
452 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
454 $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
456 $ADODB_FETCH_MODE = $save;
457 if ($rs === false) return false;
461 $isInterbase6 = ($this->dialect==3 ? true : false);
463 while (!$rs->EOF) { //print_r($rs->fields);
464 $fld = new ADOFieldObject();
465 $fld->name = trim($rs->fields[0]);
467 $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);
468 if (isset($rs->fields[1]) && $rs->fields[1]) {
469 $fld->not_null = true;
471 if (isset($rs->fields[2])) {
473 $fld->has_default = true;
474 $d = substr($rs->fields[2],strlen('default '));
478 case 'integer': $fld->default_value = (int) $d; break;
482 case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
484 case 'float': $fld->default_value = (float) $d; break;
485 default: $fld->default_value = $d; break;
487 // case 35:$tt = 'TIMESTAMP'; break;
489 if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
490 $fld->sub_type = $rs->fields[5];
492 $fld->sub_type = null;
495 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
496 else $retarr[strtoupper($fld->name)] = $fld;
506 function BlobEncode( $blob )
508 $blobid = ibase_blob_create( $this->_connectionID);
509 ibase_blob_add( $blobid, $blob );
510 return ibase_blob_close( $blobid );
513 // since we auto-decode all blob's since 2.42,
514 // BlobDecode should not do any transforms
515 function BlobDecode($blob)
523 // old blobdecode function
524 // still used to auto-decode all blob's
525 function _BlobDecode( $blob )
527 $blobid = ibase_blob_open( $blob );
528 $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
529 while($string = ibase_blob_get($blobid, 8192)){
530 $realblob .= $string;
532 ibase_blob_close( $blobid );
537 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
539 $fd = fopen($path,'rb');
540 if ($fd === false) return false;
541 $blob_id = ibase_blob_create($this->_connectionID);
545 while ($val = fread($fd,32768)){
546 ibase_blob_add($blob_id, $val);
549 /* close and get $blob_id_str for inserting into table */
550 $blob_id_str = ibase_blob_close($blob_id);
553 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
557 Insert a null into the blob field of the table first.
558 Then use UpdateBlob to store the blob.
562 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
563 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
565 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
567 $blob_id = ibase_blob_create($this->_connectionID);
569 // ibase_blob_add($blob_id, $val);
571 // replacement that solves the problem by which only the first modulus 64K /
572 // of $val are stored at the blob field ////////////////////////////////////
573 // Thx Abel Berenstein aberenstein#afip.gov.ar
576 $tail_size = $len % $chunk_size;
577 $n_chunks = ($len - $tail_size) / $chunk_size;
579 for ($n = 0; $n < $n_chunks; $n++) {
580 $start = $n * $chunk_size;
581 $data = substr($val, $start, $chunk_size);
582 ibase_blob_add($blob_id, $data);
586 $start = $n_chunks * $chunk_size;
587 $data = substr($val, $start, $tail_size);
588 ibase_blob_add($blob_id, $data);
590 // end replacement /////////////////////////////////////////////////////////
592 $blob_id_str = ibase_blob_close($blob_id);
594 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
598 function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
600 $blob_id = ibase_blob_create($this->_connectionID);
601 ibase_blob_add($blob_id, $val);
602 $blob_id_str = ibase_blob_close($blob_id);
603 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
606 // Format date column in sql string given an input format that understands Y M D
607 // Only since Interbase 6.0 - uses EXTRACT
608 // problem - does not zero-fill the day and month yet
609 function SQLDate($fmt, $col=false)
611 if (!$col) $col = $this->sysDate;
615 for ($i=0; $i < $len; $i++) {
621 $s .= "extract(year from $col)";
625 $s .= "extract(month from $col)";
629 $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
633 $s .= "(extract(day from $col))";
637 $s .= "(extract(hour from $col))";
641 $s .= "(extract(minute from $col))";
645 $s .= "CAST((extract(second from $col)) AS INTEGER)";
651 $ch = substr($fmt,$i,1);
653 $s .= $this->qstr($ch);
661 /*--------------------------------------------------------------------------------------
662 Class Name: Recordset
663 --------------------------------------------------------------------------------------*/
665 class ADORecordset_ibase extends ADORecordSet
668 var $databaseType = "ibase";
672 function ADORecordset_ibase($id,$mode=false)
674 global $ADODB_FETCH_MODE;
676 $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
677 return $this->ADORecordSet($id);
680 /* Returns: an object containing field information.
681 Get column information in the Recordset object. fetchField() can be used in order to obtain information about
682 fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
683 fetchField() is retrieved. */
685 function &FetchField($fieldOffset = -1)
687 $fld = new ADOFieldObject;
688 $ibf = ibase_field_info($this->_queryID,$fieldOffset);
689 $fld->name = strtolower($ibf['alias']);
690 if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
691 $fld->type = $ibf['type'];
692 $fld->max_length = $ibf['length'];
698 $this->_numOfRows = -1;
699 $this->_numOfFields = @ibase_num_fields($this->_queryID);
701 // cache types for blob decode check
702 for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
703 $f1 = $this->FetchField($i);
704 $this->_cacheType[] = $f1->type;
715 $f = @ibase_fetch_row($this->_queryID);
717 $this->fields = false;
720 // OPN stuff start - optimized
721 // fix missing nulls and decode blobs automatically
723 global $ADODB_ANSI_PADDING_OFF;
724 //$ADODB_ANSI_PADDING_OFF=1;
725 $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
727 for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
728 if ($this->_cacheType[$i]=="BLOB") {
730 $f[$i] = $this->connection->_BlobDecode($f[$i]);
735 if (!isset($f[$i])) {
737 } else if ($rtrim && is_string($f[$i])) {
738 $f[$i] = rtrim($f[$i]);
745 if ($this->fetchMode == ADODB_FETCH_ASSOC) {
746 $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
747 } else if ($this->fetchMode == ADODB_FETCH_BOTH) {
748 $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
753 /* Use associative array to get fields array */
754 function Fields($colname)
756 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
758 $this->bind = array();
759 for ($i=0; $i < $this->_numOfFields; $i++) {
760 $o = $this->FetchField($i);
761 $this->bind[strtoupper($o->name)] = $i;
765 return $this->fields[$this->bind[strtoupper($colname)]];
771 return @ibase_free_result($this->_queryID);
774 function MetaType($t,$len=-1,$fieldobj=false)
778 $t = $fieldobj->type;
779 $len = $fieldobj->max_length;
781 switch (strtoupper($t)) {
788 if ($len <= $this->blobSize) return 'C';
794 case 'DATE': return 'D';
796 //case 'T': return 'T';
798 //case 'L': return 'L';
801 case 'INTEGER': return 'I';