See Release Notes
Long Term Support Release
Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]
1 <?php 2 /** 3 * Firebird driver. 4 * 5 * Requires firebird client. Works on Windows and Unix. 6 * 7 * This file is part of ADOdb, a Database Abstraction Layer library for PHP. 8 * 9 * @package ADOdb 10 * @link https://adodb.org Project's web site and documentation 11 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker 12 * 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 19 * 20 * @copyright 2000-2013 John Lim 21 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community 22 * 23 * Driver was cloned from Interbase, so there's quite a lot of duplicated code 24 * @noinspection DuplicatedCode 25 * @noinspection PhpUnused 26 */ 27 28 // security - hide paths 29 if (!defined('ADODB_DIR')) die(); 30 31 class ADODB_firebird extends ADOConnection { 32 var $databaseType = "firebird"; 33 var $dataProvider = "firebird"; 34 var $replaceQuote = "''"; // string to use to replace quotes 35 var $fbird_datefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S'; 36 var $fmtDate = "'Y-m-d'"; 37 var $fbird_timestampfmt = "%Y-%m-%d %H:%M:%S"; 38 var $fbird_timefmt = "%H:%M:%S"; 39 var $fmtTimeStamp = "'Y-m-d, H:i:s'"; 40 var $concat_operator='||'; 41 var $_transactionID; 42 43 public $metaTablesSQL = "SELECT LOWER(rdb\$relation_name) FROM rdb\$relations"; 44 //OPN STUFF start 45 46 var $metaColumnsSQL = "select lower(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"; 47 //OPN STUFF end 48 49 public $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s"; 50 51 public $_dropSeqSQL = "DROP SEQUENCE %s"; 52 53 var $hasGenID = true; 54 var $_bindInputArray = true; 55 var $sysDate = "cast('TODAY' as timestamp)"; 56 var $sysTimeStamp = "CURRENT_TIMESTAMP"; //"cast('NOW' as timestamp)"; 57 var $ansiOuter = true; 58 var $hasAffectedRows = true; 59 var $poorAffectedRows = false; 60 var $blobEncodeType = 'C'; 61 /* 62 * firebird custom optionally specifies the user role 63 */ 64 public $role = false; 65 /* 66 * firebird custom optionally specifies the connection buffers 67 */ 68 public $buffers = 0; 69 70 /* 71 * firebird custom optionally specifies database dialect 72 */ 73 public $dialect = 3; 74 75 var $nameQuote = ''; /// string to use to quote identifiers and names 76 77 function __construct() 78 { 79 parent::__construct(); 80 $this->setTransactionMode(''); 81 } 82 83 /** 84 * Sets the isolation level of a transaction. 85 * 86 * The default behavior is a more practical IBASE_WAIT | IBASE_REC_VERSION | IBASE_COMMITTED 87 * instead of IBASE_DEFAULT 88 * 89 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:settransactionmode 90 * 91 * @param string $transaction_mode The transaction mode to set. 92 * 93 * @return void 94 */ 95 public function setTransactionMode($transaction_mode) 96 { 97 $this->_transmode = $transaction_mode; 98 99 if (empty($transaction_mode)) { 100 $this->_transmode = IBASE_WAIT | IBASE_REC_VERSION | IBASE_COMMITTED; 101 } 102 103 } 104 105 /** 106 * Connect to a database. 107 * 108 * @todo add: parameter int $port, parameter string $socket 109 * 110 * @param string|null $argHostname (Optional) The host to connect to. 111 * @param string|null $argUsername (Optional) The username to connect as. 112 * @param string|null $argPassword (Optional) The password to connect with. 113 * @param string|null $argDatabasename (Optional) The name of the database to start in when connected. 114 * @param bool $persist (Optional) Whether or not to use a persistent connection. 115 * 116 * @return bool|null True if connected successfully, false if connection failed, or null if the mysqli extension 117 * isn't currently loaded. 118 */ 119 public function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false) 120 { 121 if (!function_exists('fbird_pconnect')) 122 return null; 123 124 if ($argDatabasename) 125 $argHostname .= ':'.$argDatabasename; 126 127 $fn = ($persist) ? 'fbird_pconnect':'fbird_connect'; 128 129 /* 130 * Now merge in the standard connection parameters setting 131 */ 132 foreach ($this->connectionParameters as $options) 133 { 134 foreach($options as $k=>$v) 135 { 136 switch($k){ 137 case 'role': 138 $this->role = $v; 139 break; 140 case 'dialect': 141 $this->dialect = $v; 142 break; 143 case 'buffers': 144 $this->buffers = $v; 145 } 146 } 147 } 148 149 if ($this->role) 150 $this->_connectionID = $fn($argHostname,$argUsername,$argPassword, 151 $this->charSet,$this->buffers,$this->dialect,$this->role); 152 else 153 $this->_connectionID = $fn($argHostname,$argUsername,$argPassword, 154 $this->charSet,$this->buffers,$this->dialect); 155 156 if ($this->dialect == 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html 157 $this->replaceQuote = ""; 158 } 159 if ($this->_connectionID === false) { 160 $this->_handleError(); 161 return false; 162 } 163 164 ini_set("ibase.timestampformat", $this->fbird_timestampfmt); 165 ini_set("ibase.dateformat", $this->fbird_datefmt); 166 ini_set("ibase.timeformat", $this->fbird_timefmt); 167 168 return true; 169 } 170 171 /** 172 * Connect to a database with a persistent connection. 173 * 174 * @param string|null $argHostname The host to connect to. 175 * @param string|null $argUsername The username to connect as. 176 * @param string|null $argPassword The password to connect with. 177 * @param string|null $argDatabasename The name of the database to start in when connected. 178 * 179 * @return bool|null True if connected successfully, false if connection failed, or null if the mysqli extension 180 * isn't currently loaded. 181 */ 182 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) 183 { 184 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,true); 185 } 186 187 188 public function metaPrimaryKeys($table,$owner_notused=false,$internalKey=false) 189 { 190 if ($internalKey) { 191 return array('RDB$DB_KEY'); 192 } 193 194 $table = strtoupper($table); 195 196 $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME 197 FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME 198 WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\' 199 ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION'; 200 201 $a = $this->GetCol($sql,false,true); 202 if ($a && sizeof($a)>0) return $a; 203 return false; 204 } 205 206 /** 207 * Get information about the current Firebird server. 208 * 209 * @return array 210 */ 211 public function serverInfo() 212 { 213 $arr['dialect'] = $this->dialect; 214 switch($arr['dialect']) { 215 case '': 216 case '1': 217 $s = 'Firebird Dialect 1'; 218 break; 219 case '2': 220 $s = 'Firebird Dialect 2'; 221 break; 222 default: 223 case '3': 224 $s = 'Firebird Dialect 3'; 225 break; 226 } 227 $arr['version'] = ADOConnection::_findvers($s); 228 $arr['description'] = $s; 229 return $arr; 230 } 231 232 /** 233 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). 234 * 235 * @return bool true if succeeded or false if database does not support transactions 236 */ 237 public function beginTrans() 238 { 239 if ($this->transOff) return true; 240 $this->transCnt += 1; 241 $this->autoCommit = false; 242 /* 243 * We manage the transaction mode via fbird_trans 244 */ 245 $this->_transactionID = fbird_trans( $this->_transmode, $this->_connectionID ); 246 return $this->_transactionID; 247 } 248 249 250 /** 251 * Commits a transaction. 252 * 253 * @param bool $ok false to rollback transaction, true to commit 254 * 255 * @return bool 256 */ 257 public function commitTrans($ok=true) 258 { 259 if (!$ok) { 260 return $this->RollbackTrans(); 261 } 262 if ($this->transOff) { 263 return true; 264 } 265 if ($this->transCnt) { 266 $this->transCnt -= 1; 267 } 268 $ret = false; 269 $this->autoCommit = true; 270 if ($this->_transactionID) { 271 $ret = fbird_commit($this->_transactionID); 272 } 273 $this->_transactionID = false; 274 return $ret; 275 } 276 277 function _affectedrows() 278 { 279 return fbird_affected_rows($this->_transactionID ?: $this->_connectionID); 280 } 281 282 /** 283 * Rollback a smart transaction. 284 * 285 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:rollbacktrans 286 * 287 * @return bool 288 */ 289 public function rollbackTrans() 290 { 291 if ($this->transOff) 292 return true; 293 if ($this->transCnt) 294 $this->transCnt -= 1; 295 296 $ret = false; 297 $this->autoCommit = true; 298 299 if ($this->_transactionID) { 300 $ret = fbird_rollback($this->_transactionID); 301 } 302 $this->_transactionID = false; 303 304 return $ret; 305 } 306 307 /** 308 * Get a list of indexes on the specified table. 309 * 310 * @param string $table The name of the table to get indexes for. 311 * @param bool $primary (Optional) Whether or not to include the primary key. 312 * @param bool $owner (Optional) Unused. 313 * 314 * @return array|bool An array of the indexes, or false if the query to get the indexes failed. 315 */ 316 public function metaIndexes($table, $primary = false, $owner = false) 317 { 318 // save old fetch mode 319 global $ADODB_FETCH_MODE; 320 $save = $ADODB_FETCH_MODE; 321 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 322 323 if ($this->fetchMode !== FALSE) { 324 $savem = $this->SetFetchMode(FALSE); 325 } 326 327 $table = strtoupper($table); 328 $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'"; 329 if (!$primary) { 330 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'"; 331 } else { 332 $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'"; 333 } 334 // get index details 335 $rs = $this->execute($sql); 336 if (!is_object($rs)) { 337 // restore fetchmode 338 if (isset($savem)) { 339 $this->SetFetchMode($savem); 340 } 341 $ADODB_FETCH_MODE = $save; 342 return false; 343 } 344 $indexes = array(); 345 while ($row = $rs->FetchRow()) { 346 347 $index = trim($row[0]); 348 if (!isset($indexes[$index])) { 349 if (is_null($row[3])) { 350 $row[3] = 0; 351 } 352 $indexes[$index] = array( 353 'unique' => ($row[3] == 1), 354 'columns' => array() 355 ); 356 } 357 $sql = sprintf("SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '%s' ORDER BY RDB\$FIELD_POSITION ASC",$index); 358 $rs1 = $this->execute($sql); 359 while ($row1 = $rs1->FetchRow()) { 360 $indexes[$index]['columns'][$row1[2]] = trim($row1[1]); 361 } 362 } 363 364 // restore fetchmode 365 if (isset($savem)) { 366 $this->SetFetchMode($savem); 367 } 368 $ADODB_FETCH_MODE = $save; 369 370 return $indexes; 371 } 372 373 /** 374 * Lock a table row for a duration of a transaction. 375 * 376 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:rowlock 377 * @link https://firebirdsql.org/refdocs/langrefupd21-notes-withlock.html 378 * 379 * @param string $table The table(s) to lock rows for. 380 * @param string $where (Optional) The WHERE clause to use to determine which rows to lock. 381 * @param string $col (Optional) The columns to select. 382 * 383 * @return bool True if the locking SQL statement executed successfully, otherwise false. 384 */ 385 public function rowLock($table,$where,$col=false) 386 { 387 if ($this->transCnt==0) 388 $this->beginTrans(); 389 390 if ($where) $where = ' where '.$where; 391 $rs = $this->execute("SELECT $col FROM $table $where FOR UPDATE WITH LOCK"); 392 return !empty($rs); 393 } 394 395 /** 396 * Creates a sequence in the database. 397 * 398 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:createsequence 399 * 400 * @param string $seqname The sequence name. 401 * @param int $startID The start id. 402 * 403 * @return ADORecordSet|bool A record set if executed successfully, otherwise false. 404 */ 405 public function createSequence($seqname='adodbseq', $startID = 1) 406 { 407 $sql = sprintf($this->_genSeqSQL,$seqname,$startID); 408 return $this->execute($sql); 409 } 410 411 /** 412 * A portable method of creating sequence numbers. 413 * 414 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:genid 415 * 416 * @param string $seqname (Optional) The name of the sequence to use. 417 * @param int $startID (Optional) The point to start at in the sequence. 418 * 419 * @return int 420 */ 421 public function genID($seqname='adodbseq',$startID=1) 422 { 423 $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE"); 424 $rs = @$this->Execute($getnext); 425 if (!$rs) { 426 $this->Execute("CREATE SEQUENCE $seqname START WITH $startID"); 427 $rs = $this->Execute($getnext); 428 } 429 if ($rs && !$rs->EOF) { 430 $this->genID = (integer) reset($rs->fields); 431 } 432 else { 433 $this->genID = 0; // false 434 } 435 436 if ($rs) { 437 $rs->Close(); 438 } 439 440 return $this->genID; 441 } 442 443 function selectDB($dbName) 444 { 445 return false; 446 } 447 448 function _handleError() 449 { 450 $this->_errorCode = fbird_errcode(); 451 $this->_errorMsg = fbird_errmsg(); 452 } 453 454 455 public function errorNo() 456 { 457 return (integer) $this->_errorCode; 458 } 459 460 function errorMsg() 461 { 462 return $this->_errorMsg; 463 } 464 465 /** 466 * Prepares an SQL statement and returns a handle to use. 467 * This is not used by bound parameters anymore 468 * 469 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:prepare 470 * @todo update this function to handle prepared statements correctly 471 * 472 * @param string $sql The SQL to prepare. 473 * 474 * @return bool|array The SQL that was provided and the prepared parameters, 475 * or false if the preparation fails 476 */ 477 public function prepare($sql) 478 { 479 $stmt = fbird_prepare($this->_connectionID,$sql); 480 if (!$stmt) 481 return false; 482 return array($sql,$stmt); 483 } 484 485 /** 486 * Return the query id. 487 * 488 * @param string|array $sql 489 * @param array $iarr 490 * 491 * @return bool|object 492 */ 493 function _query($sql, $iarr = false) 494 { 495 if (!$this->isConnected()) { 496 return false; 497 } 498 499 if (!$this->autoCommit && $this->_transactionID) { 500 $conn = $this->_transactionID; 501 $docommit = false; 502 } else { 503 $conn = $this->_connectionID; 504 $docommit = true; 505 } 506 507 if (is_array($sql)) { 508 // Prepared statement 509 $fn = 'fbird_execute'; 510 $args = [$sql[1]]; 511 } else { 512 $fn = 'fbird_query'; 513 $args = [$conn, $sql]; 514 } 515 if (is_array($iarr)) { 516 $args = array_merge($args, $iarr); 517 } 518 $ret = call_user_func_array($fn, $args); 519 520 if ($docommit && $ret === true) { 521 fbird_commit($this->_connectionID); 522 } 523 524 $this->_handleError(); 525 return $ret; 526 } 527 528 // returns true or false 529 function _close() 530 { 531 if (!$this->autoCommit) { 532 @fbird_rollback($this->_connectionID); 533 } 534 return @fbird_close($this->_connectionID); 535 } 536 537 //OPN STUFF start 538 function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $dialect3) 539 { 540 $fscale = abs($fscale); 541 $fld->max_length = $flen; 542 $fld->scale = null; 543 switch($ftype){ 544 case 7: 545 case 8: 546 if ($dialect3) { 547 switch($fsubtype){ 548 case 0: 549 $fld->type = ($ftype == 7 ? 'smallint' : 'integer'); 550 break; 551 case 1: 552 $fld->type = 'numeric'; 553 $fld->max_length = $fprecision; 554 $fld->scale = $fscale; 555 break; 556 case 2: 557 $fld->type = 'decimal'; 558 $fld->max_length = $fprecision; 559 $fld->scale = $fscale; 560 break; 561 } // switch 562 } else { 563 if ($fscale !=0) { 564 $fld->type = 'decimal'; 565 $fld->scale = $fscale; 566 $fld->max_length = ($ftype == 7 ? 4 : 9); 567 } else { 568 $fld->type = ($ftype == 7 ? 'smallint' : 'integer'); 569 } 570 } 571 break; 572 case 16: 573 if ($dialect3) { 574 switch($fsubtype){ 575 case 0: 576 $fld->type = 'decimal'; 577 $fld->max_length = 18; 578 $fld->scale = 0; 579 break; 580 case 1: 581 $fld->type = 'numeric'; 582 $fld->max_length = $fprecision; 583 $fld->scale = $fscale; 584 break; 585 case 2: 586 $fld->type = 'decimal'; 587 $fld->max_length = $fprecision; 588 $fld->scale = $fscale; 589 break; 590 } // switch 591 } 592 break; 593 case 10: 594 $fld->type = 'float'; 595 break; 596 case 14: 597 $fld->type = 'char'; 598 break; 599 case 27: 600 if ($fscale !=0) { 601 $fld->type = 'decimal'; 602 $fld->max_length = 15; 603 $fld->scale = 5; 604 } else { 605 $fld->type = 'double'; 606 } 607 break; 608 case 35: 609 if ($dialect3) { 610 $fld->type = 'timestamp'; 611 } else { 612 $fld->type = 'date'; 613 } 614 break; 615 case 12: 616 $fld->type = 'date'; 617 break; 618 case 13: 619 $fld->type = 'time'; 620 break; 621 case 37: 622 $fld->type = 'varchar'; 623 break; 624 case 40: 625 $fld->type = 'cstring'; 626 break; 627 case 261: 628 $fld->type = 'blob'; 629 $fld->max_length = -1; 630 break; 631 } // switch 632 } 633 //OPN STUFF end 634 635 /** 636 * Return an array of information about a table's columns. 637 * 638 * @param string $table The name of the table to get the column info for. 639 * @param bool $normalize (Optional) Unused. 640 * 641 * @return ADOFieldObject[]|bool An array of info for each column, 642 * or false if it could not determine the info. 643 */ 644 public function metaColumns($table, $normalize = true) 645 { 646 647 global $ADODB_FETCH_MODE; 648 649 $save = $ADODB_FETCH_MODE; 650 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 651 652 $rs = $this->execute(sprintf($this->metaColumnsSQL,strtoupper($table))); 653 654 $ADODB_FETCH_MODE = $save; 655 656 if ($rs === false) { 657 return false; 658 } 659 660 $retarr = array(); 661 //OPN STUFF start 662 $dialect3 = $this->dialect == 3; 663 //OPN STUFF end 664 while (!$rs->EOF) { //print_r($rs->fields); 665 $fld = new ADOFieldObject(); 666 $fld->name = trim($rs->fields[0]); 667 //OPN STUFF start 668 //print_r($rs->fields); 669 $this->_ConvertFieldType( 670 $fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $dialect3); 671 if (isset($rs->fields[1]) && $rs->fields[1]) { 672 $fld->not_null = true; 673 } 674 if (isset($rs->fields[2])) { 675 676 $fld->has_default = true; 677 $d = substr($rs->fields[2],strlen('default ')); 678 switch ($fld->type) { 679 case 'smallint': 680 case 'integer': 681 $fld->default_value = (int)$d; 682 break; 683 case 'char': 684 case 'blob': 685 case 'text': 686 case 'varchar': 687 $fld->default_value = (string)substr($d, 1, strlen($d) - 2); 688 break; 689 case 'double': 690 case 'float': 691 $fld->default_value = (float)$d; 692 break; 693 default: 694 $fld->default_value = $d; 695 break; 696 } 697 // case 35:$tt = 'TIMESTAMP'; break; 698 } 699 if ((isset($rs->fields[5])) && ($fld->type == 'blob')) { 700 $fld->sub_type = $rs->fields[5]; 701 } else { 702 $fld->sub_type = null; 703 } 704 //OPN STUFF end 705 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; 706 else $retarr[strtoupper($fld->name)] = $fld; 707 708 $rs->MoveNext(); 709 } 710 $rs->Close(); 711 if ( empty($retarr)) 712 return false; 713 else return $retarr; 714 } 715 716 /** 717 * Retrieves a list of tables based on given criteria 718 * 719 * @param string|bool $ttype (Optional) Table type = 'TABLE', 'VIEW' or false=both (default) 720 * @param string|bool $showSchema (Optional) schema name, false = current schema (default) 721 * @param string|bool $mask (Optional) filters the table by name 722 * 723 * @return array list of tables 724 */ 725 public function metaTables($ttype = false, $showSchema = false, $mask = false) 726 { 727 $save = $this->metaTablesSQL; 728 if (!$showSchema) { 729 $this->metaTablesSQL .= " WHERE (rdb\$relation_name NOT LIKE 'RDB\$%' AND rdb\$relation_name NOT LIKE 'MON\$%' AND rdb\$relation_name NOT LIKE 'SEC\$%')"; 730 } elseif (is_string($showSchema)) { 731 $this->metaTablesSQL .= $this->qstr($showSchema); 732 } 733 734 if ($mask) { 735 $mask = $this->qstr($mask); 736 $this->metaTablesSQL .= " AND table_name LIKE $mask"; 737 } 738 $ret = ADOConnection::metaTables($ttype,$showSchema); 739 740 $this->metaTablesSQL = $save; 741 return $ret; 742 } 743 744 /** 745 * Encodes a blob, then assigns an id ready to be used 746 * 747 * @param string $blob The blob to be encoded 748 * 749 * @return bool success 750 */ 751 public function blobEncode( $blob ) 752 { 753 $blobid = fbird_blob_create( $this->_connectionID); 754 fbird_blob_add( $blobid, $blob ); 755 return fbird_blob_close( $blobid ); 756 } 757 758 /** 759 * Manually decode a blob 760 * 761 * since we auto-decode all blob's since 2.42, 762 * BlobDecode should not do any transforms 763 * 764 * @param string $blob 765 * 766 * @return string the same blob 767 */ 768 public function blobDecode($blob) 769 { 770 return $blob; 771 } 772 773 /** 774 * Auto function called on read of blob to decode 775 * 776 * @param string $blob Value to decode 777 * 778 * @return string Decoded blob 779 */ 780 public function _blobDecode($blob) 781 { 782 if ($blob === null) { 783 return ''; 784 } 785 786 $blob_data = fbird_blob_info($this->_connectionID, $blob); 787 $blobId = fbird_blob_open($this->_connectionID, $blob); 788 789 if ($blob_data[0] > $this->maxblobsize) { 790 $realBlob = fbird_blob_get($blobId, $this->maxblobsize); 791 while ($string = fbird_blob_get($blobId, 8192)) { 792 $realBlob .= $string; 793 } 794 } else { 795 $realBlob = fbird_blob_get($blobId, $blob_data[0]); 796 } 797 798 fbird_blob_close($blobId); 799 return $realBlob; 800 } 801 802 /** 803 * Insert blob data into a database column directly 804 * from file 805 * 806 * @param string $table table to insert 807 * @param string $column column to insert 808 * @param string $path physical file name 809 * @param string $where string to find unique record 810 * @param string $blobtype BLOB or CLOB 811 * 812 * @return bool success 813 */ 814 public function updateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 815 { 816 $fd = fopen($path,'rb'); 817 if ($fd === false) 818 return false; 819 820 $blob_id = fbird_blob_create($this->_connectionID); 821 822 /* fill with data */ 823 824 while ($val = fread($fd,32768)){ 825 fbird_blob_add($blob_id, $val); 826 } 827 828 /* close and get $blob_id_str for inserting into table */ 829 $blob_id_str = fbird_blob_close($blob_id); 830 831 fclose($fd); 832 return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 833 } 834 835 /** 836 * Insert blob data into a database column 837 * 838 * @param string $table table to insert 839 * @param string $column column to insert 840 * @param string $val value to insert 841 * @param string $where string to find unique record 842 * @param string $blobtype BLOB or CLOB 843 * 844 * @return bool success 845 */ 846 public function updateBlob($table,$column,$val,$where,$blobtype='BLOB') 847 { 848 $blob_id = fbird_blob_create($this->_connectionID); 849 850 // fbird_blob_add($blob_id, $val); 851 852 // replacement that solves the problem by which only the first modulus 64K / 853 // of $val are stored at the blob field //////////////////////////////////// 854 // Thx Abel Berenstein aberenstein#afip.gov.ar 855 $len = strlen($val); 856 $chunk_size = 32768; 857 $tail_size = $len % $chunk_size; 858 $n_chunks = ($len - $tail_size) / $chunk_size; 859 860 for ($n = 0; $n < $n_chunks; $n++) { 861 $start = $n * $chunk_size; 862 $data = substr($val, $start, $chunk_size); 863 fbird_blob_add($blob_id, $data); 864 } 865 866 if ($tail_size) { 867 $start = $n_chunks * $chunk_size; 868 $data = substr($val, $start, $tail_size); 869 fbird_blob_add($blob_id, $data); 870 } 871 // end replacement ///////////////////////////////////////////////////////// 872 873 $blob_id_str = fbird_blob_close($blob_id); 874 875 return $this->execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 876 877 } 878 879 880 /** 881 * Returns a portably-formatted date string from a timestamp database column. 882 * 883 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:sqldate 884 * 885 * Firebird does not support an AM/PM format, so the A indicator always shows AM 886 * 887 * @param string $fmt The date format to use. 888 * @param string|bool $col (Optional) The table column to date format, or if false, use NOW(). 889 * 890 * @return string The SQL DATE_FORMAT() string, or empty if the provided date format was empty. 891 */ 892 public function sqlDate($fmt, $col=false) 893 { 894 if (!$col) 895 $col = 'CURRENT_TIMESTAMP'; 896 897 $s = ''; 898 899 $len = strlen($fmt); 900 for ($i=0; $i < $len; $i++) { 901 if ($s) $s .= '||'; 902 $ch = $fmt[$i]; 903 $choice = strtoupper($ch); 904 switch($choice) { 905 case 'Y': 906 $s .= "EXTRACT(YEAR FROM $col)"; 907 break; 908 case 'M': 909 $s .= "RIGHT('0' || TRIM(EXTRACT(MONTH FROM $col)),2)"; 910 break; 911 case 'W': 912 // The more accurate way of doing this is with a stored procedure 913 // See http://wiki.firebirdsql.org/wiki/index.php?page=DATE+Handling+Functions for details 914 $s .= "((EXTRACT(YEARDAY FROM $col) - EXTRACT(WEEKDAY FROM $col - 1) + 7) / 7)"; 915 break; 916 case 'Q': 917 $s .= "CAST(((EXTRACT(MONTH FROM $col)+2) / 3) AS INTEGER)"; 918 break; 919 case 'D': 920 $s .= "RIGHT('0' || TRIM(EXTRACT(DAY FROM $col)),2)"; 921 break; 922 case 'H': 923 $s .= "RIGHT('0' || TRIM(EXTRACT(HOUR FROM $col)),2)"; 924 break; 925 case 'I': 926 $s .= "RIGHT('0' || TRIM(EXTRACT(MINUTE FROM $col)),2)"; 927 break; 928 case 'S': 929 //$s .= "CAST((EXTRACT(SECOND FROM $col)) AS INTEGER)"; 930 $s .= "RIGHT('0' || TRIM(EXTRACT(SECOND FROM $col)),2)"; 931 break; 932 case 'A': 933 $s .= $this->qstr('AM'); 934 break; 935 default: 936 if ($ch == '\\') { 937 $i++; 938 $ch = substr($fmt,$i,1); 939 } 940 $s .= $this->qstr($ch); 941 break; 942 } 943 } 944 return $s; 945 } 946 947 /** 948 * Creates a portable date offset field, for use in SQL statements. 949 * 950 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:offsetdate 951 * 952 * @param float $dayFraction A day in floating point 953 * @param string|bool $date (Optional) The date to offset. If false, uses CURDATE() 954 * 955 * @return string 956 */ 957 public function offsetDate($dayFraction, $date=false) 958 { 959 if (!$date) 960 $date = $this->sysTimeStamp; 961 962 $fraction = $dayFraction * 24 * 3600; 963 return sprintf("DATEADD (second, %s, %s) FROM RDB\$DATABASE",$fraction,$date); 964 } 965 966 967 // Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars! 968 // SELECT col1, col2 FROM table ROWS 5 -- get 5 rows 969 // SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2 970 /** 971 * Executes a provided SQL statement and returns a handle to the result, with the ability to supply a starting 972 * offset and record count. 973 * 974 * @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:connection:selectlimit 975 * 976 * @param string $sql The SQL to execute. 977 * @param int $nrows (Optional) The limit for the number of records you want returned. By default, all results. 978 * @param int $offset (Optional) The offset to use when selecting the results. By default, no offset. 979 * @param array|bool $inputarr (Optional) Any parameter values required by the SQL statement, or false if none. 980 * @param int $secs2cache (Optional) If greater than 0, perform a cached execute. By default, normal execution. 981 * 982 * @return ADORecordSet|false The query results, or false if the query failed to execute. 983 */ 984 public function selectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs2cache=0) 985 { 986 $nrows = (integer) $nrows; 987 $offset = (integer) $offset; 988 $str = 'SELECT '; 989 if ($nrows >= 0) $str .= "FIRST $nrows "; 990 $str .=($offset>=0) ? "SKIP $offset " : ''; 991 992 $sql = preg_replace('/^[ \t]*select/i',$str,$sql); 993 if ($secs2cache) 994 $rs = $this->cacheExecute($secs2cache,$sql,$inputarr); 995 else 996 $rs = $this->execute($sql,$inputarr); 997 998 return $rs; 999 } 1000 1001 } 1002 1003 /** 1004 * Class ADORecordset_firebird 1005 */ 1006 class ADORecordset_firebird extends ADORecordSet 1007 { 1008 var $databaseType = "firebird"; 1009 var $bind = false; 1010 1011 /** 1012 * @var ADOFieldObject[] Holds a cached version of the metadata 1013 */ 1014 private $fieldObjects = false; 1015 1016 /** 1017 * @var bool Flags if we have retrieved the metadata 1018 */ 1019 private $fieldObjectsRetrieved = false; 1020 1021 /** 1022 * @var array Cross-reference the objects by name for easy access 1023 */ 1024 private $fieldObjectsIndex = array(); 1025 1026 /** 1027 * @var bool Flag to indicate if the result has a blob 1028 */ 1029 private $fieldObjectsHaveBlob = false; 1030 1031 function __construct($id, $mode = false) 1032 { 1033 global $ADODB_FETCH_MODE; 1034 1035 $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode; 1036 parent::__construct($id); 1037 } 1038 1039 1040 /** 1041 * Returns: an object containing field information. 1042 * 1043 * Get column information in the Recordset object. fetchField() 1044 * can be used in order to obtain information about fields in a 1045 * certain query result. If the field offset isn't specified, 1046 * the next field that wasn't yet retrieved by fetchField() 1047 * is retrieved. 1048 * 1049 * $param int $fieldOffset (optional default=-1 for all 1050 * @return mixed an ADOFieldObject, or array of objects 1051 */ 1052 private function _fetchField($fieldOffset = -1) 1053 { 1054 if ($this->fieldObjectsRetrieved) { 1055 if ($this->fieldObjects) { 1056 // Already got the information 1057 if ($fieldOffset == -1) { 1058 return $this->fieldObjects; 1059 } else { 1060 return $this->fieldObjects[$fieldOffset]; 1061 } 1062 } else { 1063 // No metadata available 1064 return false; 1065 } 1066 } 1067 1068 // Populate the field objects cache 1069 $this->fieldObjectsRetrieved = true; 1070 $this->fieldObjectsHaveBlob = false; 1071 $this->_numOfFields = fbird_num_fields($this->_queryID); 1072 for ($fieldIndex = 0; $fieldIndex < $this->_numOfFields; $fieldIndex++) { 1073 $fld = new ADOFieldObject; 1074 $ibf = fbird_field_info($this->_queryID, $fieldIndex); 1075 1076 $name = empty($ibf['alias']) ? $ibf['name'] : $ibf['alias']; 1077 1078 switch (ADODB_ASSOC_CASE) { 1079 case ADODB_ASSOC_CASE_UPPER: 1080 $fld->name = strtoupper($name); 1081 break; 1082 case ADODB_ASSOC_CASE_LOWER: 1083 $fld->name = strtolower($name); 1084 break; 1085 case ADODB_ASSOC_CASE_NATIVE: 1086 default: 1087 $fld->name = $name; 1088 break; 1089 } 1090 1091 $fld->type = $ibf['type']; 1092 $fld->max_length = $ibf['length']; 1093 1094 // This needs to be populated from the metadata 1095 $fld->not_null = false; 1096 $fld->has_default = false; 1097 $fld->default_value = 'null'; 1098 1099 $this->fieldObjects[$fieldIndex] = $fld; 1100 $this->fieldObjectsIndex[$fld->name] = $fieldIndex; 1101 1102 if ($fld->type == 'BLOB') { 1103 $this->fieldObjectsHaveBlob = true; 1104 } 1105 } 1106 1107 if ($fieldOffset == -1) { 1108 return $this->fieldObjects; 1109 } 1110 1111 return $this->fieldObjects[$fieldOffset]; 1112 } 1113 1114 /** 1115 * Fetchfield copies the oracle method, it loads the field information 1116 * into the _fieldobjs array once, to save multiple calls to the 1117 * fbird_ function 1118 * 1119 * @param int $fieldOffset (optional) 1120 * 1121 * @return adoFieldObject|false 1122 */ 1123 public function fetchField($fieldOffset = -1) 1124 { 1125 if ($fieldOffset == -1) { 1126 return $this->fieldObjects; 1127 } 1128 1129 return $this->fieldObjects[$fieldOffset]; 1130 } 1131 1132 function _initrs() 1133 { 1134 $this->_numOfRows = -1; 1135 1136 /* 1137 * Retrieve all of the column information first. We copy 1138 * this method from oracle 1139 */ 1140 $this->_fetchField(); 1141 1142 } 1143 1144 function _seek($row) 1145 { 1146 return false; 1147 } 1148 1149 public function _fetch() 1150 { 1151 // Case conversion function for use in Closure defined below 1152 $localFnCaseConv = null; 1153 1154 if ($this->fetchMode & ADODB_FETCH_ASSOC) { 1155 // Handle either associative or fetch both 1156 $localNumeric = false; 1157 1158 $f = @fbird_fetch_assoc($this->_queryID); 1159 if (is_array($f)) { 1160 // Optimally do the case_upper or case_lower 1161 if (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_LOWER) { 1162 $f = array_change_key_case($f, CASE_LOWER); 1163 $localFnCaseConv = 'strtolower'; 1164 } elseif (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_UPPER) { 1165 $f = array_change_key_case($f, CASE_UPPER); 1166 $localFnCaseConv = 'strtoupper'; 1167 } 1168 } 1169 } else { 1170 // Numeric fetch mode 1171 $localNumeric = true; 1172 $f = @fbird_fetch_row($this->_queryID); 1173 } 1174 1175 if ($f === false) { 1176 $this->fields = false; 1177 return false; 1178 } 1179 1180 // OPN stuff start - optimized 1181 // fix missing nulls and decode blobs automatically 1182 global $ADODB_ANSI_PADDING_OFF; 1183 $rtrim = !empty($ADODB_ANSI_PADDING_OFF); 1184 1185 // For optimal performance, only process if there is a possibility of something to do 1186 if ($this->fieldObjectsHaveBlob || $rtrim) { 1187 $localFieldObjects = $this->fieldObjects; 1188 $localFieldObjectIndex = $this->fieldObjectsIndex; 1189 /** @var ADODB_firebird $localConnection */ 1190 $localConnection = &$this->connection; 1191 1192 /** 1193 * Closure for an efficient method of iterating over the elements. 1194 * @param mixed $value 1195 * @param string|int $key 1196 * @return void 1197 */ 1198 $rowTransform = function ($value, $key) use ( 1199 &$f, 1200 $rtrim, 1201 $localFieldObjects, 1202 $localConnection, 1203 $localNumeric, 1204 $localFnCaseConv, 1205 $localFieldObjectIndex 1206 ) { 1207 if ($localNumeric) { 1208 $localKey = $key; 1209 } else { 1210 // Cross-reference the associative key back to numeric 1211 // with appropriate case conversion 1212 $index = $localFnCaseConv ? $localFnCaseConv($key) : $key; 1213 $localKey = $localFieldObjectIndex[$index]; 1214 } 1215 1216 // As we iterate the elements check for blobs and padding 1217 if ($localFieldObjects[$localKey]->type == 'BLOB') { 1218 $f[$key] = $localConnection->_BlobDecode($value); 1219 } else { 1220 if ($rtrim && is_string($value)) { 1221 $f[$key] = rtrim($value); 1222 } 1223 } 1224 1225 }; 1226 1227 // Walk the array, applying the above closure 1228 array_walk($f, $rowTransform); 1229 } 1230 1231 if (!$localNumeric && $this->fetchMode & ADODB_FETCH_NUM) { 1232 // Creates a fetch both 1233 $fNum = array_values($f); 1234 $f = array_merge($f, $fNum); 1235 } 1236 1237 $this->fields = $f; 1238 1239 return true; 1240 } 1241 1242 /** 1243 * Get the value of a field in the current row by column name. 1244 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. 1245 * 1246 * @param string $colname is the field to access 1247 * 1248 * @return mixed the value of $colname column 1249 */ 1250 public function fields($colname) 1251 { 1252 if ($this->fetchMode & ADODB_FETCH_ASSOC) { 1253 return $this->fields[$colname]; 1254 } 1255 1256 if (!$this->bind) { 1257 // fieldsObjectIndex populated by the recordset load 1258 $this->bind = array_change_key_case($this->fieldObjectsIndex, CASE_UPPER); 1259 } 1260 1261 return $this->fields[$this->bind[strtoupper($colname)]]; 1262 } 1263 1264 1265 function _close() 1266 { 1267 return @fbird_free_result($this->_queryID); 1268 } 1269 1270 public function metaType($t, $len = -1, $fieldObj = false) 1271 { 1272 if (is_object($t)) { 1273 $fieldObj = $t; 1274 $t = $fieldObj->type; 1275 $len = $fieldObj->max_length; 1276 } 1277 1278 $t = strtoupper($t); 1279 1280 if (array_key_exists($t, $this->connection->customActualTypes)) { 1281 return $this->connection->customActualTypes[$t]; 1282 } 1283 1284 switch ($t) { 1285 case 'CHAR': 1286 return 'C'; 1287 1288 case 'TEXT': 1289 case 'VARCHAR': 1290 case 'VARYING': 1291 if ($len <= $this->blobSize) { 1292 return 'C'; 1293 } 1294 return 'X'; 1295 case 'BLOB': 1296 return 'B'; 1297 1298 case 'TIMESTAMP': 1299 case 'DATE': 1300 return 'D'; 1301 case 'TIME': 1302 return 'T'; 1303 //case 'T': return 'T'; 1304 1305 //case 'L': return 'L'; 1306 case 'INT': 1307 case 'SHORT': 1308 case 'INTEGER': 1309 return 'I'; 1310 default: 1311 return ADODB_DEFAULT_METATYPE; 1312 } 1313 } 1314 1315 } 1316
title
Description
Body
title
Description
Body
title
Description
Body
title
Body