5 * Requires interbase client. Works on Windows and Unix.
7 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
10 * @link https://adodb.org Project's web site and documentation
11 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
13 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
14 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
15 * any later version. This means you can use it in proprietary products.
16 * See the LICENSE.md file distributed with this source code for details.
17 * @license BSD-3-Clause
18 * @license LGPL-2.1-or-later
20 * @copyright 2000-2013 John Lim
21 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
24 // security - hide paths
25 if (!defined('ADODB_DIR')) die();
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_datefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
32 var $fmtDate = "'Y-m-d'";
33 var $ibase_timestampfmt = "%Y-%m-%d %H:%M:%S";
34 var $ibase_timefmt = "%H:%M:%S";
35 var $fmtTimeStamp = "'Y-m-d, H:i:s'";
36 var $concat_operator='||';
38 var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
40 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";
44 var $_bindInputArray = true;
47 var $sysDate = "cast('TODAY' as timestamp)";
48 var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)";
49 var $ansiOuter = true;
50 var $hasAffectedRows = false;
51 var $poorAffectedRows = true;
52 var $blobEncodeType = 'C';
55 function __construct()
57 if (defined('IBASE_DEFAULT')) $this->ibasetrans
= IBASE_DEFAULT
;
61 // returns true or false
62 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false)
64 if (!function_exists('ibase_pconnect')) return null;
65 if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
66 $fn = ($persist) ?
'ibase_pconnect':'ibase_connect';
68 $this->_connectionID
= $fn($argHostname,$argUsername,$argPassword,
69 $this->charSet
,$this->buffers
,$this->dialect
,$this->role
);
71 $this->_connectionID
= $fn($argHostname,$argUsername,$argPassword,
72 $this->charSet
,$this->buffers
,$this->dialect
);
74 if ($this->dialect
!= 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
75 $this->replaceQuote
= "''";
77 if ($this->_connectionID
=== false) {
78 $this->_handleerror();
83 if (function_exists('ibase_timefmt')) {
84 ibase_timefmt($this->ibase_datefmt
,IBASE_DATE
);
85 if ($this->dialect
== 1) {
86 ibase_timefmt($this->ibase_datefmt
,IBASE_TIMESTAMP
);
89 ibase_timefmt($this->ibase_timestampfmt
,IBASE_TIMESTAMP
);
91 ibase_timefmt($this->ibase_timefmt
,IBASE_TIME
);
94 ini_set("ibase.timestampformat", $this->ibase_timestampfmt
);
95 ini_set("ibase.dateformat", $this->ibase_datefmt
);
96 ini_set("ibase.timeformat", $this->ibase_timefmt
);
101 // returns true or false
102 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
104 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,true);
108 function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
111 return array('RDB$DB_KEY');
114 $table = strtoupper($table);
116 $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
117 FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
118 WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
119 ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
121 $a = $this->GetCol($sql,false,true);
122 if ($a && sizeof($a)>0) return $a;
126 function ServerInfo()
128 $arr['dialect'] = $this->dialect
;
129 switch($arr['dialect']) {
131 case '1': $s = 'Interbase 5.5 or earlier'; break;
132 case '2': $s = 'Interbase 5.6'; break;
134 case '3': $s = 'Interbase 6.0'; break;
136 $arr['version'] = ADOConnection
::_findvers($s);
137 $arr['description'] = $s;
141 function BeginTrans()
143 if ($this->transOff
) return true;
144 $this->transCnt +
= 1;
145 $this->autoCommit
= false;
146 $this->_transactionID
= $this->_connectionID
;//ibase_trans($this->ibasetrans, $this->_connectionID);
147 return $this->_transactionID
;
150 function CommitTrans($ok=true)
153 return $this->RollbackTrans();
155 if ($this->transOff
) {
158 if ($this->transCnt
) {
159 $this->transCnt
-= 1;
162 $this->autoCommit
= true;
163 if ($this->_transactionID
) {
165 $ret = ibase_commit($this->_transactionID
);
167 $this->_transactionID
= false;
171 // there are some compat problems with ADODB_COUNTRECS=false and $this->_logsql currently.
172 // it appears that ibase extension cannot support multiple concurrent queryid's
173 function _Execute($sql,$inputarr=false)
175 global $ADODB_COUNTRECS;
177 if ($this->_logsql
) {
178 $savecrecs = $ADODB_COUNTRECS;
179 $ADODB_COUNTRECS = true; // force countrecs
180 $ret = ADOConnection
::_Execute($sql,$inputarr);
181 $ADODB_COUNTRECS = $savecrecs;
183 $ret = ADOConnection
::_Execute($sql,$inputarr);
188 function RollbackTrans()
190 if ($this->transOff
) return true;
191 if ($this->transCnt
) $this->transCnt
-= 1;
193 $this->autoCommit
= true;
194 if ($this->_transactionID
) {
195 $ret = ibase_rollback($this->_transactionID
);
197 $this->_transactionID
= false;
202 function MetaIndexes ($table, $primary = FALSE, $owner=false)
204 // save old fetch mode
205 global $ADODB_FETCH_MODE;
207 $save = $ADODB_FETCH_MODE;
208 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
209 if ($this->fetchMode
!== FALSE) {
210 $savem = $this->SetFetchMode(FALSE);
212 $table = strtoupper($table);
213 $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
215 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
217 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
220 $rs = $this->Execute($sql);
221 if (!is_object($rs)) {
224 $this->SetFetchMode($savem);
226 $ADODB_FETCH_MODE = $save;
231 while ($row = $rs->FetchRow()) {
233 if (!isset($indexes[$index])) {
234 if (is_null($row[3])) {
237 $indexes[$index] = array(
238 'unique' => ($row[3] == 1),
242 $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$index."' ORDER BY RDB\$FIELD_POSITION ASC";
243 $rs1 = $this->Execute($sql);
244 while ($row1 = $rs1->FetchRow()) {
245 $indexes[$index]['columns'][$row1[2]] = $row1[1];
250 $this->SetFetchMode($savem);
252 $ADODB_FETCH_MODE = $save;
258 // See http://community.borland.com/article/0,1410,25844,00.html
259 function RowLock($tables,$where,$col=false)
261 if ($this->autoCommit
) {
264 $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
269 function CreateSequence($seqname = 'adodbseq', $startID = 1)
271 $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
272 if (!$ok) return false;
273 return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
276 function DropSequence($seqname = 'adodbseq')
278 $seqname = strtoupper($seqname);
279 $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
282 function GenID($seqname='adodbseq',$startID=1)
284 $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
285 $rs = @$this->Execute($getnext);
287 $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
288 $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
289 $rs = $this->Execute($getnext);
291 if ($rs && !$rs->EOF
) {
292 $this->genID
= (integer) reset($rs->fields
);
295 $this->genID
= 0; // false
305 function SelectDB($dbName)
310 function _handleerror()
312 $this->_errorMsg
= ibase_errmsg();
317 if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg
,$arr)) return (integer) $arr[1];
323 return $this->_errorMsg
;
326 function Prepare($sql)
328 $stmt = ibase_prepare($this->_connectionID
,$sql);
329 if (!$stmt) return false;
330 return array($sql,$stmt);
333 // returns query ID if successful, otherwise false
334 // there have been reports of problems with nested queries - the code is probably not re-entrant?
335 function _query($sql,$iarr=false)
338 if (!$this->autoCommit
&& $this->_transactionID
) {
339 $conn = $this->_transactionID
;
342 $conn = $this->_connectionID
;
345 if (is_array($sql)) {
346 $fn = 'ibase_execute';
348 if (is_array($iarr)) {
349 if ( !isset($iarr[0]) )
350 $iarr[0] = ''; // PHP5 compat hack
351 $fnarr = array_merge( array($sql) , $iarr);
352 $ret = call_user_func_array($fn,$fnarr);
360 if (is_array($iarr)) {
361 if (sizeof($iarr) == 0)
362 $iarr[0] = ''; // PHP5 compat hack
363 $fnarr = array_merge( array($conn,$sql) , $iarr);
364 $ret = call_user_func_array($fn,$fnarr);
367 $ret = $fn($conn, $sql);
370 if ($docommit && $ret === true) {
371 ibase_commit($this->_connectionID
);
374 $this->_handleerror();
378 // returns true or false
381 if (!$this->autoCommit
) {
382 @ibase_rollback
($this->_connectionID
);
384 return @ibase_close
($this->_connectionID
);
388 function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $dialect3)
390 $fscale = abs($fscale);
391 $fld->max_length
= $flen;
399 $fld->type
= ($ftype == 7 ?
'smallint' : 'integer');
402 $fld->type
= 'numeric';
403 $fld->max_length
= $fprecision;
404 $fld->scale
= $fscale;
407 $fld->type
= 'decimal';
408 $fld->max_length
= $fprecision;
409 $fld->scale
= $fscale;
414 $fld->type
= 'decimal';
415 $fld->scale
= $fscale;
416 $fld->max_length
= ($ftype == 7 ?
4 : 9);
418 $fld->type
= ($ftype == 7 ?
'smallint' : 'integer');
426 $fld->type
= 'decimal';
427 $fld->max_length
= 18;
431 $fld->type
= 'numeric';
432 $fld->max_length
= $fprecision;
433 $fld->scale
= $fscale;
436 $fld->type
= 'decimal';
437 $fld->max_length
= $fprecision;
438 $fld->scale
= $fscale;
444 $fld->type
= 'float';
451 $fld->type
= 'decimal';
452 $fld->max_length
= 15;
455 $fld->type
= 'double';
460 $fld->type
= 'timestamp';
472 $fld->type
= 'varchar';
475 $fld->type
= 'cstring';
479 $fld->max_length
= -1;
485 // returns array of ADOFieldObjects for current table
486 function MetaColumns($table, $normalize=true)
488 global $ADODB_FETCH_MODE;
490 $save = $ADODB_FETCH_MODE;
491 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
493 $rs = $this->Execute(sprintf($this->metaColumnsSQL
,strtoupper($table)));
495 $ADODB_FETCH_MODE = $save;
503 $dialect3 = ($this->dialect
==3 ?
true : false);
505 while (!$rs->EOF
) { //print_r($rs->fields);
506 $fld = new ADOFieldObject();
507 $fld->name
= trim($rs->fields
[0]);
509 $this->_ConvertFieldType($fld, $rs->fields
[7], $rs->fields
[3], $rs->fields
[4], $rs->fields
[5], $rs->fields
[6], $dialect3);
510 if (isset($rs->fields
[1]) && $rs->fields
[1]) {
511 $fld->not_null
= true;
513 if (isset($rs->fields
[2])) {
515 $fld->has_default
= true;
516 $d = substr($rs->fields
[2],strlen('default '));
520 case 'integer': $fld->default_value
= (int) $d; break;
524 case 'varchar': $fld->default_value
= (string) substr($d,1,strlen($d)-2); break;
526 case 'float': $fld->default_value
= (float) $d; break;
527 default: $fld->default_value
= $d; break;
529 // case 35:$tt = 'TIMESTAMP'; break;
531 if ((isset($rs->fields
[5])) && ($fld->type
== 'blob')) {
532 $fld->sub_type
= $rs->fields
[5];
534 $fld->sub_type
= null;
537 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM
) $retarr[] = $fld;
538 else $retarr[strtoupper($fld->name
)] = $fld;
543 if ( empty($retarr)) return $false;
547 function BlobEncode( $blob )
549 $blobid = ibase_blob_create( $this->_connectionID
);
550 ibase_blob_add( $blobid, $blob );
551 return ibase_blob_close( $blobid );
554 // since we auto-decode all blob's since 2.42,
555 // BlobDecode should not do any transforms
556 function BlobDecode($blob)
564 // old blobdecode function
565 // still used to auto-decode all blob's
566 function _BlobDecode_old( $blob )
568 $blobid = ibase_blob_open($this->_connectionID
, $blob );
569 $realblob = ibase_blob_get( $blobid,$this->maxblobsize
); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
570 while($string = ibase_blob_get($blobid, 8192)){
571 $realblob .= $string;
573 ibase_blob_close( $blobid );
578 function _BlobDecode( $blob )
580 $blob_data = ibase_blob_info($this->_connectionID
, $blob );
581 $blobid = ibase_blob_open($this->_connectionID
, $blob );
583 if( $blob_data[0] > $this->maxblobsize
) {
585 $realblob = ibase_blob_get($blobid, $this->maxblobsize
);
587 while($string = ibase_blob_get($blobid, 8192)){
588 $realblob .= $string;
591 $realblob = ibase_blob_get($blobid, $blob_data[0]);
594 ibase_blob_close( $blobid );
598 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
600 $fd = fopen($path,'rb');
601 if ($fd === false) return false;
602 $blob_id = ibase_blob_create($this->_connectionID
);
606 while ($val = fread($fd,32768)){
607 ibase_blob_add($blob_id, $val);
610 /* close and get $blob_id_str for inserting into table */
611 $blob_id_str = ibase_blob_close($blob_id);
614 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
618 Insert a null into the blob field of the table first.
619 Then use UpdateBlob to store the blob.
623 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
624 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
626 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
628 $blob_id = ibase_blob_create($this->_connectionID
);
630 // ibase_blob_add($blob_id, $val);
632 // replacement that solves the problem by which only the first modulus 64K /
633 // of $val are stored at the blob field ////////////////////////////////////
634 // Thx Abel Berenstein aberenstein#afip.gov.ar
637 $tail_size = $len %
$chunk_size;
638 $n_chunks = ($len - $tail_size) / $chunk_size;
640 for ($n = 0; $n < $n_chunks; $n++
) {
641 $start = $n * $chunk_size;
642 $data = substr($val, $start, $chunk_size);
643 ibase_blob_add($blob_id, $data);
647 $start = $n_chunks * $chunk_size;
648 $data = substr($val, $start, $tail_size);
649 ibase_blob_add($blob_id, $data);
651 // end replacement /////////////////////////////////////////////////////////
653 $blob_id_str = ibase_blob_close($blob_id);
655 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
660 function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
662 $blob_id = ibase_blob_create($this->_connectionID
);
663 ibase_blob_add($blob_id, $val);
664 $blob_id_str = ibase_blob_close($blob_id);
665 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
668 // Format date column in sql string given an input format that understands Y M D
669 // Only since Interbase 6.0 - uses EXTRACT
670 // problem - does not zero-fill the day and month yet
671 function SQLDate($fmt, $col=false)
673 if (!$col) $col = $this->sysDate
;
677 for ($i=0; $i < $len; $i++
) {
683 $s .= "extract(year from $col)";
687 $s .= "extract(month from $col)";
691 $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
695 $s .= "(extract(day from $col))";
699 $s .= "(extract(hour from $col))";
703 $s .= "(extract(minute from $col))";
707 $s .= "CAST((extract(second from $col)) AS INTEGER)";
713 $ch = substr($fmt,$i,1);
715 $s .= $this->qstr($ch);
723 /*--------------------------------------------------------------------------------------
724 Class Name: Recordset
725 --------------------------------------------------------------------------------------*/
727 class ADORecordset_ibase
extends ADORecordSet
730 var $databaseType = "ibase";
734 function __construct($id,$mode=false)
736 global $ADODB_FETCH_MODE;
738 $this->fetchMode
= ($mode === false) ?
$ADODB_FETCH_MODE : $mode;
739 parent
::__construct($id);
742 /* Returns: an object containing field information.
743 Get column information in the Recordset object. fetchField() can be used in order to obtain information about
744 fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
745 fetchField() is retrieved. */
747 function FetchField($fieldOffset = -1)
749 $fld = new ADOFieldObject
;
750 $ibf = ibase_field_info($this->_queryID
,$fieldOffset);
752 $name = empty($ibf['alias']) ?
$ibf['name'] : $ibf['alias'];
754 switch (ADODB_ASSOC_CASE
) {
755 case ADODB_ASSOC_CASE_UPPER
:
756 $fld->name
= strtoupper($name);
758 case ADODB_ASSOC_CASE_LOWER
:
759 $fld->name
= strtolower($name);
761 case ADODB_ASSOC_CASE_NATIVE
:
767 $fld->type
= $ibf['type'];
768 $fld->max_length
= $ibf['length'];
770 /* This needs to be populated from the metadata */
771 $fld->not_null
= false;
772 $fld->has_default
= false;
773 $fld->default_value
= 'null';
779 $this->_numOfRows
= -1;
780 $this->_numOfFields
= @ibase_num_fields
($this->_queryID
);
782 // cache types for blob decode check
783 for ($i=0, $max = $this->_numOfFields
; $i < $max; $i++
) {
784 $f1 = $this->FetchField($i);
785 $this->_cacheType
[] = $f1->type
;
796 $f = @ibase_fetch_row
($this->_queryID
);
798 $this->fields
= false;
801 // OPN stuff start - optimized
802 // fix missing nulls and decode blobs automatically
804 global $ADODB_ANSI_PADDING_OFF;
805 //$ADODB_ANSI_PADDING_OFF=1;
806 $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
808 for ($i=0, $max = $this->_numOfFields
; $i < $max; $i++
) {
809 if ($this->_cacheType
[$i]=="BLOB") {
811 $f[$i] = $this->connection
->_BlobDecode($f[$i]);
816 if (!isset($f[$i])) {
818 } else if ($rtrim && is_string($f[$i])) {
819 $f[$i] = rtrim($f[$i]);
826 if ($this->fetchMode
== ADODB_FETCH_ASSOC
) {
827 $this->fields
= $this->GetRowAssoc();
828 } else if ($this->fetchMode
== ADODB_FETCH_BOTH
) {
829 $this->fields
= array_merge($this->fields
,$this->GetRowAssoc());
834 /* Use associative array to get fields array */
835 function Fields($colname)
837 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) return $this->fields
[$colname];
839 $this->bind
= array();
840 for ($i=0; $i < $this->_numOfFields
; $i++
) {
841 $o = $this->FetchField($i);
842 $this->bind
[strtoupper($o->name
)] = $i;
846 return $this->fields
[$this->bind
[strtoupper($colname)]];
853 return @ibase_free_result
($this->_queryID
);
856 function MetaType($t,$len=-1,$fieldobj=false)
860 $t = $fieldobj->type
;
861 $len = $fieldobj->max_length
;
863 switch (strtoupper($t)) {
870 if ($len <= $this->blobSize
) return 'C';
876 case 'DATE': return 'D';
877 case 'TIME': return 'T';
878 //case 'T': return 'T';
880 //case 'L': return 'L';
883 case 'INTEGER': return 'I';
884 default: return ADODB_DEFAULT_METATYPE
;