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,...)");
27 class ADODB_ibase extends ADOConnection {
28 var $databaseType = "ibase";
29 var $dataProvider = "ibase";
30 var $replaceQuote = "''"; // string to use to replace quotes
31 var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
32 var $fmtDate = "'Y-m-d'";
33 var $fmtTimeStamp = "'Y-m-d, H:i:s'";
34 var $concat_operator='||';
36 var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
38 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";
42 var $_bindInputArray = true;
45 var $sysDate = "cast('TODAY' as date)";
46 var $sysTimeStamp = "cast('NOW' as timestamp)";
47 var $ansiOuter = true;
48 var $hasAffectedRows = false;
49 var $poorAffectedRows = true;
50 var $blobEncodeType = 'C';
52 function ADODB_ibase()
54 if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
57 function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
59 if ($internalKey) return array('RDB$DB_KEY');
61 $table = strtoupper($table);
63 $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
64 FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
65 WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
66 ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
68 $a = $this->GetCol($sql,false,true);
69 if ($a && sizeof($a)>0) return $a;
75 $arr['dialect'] = $this->dialect;
76 switch($arr['dialect']) {
78 case '1': $s = 'Interbase 5.5 or earlier'; break;
79 case '2': $s = 'Interbase 5.6'; break;
81 case '3': $s = 'Interbase 6.0'; break;
83 $arr['version'] = ADOConnection::_findvers($s);
84 $arr['description'] = $s;
90 if ($this->transOff) return true;
92 $this->autoCommit = false;
93 $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
94 return $this->_transactionID;
97 function CommitTrans($ok=true)
99 if (!$ok) return $this->RollbackTrans();
100 if ($this->transOff) return true;
101 if ($this->transCnt) $this->transCnt -= 1;
103 $this->autoCommit = true;
104 if ($this->_transactionID) {
106 $ret = ibase_commit($this->_transactionID);
108 $this->_transactionID = false;
112 function RollbackTrans()
114 if ($this->transOff) return true;
115 if ($this->transCnt) $this->transCnt -= 1;
117 $this->autoCommit = true;
118 if ($this->_transactionID)
119 $ret = ibase_rollback($this->_transactionID);
120 $this->_transactionID = false;
125 function &MetaIndexes ($table, $primary = FALSE, $owner=false)
127 // save old fetch mode
128 global $ADODB_FETCH_MODE;
130 $save = $ADODB_FETCH_MODE;
131 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
132 if ($this->fetchMode !== FALSE) {
133 $savem = $this->SetFetchMode(FALSE);
135 $table = strtoupper($table);
136 $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
138 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
140 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
143 $rs = $this->Execute($sql);
144 if (!is_object($rs)) {
147 $this->SetFetchMode($savem);
149 $ADODB_FETCH_MODE = $save;
154 while ($row = $rs->FetchRow()) {
156 if (!isset($indexes[$index])) {
157 if (is_null($row[3])) {$row[3] = 0;}
158 $indexes[$index] = array(
159 'unique' => ($row[3] == 1),
163 $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";
164 $rs1 = $this->Execute($sql);
165 while ($row1 = $rs1->FetchRow()) {
166 $indexes[$index]['columns'][$row1[2]] = $row1[1];
171 $this->SetFetchMode($savem);
173 $ADODB_FETCH_MODE = $save;
179 // See http://community.borland.com/article/0,1410,25844,00.html
180 function RowLock($tables,$where,$col)
182 if ($this->autoCommit) $this->BeginTrans();
183 $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
188 function CreateSequence($seqname,$startID=1)
190 $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
191 if (!$ok) return false;
192 return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
195 function DropSequence($seqname)
197 $seqname = strtoupper($seqname);
198 $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
201 function GenID($seqname='adodbseq',$startID=1)
203 $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
204 $rs = @$this->Execute($getnext);
206 $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
207 $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
208 $rs = $this->Execute($getnext);
210 if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
211 else $this->genID = 0; // false
213 if ($rs) $rs->Close();
218 function SelectDB($dbName)
223 function _handleerror()
225 $this->_errorMsg = ibase_errmsg();
230 if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
236 return $this->_errorMsg;
239 // returns true or false
240 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
242 if (!function_exists('ibase_pconnect')) return false;
243 if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
244 $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
245 if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
246 $this->replaceQuote = "''";
248 if ($this->_connectionID === false) {
249 $this->_handleerror();
253 ibase_timefmt($this->ibase_timefmt);
256 // returns true or false
257 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
259 if (!function_exists('ibase_pconnect')) return false;
260 if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
261 $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
262 if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
263 $this->replaceQuote = "''";
265 if ($this->_connectionID === false) {
266 $this->_handleerror();
270 ibase_timefmt($this->ibase_timefmt);
274 function Prepare($sql)
276 $stmt = ibase_prepare($this->_connectionID,$sql);
277 if (!$stmt) return false;
278 return array($sql,$stmt);
281 // returns query ID if successful, otherwise false
282 // there have been reports of problems with nested queries - the code is probably not re-entrant?
283 function _query($sql,$iarr=false)
286 if (!$this->autoCommit && $this->_transactionID) {
287 $conn = $this->_transactionID;
290 $conn = $this->_connectionID;
293 if (is_array($sql)) {
294 $fn = 'ibase_execute';
297 if (is_array($iarr)) {
298 if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
299 if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
300 $fnarr =& array_merge( array($sql) , $iarr);
301 $ret = call_user_func_array($fn,$fnarr);
303 switch(sizeof($iarr)) {
304 case 1: $ret = $fn($sql,$iarr[0]); break;
305 case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
306 case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
307 case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
308 case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
309 case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
310 case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
311 default: ADOConnection::outp( "Too many parameters to ibase query $sql");
312 case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
315 } else $ret = $fn($sql);
319 if (is_array($iarr)) {
320 if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
321 if ( !isset($iarr[0]) ) $iarr[0] = ''; // PHP5 compat hack
322 $fnarr =& array_merge( array($conn,$sql) , $iarr);
323 $ret = call_user_func_array($fn,$fnarr);
325 switch(sizeof($iarr)) {
326 case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
327 case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
328 case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
329 case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
330 case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
331 case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
332 case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
333 default: ADOConnection::outp( "Too many parameters to ibase query $sql");
334 case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
337 } else $ret = $fn($conn,$sql);
339 if ($docommit && $ret === true) ibase_commit($this->_connectionID);
341 $this->_handleerror();
345 // returns true or false
348 if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
349 return @ibase_close($this->_connectionID);
353 function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)
355 $fscale = abs($fscale);
356 $fld->max_length = $flen;
364 $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
367 $fld->type = 'numeric';
368 $fld->max_length = $fprecision;
369 $fld->scale = $fscale;
372 $fld->type = 'decimal';
373 $fld->max_length = $fprecision;
374 $fld->scale = $fscale;
379 $fld->type = 'decimal';
380 $fld->scale = $fscale;
381 $fld->max_length = ($ftype == 7 ? 4 : 9);
383 $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
391 $fld->type = 'decimal';
392 $fld->max_length = 18;
396 $fld->type = 'numeric';
397 $fld->max_length = $fprecision;
398 $fld->scale = $fscale;
401 $fld->type = 'decimal';
402 $fld->max_length = $fprecision;
403 $fld->scale = $fscale;
409 $fld->type = 'float';
416 $fld->type = 'decimal';
417 $fld->max_length = 15;
420 $fld->type = 'double';
425 $fld->type = 'timestamp';
435 $fld->type = 'varchar';
438 $fld->type = 'cstring';
442 $fld->max_length = -1;
447 // returns array of ADOFieldObjects for current table
448 function &MetaColumns($table)
450 global $ADODB_FETCH_MODE;
452 if ($this->metaColumnsSQL) {
454 $save = $ADODB_FETCH_MODE;
455 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
457 $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
459 $ADODB_FETCH_MODE = $save;
460 if ($rs === false) return false;
464 $isInterbase6 = ($this->dialect==3 ? true : false);
466 while (!$rs->EOF) { //print_r($rs->fields);
467 $fld = new ADOFieldObject();
468 $fld->name = trim($rs->fields[0]);
470 $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);
471 if (isset($rs->fields[1]) && $rs->fields[1]) {
472 $fld->not_null = true;
474 if (isset($rs->fields[2])) {
476 $fld->has_default = true;
477 $d = substr($rs->fields[2],strlen('default '));
481 case 'integer': $fld->default_value = (int) $d; break;
485 case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
487 case 'float': $fld->default_value = (float) $d; break;
488 default: $fld->default_value = $d; break;
490 // case 35:$tt = 'TIMESTAMP'; break;
492 if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
493 $fld->sub_type = $rs->fields[5];
495 $fld->sub_type = null;
498 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
499 else $retarr[strtoupper($fld->name)] = $fld;
509 function BlobEncode( $blob )
511 $blobid = ibase_blob_create( $this->_connectionID);
512 ibase_blob_add( $blobid, $blob );
513 return ibase_blob_close( $blobid );
516 // since we auto-decode all blob's since 2.42,
517 // BlobDecode should not do any transforms
518 function BlobDecode($blob)
526 // old blobdecode function
527 // still used to auto-decode all blob's
528 function _BlobDecode( $blob )
530 $blobid = ibase_blob_open( $blob );
531 $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
532 while($string = ibase_blob_get($blobid, 8192)){
533 $realblob .= $string;
535 ibase_blob_close( $blobid );
540 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
542 $fd = fopen($path,'rb');
543 if ($fd === false) return false;
544 $blob_id = ibase_blob_create($this->_connectionID);
548 while ($val = fread($fd,32768)){
549 ibase_blob_add($blob_id, $val);
552 /* close and get $blob_id_str for inserting into table */
553 $blob_id_str = ibase_blob_close($blob_id);
556 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
560 Insert a null into the blob field of the table first.
561 Then use UpdateBlob to store the blob.
565 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
566 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
568 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
570 $blob_id = ibase_blob_create($this->_connectionID);
572 // ibase_blob_add($blob_id, $val);
574 // replacement that solves the problem by which only the first modulus 64K /
575 // of $val are stored at the blob field ////////////////////////////////////
576 // Thx Abel Berenstein aberenstein#afip.gov.ar
579 $tail_size = $len % $chunk_size;
580 $n_chunks = ($len - $tail_size) / $chunk_size;
582 for ($n = 0; $n < $n_chunks; $n++) {
583 $start = $n * $chunk_size;
584 $data = substr($val, $start, $chunk_size);
585 ibase_blob_add($blob_id, $data);
589 $start = $n_chunks * $chunk_size;
590 $data = substr($val, $start, $tail_size);
591 ibase_blob_add($blob_id, $data);
593 // end replacement /////////////////////////////////////////////////////////
595 $blob_id_str = ibase_blob_close($blob_id);
597 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
602 function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
604 $blob_id = ibase_blob_create($this->_connectionID);
605 ibase_blob_add($blob_id, $val);
606 $blob_id_str = ibase_blob_close($blob_id);
607 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
610 // Format date column in sql string given an input format that understands Y M D
611 // Only since Interbase 6.0 - uses EXTRACT
612 // problem - does not zero-fill the day and month yet
613 function SQLDate($fmt, $col=false)
615 if (!$col) $col = $this->sysDate;
619 for ($i=0; $i < $len; $i++) {
625 $s .= "extract(year from $col)";
629 $s .= "extract(month from $col)";
633 $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
637 $s .= "(extract(day from $col))";
641 $s .= "(extract(hour from $col))";
645 $s .= "(extract(minute from $col))";
649 $s .= "CAST((extract(second from $col)) AS INTEGER)";
655 $ch = substr($fmt,$i,1);
657 $s .= $this->qstr($ch);
665 /*--------------------------------------------------------------------------------------
666 Class Name: Recordset
667 --------------------------------------------------------------------------------------*/
669 class ADORecordset_ibase extends ADORecordSet
672 var $databaseType = "ibase";
676 function ADORecordset_ibase($id,$mode=false)
678 global $ADODB_FETCH_MODE;
680 $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
681 return $this->ADORecordSet($id);
684 /* Returns: an object containing field information.
685 Get column information in the Recordset object. fetchField() can be used in order to obtain information about
686 fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
687 fetchField() is retrieved. */
689 function &FetchField($fieldOffset = -1)
691 $fld = new ADOFieldObject;
692 $ibf = ibase_field_info($this->_queryID,$fieldOffset);
693 $fld->name = strtolower($ibf['alias']);
694 if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
695 $fld->type = $ibf['type'];
696 $fld->max_length = $ibf['length'];
702 $this->_numOfRows = -1;
703 $this->_numOfFields = @ibase_num_fields($this->_queryID);
705 // cache types for blob decode check
706 for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
707 $f1 = $this->FetchField($i);
708 $this->_cacheType[] = $f1->type;
721 $f = @ibase_fetch_row($this->_queryID);
723 $this->fields = false;
726 // OPN stuff start - optimized
727 // fix missing nulls and decode blobs automatically
729 global $ADODB_ANSI_PADDING_OFF;
730 //$ADODB_ANSI_PADDING_OFF=1;
731 $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
733 for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {
734 if ($this->_cacheType[$i]=="BLOB") {
736 $f[$i] = $this->connection->_BlobDecode($f[$i]);
741 if (!isset($f[$i])) {
743 } else if ($rtrim && is_string($f[$i])) {
744 $f[$i] = rtrim($f[$i]);
751 if ($this->fetchMode == ADODB_FETCH_ASSOC) {
752 $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
753 } else if ($this->fetchMode == ADODB_FETCH_BOTH) {
754 $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
759 /* Use associative array to get fields array */
760 function Fields($colname)
762 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
764 $this->bind = array();
765 for ($i=0; $i < $this->_numOfFields; $i++) {
766 $o = $this->FetchField($i);
767 $this->bind[strtoupper($o->name)] = $i;
771 return $this->fields[$this->bind[strtoupper($colname)]];
778 return @ibase_free_result($this->_queryID);
781 function MetaType($t,$len=-1,$fieldobj=false)
785 $t = $fieldobj->type;
786 $len = $fieldobj->max_length;
788 switch (strtoupper($t)) {
795 if ($len <= $this->blobSize) return 'C';
801 case 'DATE': return 'D';
803 //case 'T': return 'T';
805 //case 'L': return 'L';
808 case 'INTEGER': return 'I';