Source for file ibase.php
Documentation is available at ibase.php
// vim: set et ts=4 sw=4 fdm=marker:
// +----------------------------------------------------------------------+
// | PHP versions 4 and 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox, |
// | Stig. S. Bakken, Lukas Smith |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Author: Lorenzo Alberton <l.alberton@quipo.it> |
// +----------------------------------------------------------------------+
// $Id: ibase.php,v 1.88 2005/04/25 13:09:03 lsmith Exp $
* MDB2 FireBird/InterBase driver
* @author Lorenzo Alberton <l.alberton@quipo.it>
$this->supported['summary_functions'] = true;
// maybe this needs different handling for ibase and firebird?
$this->options['database_path'] = '';
$this->options['database_extension'] = '.gdb';
$this->options['default_text_field_length'] = 4096;
* This method is used to collect information about an error
$native_msg = @ibase_errmsg ();
$native_code = @ibase_errcode ();
// memo for the interbase php module hackers: we need something similar
// to mysql_errno() to retrieve error codes instead of this ugly hack
if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/', $native_msg, $m)) {
$native_code = (int) $m[2 ];
// try to interpret Interbase error code (that's why we need ibase_errno()
// in the interbase module to return the real error code)
if (isset ($m[3 ]) && is_int(strpos($m[3 ], 'Table unknown'))) {
// -204 => // Covers too many errors, need to use regex on msg
// -607 => // Covers too many errors, need to use regex on msg
if (isset ($ecode_map[$native_code])) {
$error = $ecode_map[$native_code];
if (!isset ($error_regexps)) {
'/generator .* is not defined/'
'/table.*(not exist|not found|unknown)/i'
'/table .* already exists/i'
'/unsuccessful metadata update .* failed attempt to store duplicate value/i'
'/unsuccessful metadata update .* not found/i'
'/validation error for column .* value "\*\*\* null/i'
'/violation of [\w ]+ constraint/i'
'/conversion error from string/i'
'/arithmetic exception, numeric overflow, or string truncation/i'
foreach ($error_regexps as $regexp => $code) {
return array ($error, $native_code, $native_msg);
// {{{ beginTransaction()
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('starting transaction', 'beginTransaction');
'beginTransaction: could not start a transaction');
* Commit the database changes done during a transaction that is in
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('commit transaction', 'commit');
'commit: transaction changes are being auto committed');
'commit: could not commit a transaction');
//$this->transaction_id = 0;
* Cancel any database changes done during a transaction that is in
* @return mixed MDB2_OK on success, a MDB2 error on failure
$this->debug('rolling back transaction', 'rollback');
'rollback: transactions can not be rolled back when changes are auto committed');
'rollback: Could not rollback a pending transaction: '.ibase_errmsg ());
* Builds the string with path+dbname+extension
* @return string full database path+file
* Does the grunt work of connecting to the database
* @return mixed connection resource on success, MDB2 Error Object on failure
function _doConnect($database_name, $persistent = false )
$user = $this->dsn['username'];
$pw = $this->dsn['password'];
$dbhost = $this->dsn['hostspec'] ?
($this->dsn['hostspec']. ':'. $database_name) : $database_name;
$params[] = !empty ($user) ? $user : null;
$params[] = !empty ($pw) ? $pw : null;
$params[] = isset ($this->dsn['charset']) ? $this->dsn['charset'] : null;
$params[] = isset ($this->dsn['buffers']) ? $this->dsn['buffers'] : null;
$params[] = isset ($this->dsn['dialect']) ? $this->dsn['dialect'] : null;
$params[] = isset ($this->dsn['role']) ? $this->dsn['role'] : null;
$connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect';
@ibase_timefmt ("%Y-%m-%d %H:%M:%S", IBASE_TIMESTAMP );
@ibase_timefmt ("%Y-%m-%d", IBASE_DATE );
@ini_set("ibase.timestampformat", "%Y-%m-%d %H:%M:%S");
//@ini_set("ibase.timeformat", "%H:%M:%S");
@ini_set("ibase.dateformat", "%Y-%m-%d");
* Connect to the database
* @return true on success, MDB2 Error Object on failure
if (!PEAR ::loadExtension ('interbase')) {
'connect: extension '. $this->phptype. ' is not compiled into PHP');
if (PEAR ::isError ($connection)) {
* Log out and disconnect from the database.
* @return mixed true on success, false if not connected and error
* @param string $query query
* @param boolean $isManip if the query is a manipulation query
* @param resource $connection
* @param string $database_name
* @return result or error object
function _doQuery($query, $isManip = false , $connection = null , $database_name = null )
$this->debug($query, 'query');
if ($this->options['disable_query']) {
if (PEAR ::isError ($error)) {
$result = ibase_query ($connection, $query);
return (function_exists('ibase_affected_rows') ? ibase_affected_rows ($connection) : 0 );
* Changes a query string for various DBMS specific reasons
* @param string $query query to modify
* @return the new (modified) query
if ($limit > 0 && $this->dsn['dbsyntax'] == 'firebird') {
$query = preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i',
" SELECT FIRST $limit SKIP $offset" , $query);
* Prepares a query for multiple execution with execute().
* With some database backends, this is emulated.
* prepare() requires a generic query as string like
* 'INSERT INTO numbers VALUES(?,?)' or
* 'INSERT INTO numbers VALUES(:foo,:bar)'.
* The ? and :[a-zA-Z] and are placeholders which can be set using
* bindParam() and the query can be send off using the execute() method.
* @param string $query the query to prepare
* @param mixed $types array that contains the types of the placeholders
* @param mixed $result_types array that contains the types of the columns in
* @return mixed resource handle for the prepared query on success, a MDB2
* @see bindParam, execute
function &prepare($query, $types = null , $result_types = null )
$this->debug($query, 'prepare');
$placeholder_type_guess = $placeholder_type = null;
while ($position < strlen($query)) {
$q_position = strpos($query, $question, $position);
$c_position = strpos($query, $colon, $position);
if ($q_position && $c_position) {
$p_position = min($q_position, $c_position);
$p_position = $q_position;
$p_position = $c_position;
$placeholder_type_guess = $query[$p_position];
if (is_int($quote = strpos($query, "'", $position)) && $quote < $p_position) {
if (!is_int($end_quote = strpos($query, "'", $quote + 1 ))) {
'prepare: query with an unterminated text string specified');
$position = $end_quote + 1;
if ($end_quote == $quote + 1 ) {
$position = $end_quote + 1;
$position = $end_quote + 1;
} elseif ($query[$position] == $placeholder_type_guess) {
if ($placeholder_type_guess == '?') {
$placeholder_type = $query[$p_position];
$question = $colon = $placeholder_type;
$name = preg_replace('/^.{'. ($position+1 ). '}([a-z0-9_]+).*$/i', '\\1', $query);
'prepare: named parameter with an empty name');
$position = $p_position + 1;
$statement = ibase_prepare ($connection, $query);
$class_name = 'MDB2_Statement_'. $this->phptype;
$obj = & new $class_name($this, $statement, $query, $types, $result_types);
* returns the next free id of a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true the seqence is
* automatic created, if it
* @return mixed MDB2 Error Object or id
function nextID($seq_name, $ondemand = true )
$query = 'SELECT GEN_ID('. strtoupper($sequence_name). ', 1) as the_value FROM RDB$DATABASE';
$result = $this->queryOne($query, 'integer');
if (PEAR ::isError ($result)) {
// Since we are creating the sequence on demand
// we know the first id = 1 so initialize the
$result = $this->manager->createSequence ($seq_name, 2 );
if (PEAR ::isError ($result)) {
'nextID: on demand sequence could not be created');
// First ID of a newly created sequence is 1
// BUT generators are not always reset, so return the actual value
return $this->currID($seq_name);
* returns the current id of a sequence
* @param string $seq_name name of the sequence
* @return mixed MDB2 Error Object or id
$query = 'SELECT GEN_ID('. strtoupper($sequence_name). ', 0) as the_value FROM RDB$DATABASE';
if (PEAR ::isError ($value)) {
'currID: Unable to select from ' . $seq_name) ;
'currID: could not find value in sequence table');
class MDB2_Result_ibase extends MDB2_Result_Common
// {{{ _skipLimitOffset()
* Skip the first row of a result set.
* @param resource $result
* @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
function _skipLimitOffset ()
if ($db->dsn ['dbsyntax'] == 'firebird') {
if ($this->rownum > $this->limit) {
while ($this->offset_count < $this->offset) {
if (!is_array(@ibase_fetch_row ($this->result))) {
$this->offset_count = $this->offset;
* Fetch a row and insert the data into an existing array.
* @param int $fetchmode how the array data should be indexed
* @param int $rownum number of the row where the data can be found
* @return int data array on success, a MDB2 error on failure
function &fetchRow ($fetchmode = MDB2_FETCHMODE_DEFAULT , $rownum = null )
if ($this->result === true ) {
//query successfully executed, but without results...
if (!$this->_skipLimitOffset ()) {
$seek = $this->seek ($rownum);
if (PEAR ::isError ($seek)) {
$fetchmode = $this->db->fetchmode;
$row = @ibase_fetch_assoc ($this->result);
$row = @ibase_fetch_row ($this->result);
'fetchRow: resultset has already been freed');
$this->db->_rtrimArrayValues ($row);
$this->db->_convertEmptyArrayValuesToNull ($row);
if (isset ($this->values)) {
$this->_assignBindColumns ($row);
if (isset ($this->types)) {
$row = $this->db->datatype ->convertResultRow ($this->types, $row);
$object_class = $this->db->options ['fetch_class'];
if ($object_class == 'stdClass') {
$row = &new $object_class($row);
* Retrieve the names of columns returned by the DBMS in a query result.
* @return mixed associative array variable
* that holds the names of columns. The indexes of the array are
* the column names mapped to lower case and the values are the
* respective numbers of the columns starting from 0. Some DBMS may
* not return any columns when the result set does not contain any
function _getColumnNames ()
$numcols = $this->numCols ();
if (PEAR ::isError ($numcols)) {
for ($column = 0; $column < $numcols; $column++ ) {
$column_info = @ibase_field_info ($this->result, $column);
$columns[$column_info['alias']] = $column;
* Count the number of columns returned by the DBMS in a query result.
* @return mixed integer value with the number of columns, a MDB2 error
if ($this->result === true ) {
//query successfully executed, but without results...
return $this->db->raiseError ('numCols(): not a valid ibase resource');
$cols = @ibase_num_fields ($this->result);
'numCols: resultset has already been freed');
return $this->db->raiseError ();
* Free the internal resources associated with $result.
* @return boolean true on success, false if $result is invalid
$free = @ibase_free_result ($this->result);
return $this->db->raiseError ();
class MDB2_BufferedResult_ibase extends MDB2_Result_ibase
var $buffer_rownum = - 1;
* @param int $rownum row number upto which the buffer should be filled
* if the row number is null all rows are ready into the buffer
* @return boolean true on success, false on failure
function _fillBuffer ($rownum = null )
if (isset ($this->buffer) && is_array($this->buffer)) {
if (!end($this->buffer)) {
} elseif (isset ($this->buffer[$rownum])) {
return (bool) $this->buffer[$rownum];
if (!$this->_skipLimitOffset ()) {
while ((is_null($rownum) || $this->buffer_rownum < $rownum)
&& (!$this->limit || $this->buffer_rownum < $this->limit)
&& ($buffer = @ibase_fetch_row ($this->result))
$this->buffer[$this->buffer_rownum] = $buffer;
$this->buffer[$this->buffer_rownum] = false;
} elseif ($this->limit && $this->buffer_rownum >= $this->limit) {
$this->buffer[$this->buffer_rownum] = false;
* Fetch a row and insert the data into an existing array.
* @param int $fetchmode how the array data should be indexed
* @param int $rownum number of the row where the data can be found
* @return int data array on success, a MDB2 error on failure
function &fetchRow ($fetchmode = MDB2_FETCHMODE_DEFAULT , $rownum = null )
if ($this->result === true ) {
//query successfully executed, but without results...
'fetchRow: resultset has already been freed');
$seek = $this->seek ($rownum);
if (PEAR ::isError ($seek)) {
$target_rownum = $this->rownum + 1;
$fetchmode = $this->db->fetchmode;
if (!$this->_fillBuffer ($target_rownum)) {
$row = $this->buffer[$target_rownum];
$column_names = $this->getColumnNames ();
foreach ($column_names as $name => $i) {
$column_names[$name] = $row[$i];
$this->db->_convertEmptyArrayValuesToNull ($row);
if (isset ($this->values)) {
$this->_assignBindColumns ($row);
if (isset ($this->types)) {
$row = $this->db->datatype ->convertResultRow ($this->types, $row);
$this->db->_rtrimArrayValues ($row);
$this->db->_convertEmptyArrayValuesToNull ($row);
$object_class = $this->db->options ['fetch_class'];
if ($object_class == 'stdClass') {
$row = &new $object_class($row);
* seek to a specific row in a result set
* @param int $rownum number of the row where the data can be found
* @return mixed MDB2_OK on success, a MDB2 error on failure
function seek ($rownum = 0 )
'seek: resultset has already been freed');
$this->rownum = $rownum - 1;
* check if the end of the result set has been reached
* @return mixed true or false on sucess, a MDB2 error on failure
'valid: resultset has already been freed');
if ($this->_fillBuffer ($this->rownum + 1 )) {
* returns the number of rows in a result object
* @return mixed MDB2 Error Object or the number of rows
'seek: resultset has already been freed');
return $this->buffer_rownum;
* Free the internal resources associated with $result.
* @return boolean true on success, false if $result is invalid
$this->buffer_rownum = null;
class MDB2_Statement_ibase extends MDB2_Statement_Common
* Execute a prepared query statement.
* @param mixed $result_class string which specifies which result class to use
* @param mixed $result_wrap_class string which specifies which class to wrap results in
* @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
function &execute ($result_class = true , $result_wrap_class = false )
$this->db->last_query = $this->query;
$this->db->debug ($this->query, 'query');
if ($this->db->getOption ('disable_query')) {
$connected = $this->db->connect ();
if (PEAR ::isError ($connected)) {
$connection = ($this->db->in_transaction ? $this->db->transaction_id : $this->db->connection );
$parameters = $this->quoteParamsForPreparedQuery ();
$this->db->row_offset = $this->row_offset;
$this->db->row_limit = $this->row_limit;
return $this->db->raiseError ();
return (function_exists('ibase_affected_rows') ? ibase_affected_rows ($connection) : 0 );
return $this->db->_wrapResult ($result, $this->types,
$result_class, $result_wrap_class, $this->row_limit, $this->row_offset);
// {{{ quoteParamsForPreparedQuery()
function quoteParamsForPreparedQuery ()
$must_quote = array ('decimal', 'boolean', 'blob', 'clob');
foreach ($this->values as $parameter => $value) {
$type = isset ($this->types[$parameter]) ? $this->types[$parameter] : null;
if ($type == 'boolean') {
$value = ($value ? 'Y' : 'N');
$value = $this->db->quote ($value, $type);
} elseif (strpos($value, '?') !== false ) {
$value = "'". $this->db->escape ($value). "'";
Documentation generated on Mon, 11 Mar 2019 14:20:18 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|