Source for file ibase.php
Documentation is available at ibase.php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
* The PEAR DB driver for PHP's interbase extension
* for interacting with Interbase and Firebird databases
* While this class works with PHP 4, PHP's InterBase extension is
* unstable in PHP 4. Use PHP 5.
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
* @author Sterling Hughes <sterling@php.net>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2007 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: ibase.php,v 1.116 2007/09/21 13:40:41 aharvey Exp $
* @link http://pear.php.net/package/DB
* Obtain the DB_common class so it can be extended from
require_once DB_PEAR_PATH.
'DB/common.php';
* The methods PEAR DB uses to interact with PHP's interbase extension
* for interacting with Interbase and Firebird databases
* These methods overload the ones declared in DB_common.
* While this class works with PHP 4, PHP's InterBase extension is
* unstable in PHP 4. Use PHP 5.
* NOTICE: limitQuery() only works for Firebird.
* @author Sterling Hughes <sterling@php.net>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2007 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.7.13
* @link http://pear.php.net/package/DB
* @since Class became stable in Release 1.7.0
* The DB driver type (mysql, oci8, odbc, etc.)
* The database syntax variant to be used (db2, access, etc.), if any
* The capabilities of this DB implementation
* The 'new_link' element contains the PHP version that first provided
* new_link support for this DBMS. Contains false if it's unsupported.
* Meaning of the 'limit' element:
* + 'emulate' = emulate with fetch row by number
* + 'alter' = alter the query
* NOTE: only firebird supports limit.
* A mapping of native error codes to DB error codes
-
150 =>
DB_ERROR_ACCESS_VIOLATION,
-
151 =>
DB_ERROR_ACCESS_VIOLATION,
-
155 =>
DB_ERROR_NOSUCHTABLE,
-
157 =>
DB_ERROR_NOSUCHFIELD,
-
158 =>
DB_ERROR_VALUE_COUNT_ON_ROW,
-
170 =>
DB_ERROR_MISMATCH,
-
171 =>
DB_ERROR_MISMATCH,
-
172 =>
DB_ERROR_INVALID,
// -204 => // Covers too many errors, need to use regex on msg
-
205 =>
DB_ERROR_NOSUCHFIELD,
-
206 =>
DB_ERROR_NOSUCHFIELD,
-
208 =>
DB_ERROR_INVALID,
-
219 =>
DB_ERROR_NOSUCHTABLE,
-
297 =>
DB_ERROR_CONSTRAINT,
-
303 =>
DB_ERROR_INVALID,
-
413 =>
DB_ERROR_INVALID_NUMBER,
-
530 =>
DB_ERROR_CONSTRAINT,
-
551 =>
DB_ERROR_ACCESS_VIOLATION,
-
552 =>
DB_ERROR_ACCESS_VIOLATION,
// -607 => // Covers too many errors, need to use regex on msg
-
625 =>
DB_ERROR_CONSTRAINT_NOT_NULL,
-
803 =>
DB_ERROR_CONSTRAINT,
-
804 =>
DB_ERROR_VALUE_COUNT_ON_ROW,
// -902 => // Covers too many errors, need to use regex on msg
-
904 =>
DB_ERROR_CONNECT_FAILED,
-
922 =>
DB_ERROR_NOSUCHDB,
-
923 =>
DB_ERROR_CONNECT_FAILED,
-
924 =>
DB_ERROR_CONNECT_FAILED
* The raw database connection created by PHP
* The DSN information for connecting to a database
* The number of rows affected by a data manipulation query
* Should data manipulation queries be committed automatically?
* The prepared statement handle from the most recently executed statement
* {@internal Mainly here because the InterBase/Firebird API is only
* able to retrieve data from result sets if the statemnt handle is
* Is the given prepared statement a data manipulation query?
var $manip_query =
array();
* This constructor calls <kbd>$this->DB_common()</kbd>
* Connect to the database server, log in and open the database
* Don't call this method directly. Use DB::connect() instead.
* PEAR DB's ibase driver supports the following extra DSN options:
* + buffers The number of database buffers to allocate for the
* + charset The default character set for a database.
* + dialect The default SQL dialect for any statement
* executed within a connection. Defaults to the
* highest one supported by client libraries.
* Functional only with InterBase 6 and up.
* + role Functional only with InterBase 5 and up.
* @param array $dsn the data source name
* @param bool $persistent should the connection be persistent?
* @return int DB_OK on success. A DB_Error object on failure.
function connect($dsn, $persistent =
false)
?
($dsn['hostspec'] .
':' .
$dsn['database'])
$dsn['username'] ?
$dsn['username'] :
null,
$dsn['password'] ?
$dsn['password'] :
null,
isset
($dsn['charset']) ?
$dsn['charset'] :
null,
isset
($dsn['buffers']) ?
$dsn['buffers'] :
null,
isset
($dsn['dialect']) ?
$dsn['dialect'] :
null,
isset
($dsn['role']) ?
$dsn['role'] :
null,
$connect_function =
$persistent ?
'ibase_pconnect' :
'ibase_connect';
* Disconnects from the database server
* @return bool TRUE on success, FALSE on failure
* Sends a query to the database server
* @param string the SQL query string
* @return mixed + a PHP result resrouce for successful SELECT queries
* + the DB_OK constant for other successful queries
* + a DB_Error object on failure
$result =
@ibase_query($this->connection, $query);
if ($this->autocommit &&
$ismanip) {
$this->affected =
$result;
// {{{ modifyLimitQuery()
* Adds LIMIT clauses to a query string according to current DBMS standards
* Only works with Firebird.
* @param string $query the query to modify
* @param int $from the row to start to fetching (0 = the first row)
* @param int $count the numbers of rows to fetch
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
* @return string the query string with LIMIT clauses added
if ($this->dsn['dbsyntax'] ==
'firebird') {
"SELECT FIRST $count SKIP $from", $query);
* Move the internal ibase result pointer to the next available result
* @param a valid fbsql result resource
* @return true if a result is available otherwise return false
* Places a row from the result set into the given array
* Formating of the array and the data therein are configurable.
* See DB_result::fetchInto() for more information.
* This method is not meant to be called directly. Use
* DB_result::fetchInto() instead. It can't be declared "protected"
* because DB_result is a separate object.
* @param resource $result the query result resource
* @param array $arr the referenced array to put the data in
* @param int $fetchmode how the resulting array should be indexed
* @param int $rownum the row number to fetch (0 = first row)
* @return mixed DB_OK on success, NULL when the end of a result set is
* @see DB_result::fetchInto()
function fetchInto($result, &$arr, $fetchmode, $rownum =
null)
$arr =
@ibase_fetch_assoc($result);
$arr =
@ibase_fetch_row($result);
* Deletes the result set and frees the memory occupied by the result set
* This method is not meant to be called directly. Use
* DB_result::free() instead. It can't be declared "protected"
* because DB_result is a separate object.
* @param resource $result PHP's query result resource
* @return bool TRUE on success, FALSE if $result is invalid
return is_resource($result) ?
ibase_free_result($result) :
false;
return is_resource($query) ?
ibase_free_query($query) :
false;
* Determines the number of rows affected by a data maniuplation query
* 0 is returned for queries that don't manipulate data.
* @return int the number of rows. A DB_Error object on failure.
* Gets the number of columns in a result set
* This method is not meant to be called directly. Use
* DB_result::numCols() instead. It can't be declared "protected"
* because DB_result is a separate object.
* @param resource $result PHP's query result resource
* @return int the number of columns. A DB_Error object on failure.
* @see DB_result::numCols()
$cols =
@ibase_num_fields($result);
* Prepares a query for multiple execution with execute().
* prepare() requires a generic query as string like <code>
* INSERT INTO numbers VALUES (?, ?, ?)
* </code>. The <kbd>?</kbd> characters are placeholders.
* Three types of placeholders can be used:
* + <kbd>?</kbd> a quoted scalar value, i.e. strings, integers
* + <kbd>!</kbd> value is inserted 'as is'
* + <kbd>&</kbd> requires a file name. The file's contents get
* inserted into the query (i.e. saving binary
* Use backslashes to escape placeholder characters if you don't want
* them to be interpreted as placeholders. Example: <code>
* "UPDATE foo SET col=? WHERE col='over \& under'"
* @param string $query query to be prepared
* @return mixed DB statement resource on success. DB_Error on failure.
$tokens =
preg_split('/((?<!\\\)[&?!])/', $query, -
1,
PREG_SPLIT_DELIM_CAPTURE);
foreach ($tokens as $key =>
$val) {
$newquery .=
$tokens[$key] .
'?';
$newquery =
substr($newquery, 0, -
1);
$stmt =
@ibase_prepare($this->connection, $newquery);
$this->manip_query[(int)
$stmt] =
DB::isManip($query);
* Executes a DB statement prepared with prepare().
* @param resource $stmt a DB statement resource returned from prepare()
* @param mixed $data array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 for non-array items or the
* quantity of elements in the array.
* @return object a new DB_Result or a DB_Error when fail
* @see DB_ibase::prepare()
function &execute($stmt, $data =
array())
foreach ($data as $key =>
$value) {
* ibase doesn't seem to have the ability to pass a
* parameter along unchanged, so strip off quotes from start
* and end, plus turn two single quotes to one single quote,
* in order to avoid the quotes getting escaped by
* ibase and ending up in the database.
$data[$key] =
preg_replace("/^'(.*)'$/", "\\1", $data[$key]);
$fp =
@fopen($data[$key], 'rb');
if ($this->autocommit && $this->manip_query[(int)$stmt]) {
@ibase_commit($this->connection);
* Frees the internal resources associated with a prepared query
* @param resource $stmt the prepared statement's PHP resource
* @param bool $free_resource should the PHP resource be freed too?
* Use false if you need to get data
* from the result set later.
* @return bool TRUE on success, FALSE if $result is invalid
* @see DB_ibase::prepare()
@ibase_free_query($stmt);
unset
($this->manip_query[(int)
$stmt]);
* Enables or disables automatic commits
* @param bool $onoff true turns it on, false turns it off
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
$this->autocommit =
$onoff ?
1 :
0;
* Commits the current transaction
* @return int DB_OK on success. A DB_Error object on failure.
* Reverts the current transaction
* @return int DB_OK on success. A DB_Error object on failure.
* Returns the next free id in a sequence
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
* @return int the next id number in the sequence.
* A DB_Error object on failure.
* @see DB_common::nextID(), DB_common::getSequenceName(),
* DB_ibase::createSequence(), DB_ibase::dropSequence()
function nextId($seq_name, $ondemand =
true)
$result =
$this->query("SELECT GEN_ID(${sqn}, 1) "
.
"WHERE RDB\$GENERATOR_NAME='${sqn}'");
* @param string $seq_name name of the new sequence
* @return int DB_OK on success. A DB_Error object on failure.
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_ibase::nextID(), DB_ibase::dropSequence()
$result =
$this->query("CREATE GENERATOR ${sqn}");
* @param string $seq_name name of the sequence to be deleted
* @return int DB_OK on success. A DB_Error object on failure.
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_ibase::nextID(), DB_ibase::createSequence()
return $this->query('DELETE FROM RDB$GENERATORS '
.
"WHERE RDB\$GENERATOR_NAME='"
// {{{ _ibaseFieldFlags()
* Supports "primary_key", "unique_key", "not_null", "default",
* @param string $field_name the name of the field
* @param string $table_name the name of the table
* @return string the flags
function _ibaseFieldFlags($field_name, $table_name)
$sql =
'SELECT R.RDB$CONSTRAINT_TYPE CTYPE'
.
' FROM RDB$INDEX_SEGMENTS I'
.
' JOIN RDB$RELATION_CONSTRAINTS R ON I.RDB$INDEX_NAME=R.RDB$INDEX_NAME'
.
' WHERE I.RDB$FIELD_NAME=\'' .
$field_name .
'\''
.
' AND UPPER(R.RDB$RELATION_NAME)=\'' .
strtoupper($table_name) .
'\'';
if ($obj =
@ibase_fetch_object($result)) {
@ibase_free_result($result);
if (isset
($obj->CTYPE) &&
trim($obj->CTYPE) ==
'PRIMARY KEY') {
$flags .=
'primary_key ';
if (isset
($obj->CTYPE) &&
trim($obj->CTYPE) ==
'UNIQUE') {
$sql =
'SELECT R.RDB$NULL_FLAG AS NFLAG,'
.
' R.RDB$DEFAULT_SOURCE AS DSOURCE,'
.
' F.RDB$FIELD_TYPE AS FTYPE,'
.
' F.RDB$COMPUTED_SOURCE AS CSOURCE'
.
' FROM RDB$RELATION_FIELDS R '
.
' JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME'
.
' WHERE UPPER(R.RDB$RELATION_NAME)=\'' .
strtoupper($table_name) .
'\''
.
' AND R.RDB$FIELD_NAME=\'' .
$field_name .
'\'';
if ($obj =
@ibase_fetch_object($result)) {
@ibase_free_result($result);
if (isset
($obj->NFLAG)) {
if (isset
($obj->DSOURCE)) {
if (isset
($obj->CSOURCE)) {
if (isset
($obj->FTYPE) &&
$obj->FTYPE ==
261) {
* Produces a DB_Error object regarding the current problem
* @param int $errno if the error is being manually raised pass a
* DB_ERROR* constant here. If this isn't passed
* the error information gathered from the DBMS.
* @return object the DB_Error object
* @see DB_common::raiseError(),
* DB_ibase::errorNative(), DB_ibase::errorCode()
$tmp =
$this->raiseError($errno, null, null, null, @ibase_errmsg());
* Gets the DBMS' native error code produced by the last query
* @return int the DBMS' error code. NULL if there is no error code.
* @since Method available since Release 1.7.0
if (preg_match('/^Dynamic SQL Error SQL error code = ([0-9-]+)/i',
* Maps native error codes to DB's portable ones
* @param int $nativecode the error code returned by the DBMS
* @return int the portable DB error code. Return DB_ERROR if the
* current driver doesn't have a mapping for the
* @since Method available since Release 1.7.0
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'
'/feature is not supported/i'
$errormsg =
@ibase_errmsg();
foreach ($error_regexps as $regexp =>
$code) {
* Returns information about a table or a result set
* NOTE: only supports 'table' and 'flags' if <var>$result</var>
* @param object|string $result DB_result object from a query or a
* string containing the name of a table.
* While this also accepts a query result
* resource identifier, this behavior is
* @param int $mode a valid tableInfo mode
* @return array an associative array with the information requested.
* A DB_Error object on failure.
* @see DB_common::tableInfo()
* Probably received a table name.
* Create a result resource identifier.
"SELECT * FROM $result WHERE 1=0");
} elseif (isset
($result->result)) {
* Probably received a result object.
* Extract the result resource identifier.
* Probably received a result resource identifier.
* Deprecated. Here for compatibility only.
$case_func =
'strtolower';
$count =
@ibase_num_fields($id);
$res['num_fields'] =
$count;
for ($i =
0; $i <
$count; $i++
) {
$info =
@ibase_field_info($id, $i);
'table' =>
$got_string ?
$case_func($result) :
'',
'name' =>
$case_func($info['name']),
'len' =>
$info['length'],
?
$this->_ibaseFieldFlags($info['name'], $result)
$res['order'][$res[$i]['name']] =
$i;
$res['ordertable'][$res[$i]['table']][$res[$i]['name']] =
$i;
// free the result only if we were called on a table
* Obtains the query string needed for listing a given type of objects
* @param string $type the kind of objects you want to retrieve
* @return string the SQL query string or null if the driver doesn't
* support the object type requested
* @see DB_common::getListOf()
return 'SELECT DISTINCT R.RDB$RELATION_NAME FROM '
.
'RDB$RELATION_FIELDS R WHERE R.RDB$SYSTEM_FLAG=0';
return 'SELECT DISTINCT RDB$VIEW_NAME from RDB$VIEW_RELATIONS';
return 'SELECT DISTINCT RDB$USER FROM RDB$USER_PRIVILEGES';
Documentation generated on Wed, 09 Feb 2011 09:01:30 +0700 by phpDocumentor 1.4.2