3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * The PEAR DB driver for PHP's fbsql extension
7 * for interacting with FrontBase databases
11 * LICENSE: This source file is subject to version 3.0 of the PHP license
12 * that is available through the world-wide-web at the following URI:
13 * http://www.php.net/license/3_0.txt. If you did not receive a copy of
14 * the PHP License and are unable to obtain it through the web, please
15 * send a note to license@php.net so we can mail you a copy immediately.
19 * @author Frank M. Kromann <frank@frontbase.com>
20 * @author Daniel Convissor <danielc@php.net>
21 * @copyright 1997-2007 The PHP Group
22 * @license http://www.php.net/license/3_0.txt PHP License 3.0
23 * @version CVS: $Id: fbsql.php,v 1.88 2007/07/06 05:19:21 aharvey Exp $
24 * @link http://pear.php.net/package/DB
28 * Obtain the DB_common class so it can be extended from
30 require_once 'DB/common.php';
33 * The methods PEAR DB uses to interact with PHP's fbsql extension
34 * for interacting with FrontBase databases
36 * These methods overload the ones declared in DB_common.
40 * @author Frank M. Kromann <frank@frontbase.com>
41 * @author Daniel Convissor <danielc@php.net>
42 * @copyright 1997-2007 The PHP Group
43 * @license http://www.php.net/license/3_0.txt PHP License 3.0
44 * @version Release: 1.7.14RC1
45 * @link http://pear.php.net/package/DB
46 * @since Class functional since Release 1.7.0
48 class DB_fbsql extends DB_common
53 * The DB driver type (mysql, oci8, odbc, etc.)
56 var $phptype = 'fbsql';
59 * The database syntax variant to be used (db2, access, etc.), if any
62 var $dbsyntax = 'fbsql';
65 * The capabilities of this DB implementation
67 * The 'new_link' element contains the PHP version that first provided
68 * new_link support for this DBMS. Contains false if it's unsupported.
70 * Meaning of the 'limit' element:
71 * + 'emulate' = emulate with fetch row by number
72 * + 'alter' = alter the query
77 var $features = array(
84 'transactions' => true,
88 * A mapping of native error codes to DB error codes
91 var $errorcode_map = array(
92 22 => DB_ERROR_SYNTAX,
93 85 => DB_ERROR_ALREADY_EXISTS,
94 108 => DB_ERROR_SYNTAX,
95 116 => DB_ERROR_NOSUCHTABLE,
96 124 => DB_ERROR_VALUE_COUNT_ON_ROW,
97 215 => DB_ERROR_NOSUCHFIELD,
98 217 => DB_ERROR_INVALID_NUMBER,
99 226 => DB_ERROR_NOSUCHFIELD,
100 231 => DB_ERROR_INVALID,
101 239 => DB_ERROR_TRUNCATED,
102 251 => DB_ERROR_SYNTAX,
103 266 => DB_ERROR_NOT_FOUND,
104 357 => DB_ERROR_CONSTRAINT_NOT_NULL,
105 358 => DB_ERROR_CONSTRAINT,
106 360 => DB_ERROR_CONSTRAINT,
107 361 => DB_ERROR_CONSTRAINT,
111 * The raw database connection created by PHP
117 * The DSN information for connecting to a database
127 * This constructor calls <kbd>$this->DB_common()</kbd>
140 * Connect to the database server, log in and open the database
142 * Don't call this method directly. Use DB::connect() instead.
144 * @param array $dsn the data source name
145 * @param bool $persistent should the connection be persistent?
147 * @return int DB_OK on success. A DB_Error object on failure.
149 function connect($dsn, $persistent = false)
151 if (!PEAR::loadExtension('fbsql')) {
152 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
156 if ($dsn['dbsyntax']) {
157 $this->dbsyntax = $dsn['dbsyntax'];
161 $dsn['hostspec'] ? $dsn['hostspec'] : 'localhost',
162 $dsn['username'] ? $dsn['username'] : null,
163 $dsn['password'] ? $dsn['password'] : null,
166 $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
168 $ini = ini_get('track_errors');
171 $this->connection = @call_user_func_array($connect_function,
174 @ini_set('track_errors', 1);
175 $this->connection = @call_user_func_array($connect_function,
177 @ini_set('track_errors', $ini);
180 if (!$this->connection) {
181 return $this->raiseError(DB_ERROR_CONNECT_FAILED,
186 if ($dsn['database']) {
187 if (!@fbsql_select_db($dsn['database'], $this->connection)) {
188 return $this->fbsqlRaiseError();
199 * Disconnects from the database server
201 * @return bool TRUE on success, FALSE on failure
203 function disconnect()
205 $ret = @fbsql_close($this->connection);
206 $this->connection = null;
214 * Sends a query to the database server
216 * @param string the SQL query string
218 * @return mixed + a PHP result resrouce for successful SELECT queries
219 * + the DB_OK constant for other successful queries
220 * + a DB_Error object on failure
222 function simpleQuery($query)
224 $this->last_query = $query;
225 $query = $this->modifyQuery($query);
226 $result = @fbsql_query("$query;", $this->connection);
228 return $this->fbsqlRaiseError();
230 // Determine which queries that should return data, and which
231 // should return an error code only.
232 if ($this->_checkManip($query)) {
242 * Move the internal fbsql result pointer to the next available result
244 * @param a valid fbsql result resource
248 * @return true if a result is available otherwise return false
250 function nextResult($result)
252 return @fbsql_next_result($result);
259 * Places a row from the result set into the given array
261 * Formating of the array and the data therein are configurable.
262 * See DB_result::fetchInto() for more information.
264 * This method is not meant to be called directly. Use
265 * DB_result::fetchInto() instead. It can't be declared "protected"
266 * because DB_result is a separate object.
268 * @param resource $result the query result resource
269 * @param array $arr the referenced array to put the data in
270 * @param int $fetchmode how the resulting array should be indexed
271 * @param int $rownum the row number to fetch (0 = first row)
273 * @return mixed DB_OK on success, NULL when the end of a result set is
274 * reached or on failure
276 * @see DB_result::fetchInto()
278 function fetchInto($result, &$arr, $fetchmode, $rownum = null)
280 if ($rownum !== null) {
281 if (!@fbsql_data_seek($result, $rownum)) {
285 if ($fetchmode & DB_FETCHMODE_ASSOC) {
286 $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
287 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
288 $arr = array_change_key_case($arr, CASE_LOWER);
291 $arr = @fbsql_fetch_row($result);
296 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
297 $this->_rtrimArrayValues($arr);
299 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
300 $this->_convertNullArrayValuesToEmpty($arr);
309 * Deletes the result set and frees the memory occupied by the result set
311 * This method is not meant to be called directly. Use
312 * DB_result::free() instead. It can't be declared "protected"
313 * because DB_result is a separate object.
315 * @param resource $result PHP's query result resource
317 * @return bool TRUE on success, FALSE if $result is invalid
319 * @see DB_result::free()
321 function freeResult($result)
323 return is_resource($result) ? fbsql_free_result($result) : false;
330 * Enables or disables automatic commits
332 * @param bool $onoff true turns it on, false turns it off
334 * @return int DB_OK on success. A DB_Error object if the driver
335 * doesn't support auto-committing transactions.
337 function autoCommit($onoff=false)
340 $this->query("SET COMMIT TRUE");
342 $this->query("SET COMMIT FALSE");
350 * Commits the current transaction
352 * @return int DB_OK on success. A DB_Error object on failure.
356 @fbsql_commit($this->connection);
363 * Reverts the current transaction
365 * @return int DB_OK on success. A DB_Error object on failure.
369 @fbsql_rollback($this->connection);
376 * Gets the number of columns in a result set
378 * This method is not meant to be called directly. Use
379 * DB_result::numCols() instead. It can't be declared "protected"
380 * because DB_result is a separate object.
382 * @param resource $result PHP's query result resource
384 * @return int the number of columns. A DB_Error object on failure.
386 * @see DB_result::numCols()
388 function numCols($result)
390 $cols = @fbsql_num_fields($result);
392 return $this->fbsqlRaiseError();
401 * Gets the number of rows in a result set
403 * This method is not meant to be called directly. Use
404 * DB_result::numRows() instead. It can't be declared "protected"
405 * because DB_result is a separate object.
407 * @param resource $result PHP's query result resource
409 * @return int the number of rows. A DB_Error object on failure.
411 * @see DB_result::numRows()
413 function numRows($result)
415 $rows = @fbsql_num_rows($result);
416 if ($rows === null) {
417 return $this->fbsqlRaiseError();
423 // {{{ affectedRows()
426 * Determines the number of rows affected by a data maniuplation query
428 * 0 is returned for queries that don't manipulate data.
430 * @return int the number of rows. A DB_Error object on failure.
432 function affectedRows()
434 if ($this->_last_query_manip) {
435 $result = @fbsql_affected_rows($this->connection);
446 * Returns the next free id in a sequence
448 * @param string $seq_name name of the sequence
449 * @param boolean $ondemand when true, the seqence is automatically
450 * created if it does not exist
452 * @return int the next id number in the sequence.
453 * A DB_Error object on failure.
455 * @see DB_common::nextID(), DB_common::getSequenceName(),
456 * DB_fbsql::createSequence(), DB_fbsql::dropSequence()
458 function nextId($seq_name, $ondemand = true)
460 $seqname = $this->getSequenceName($seq_name);
463 $this->pushErrorHandling(PEAR_ERROR_RETURN);
464 $result = $this->query('SELECT UNIQUE FROM ' . $seqname);
465 $this->popErrorHandling();
466 if ($ondemand && DB::isError($result) &&
467 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
469 $result = $this->createSequence($seq_name);
470 if (DB::isError($result)) {
477 if (DB::isError($result)) {
478 return $this->fbsqlRaiseError();
480 $result->fetchInto($tmp, DB_FETCHMODE_ORDERED);
485 * Creates a new sequence
487 * @param string $seq_name name of the new sequence
489 * @return int DB_OK on success. A DB_Error object on failure.
491 * @see DB_common::createSequence(), DB_common::getSequenceName(),
492 * DB_fbsql::nextID(), DB_fbsql::dropSequence()
494 function createSequence($seq_name)
496 $seqname = $this->getSequenceName($seq_name);
497 $res = $this->query('CREATE TABLE ' . $seqname
498 . ' (id INTEGER NOT NULL,'
499 . ' PRIMARY KEY(id))');
501 $res = $this->query('SET UNIQUE = 0 FOR ' . $seqname);
507 // {{{ dropSequence()
512 * @param string $seq_name name of the sequence to be deleted
514 * @return int DB_OK on success. A DB_Error object on failure.
516 * @see DB_common::dropSequence(), DB_common::getSequenceName(),
517 * DB_fbsql::nextID(), DB_fbsql::createSequence()
519 function dropSequence($seq_name)
521 return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name)
526 // {{{ modifyLimitQuery()
529 * Adds LIMIT clauses to a query string according to current DBMS standards
531 * @param string $query the query to modify
532 * @param int $from the row to start to fetching (0 = the first row)
533 * @param int $count the numbers of rows to fetch
534 * @param mixed $params array, string or numeric data to be used in
535 * execution of the statement. Quantity of items
536 * passed must match quantity of placeholders in
537 * query: meaning 1 placeholder for non-array
538 * parameters or 1 placeholder per array element.
540 * @return string the query string with LIMIT clauses added
544 function modifyLimitQuery($query, $from, $count, $params = array())
546 if (DB::isManip($query) || $this->_next_query_manip) {
547 return preg_replace('/^([\s(])*SELECT/i',
548 "\\1SELECT TOP($count)", $query);
550 return preg_replace('/([\s(])*SELECT/i',
551 "\\1SELECT TOP($from, $count)", $query);
556 // {{{ quoteBoolean()
559 * Formats a boolean value for use within a query in a locale-independent
562 * @param boolean the boolean value to be quoted.
563 * @return string the quoted string.
564 * @see DB_common::quoteSmart()
565 * @since Method available since release 1.7.8.
567 function quoteBoolean($boolean) {
568 return $boolean ? 'TRUE' : 'FALSE';
575 * Formats a float value for use within a query in a locale-independent
578 * @param float the float value to be quoted.
579 * @return string the quoted string.
580 * @see DB_common::quoteSmart()
581 * @since Method available since release 1.7.8.
583 function quoteFloat($float) {
584 return $this->escapeSimple(str_replace(',', '.', strval(floatval($float))));
588 // {{{ fbsqlRaiseError()
591 * Produces a DB_Error object regarding the current problem
593 * @param int $errno if the error is being manually raised pass a
594 * DB_ERROR* constant here. If this isn't passed
595 * the error information gathered from the DBMS.
597 * @return object the DB_Error object
599 * @see DB_common::raiseError(),
600 * DB_fbsql::errorNative(), DB_common::errorCode()
602 function fbsqlRaiseError($errno = null)
604 if ($errno === null) {
605 $errno = $this->errorCode(fbsql_errno($this->connection));
607 return $this->raiseError($errno, null, null, null,
608 @fbsql_error($this->connection));
615 * Gets the DBMS' native error code produced by the last query
617 * @return int the DBMS' error code
619 function errorNative()
621 return @fbsql_errno($this->connection);
628 * Returns information about a table or a result set
630 * @param object|string $result DB_result object from a query or a
631 * string containing the name of a table.
632 * While this also accepts a query result
633 * resource identifier, this behavior is
635 * @param int $mode a valid tableInfo mode
637 * @return array an associative array with the information requested.
638 * A DB_Error object on failure.
640 * @see DB_common::tableInfo()
642 function tableInfo($result, $mode = null)
644 if (is_string($result)) {
646 * Probably received a table name.
647 * Create a result resource identifier.
649 $id = @fbsql_list_fields($this->dsn['database'],
650 $result, $this->connection);
652 } elseif (isset($result->result)) {
654 * Probably received a result object.
655 * Extract the result resource identifier.
657 $id = $result->result;
661 * Probably received a result resource identifier.
663 * Deprecated. Here for compatibility only.
669 if (!is_resource($id)) {
670 return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
673 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
674 $case_func = 'strtolower';
676 $case_func = 'strval';
679 $count = @fbsql_num_fields($id);
683 $res['num_fields'] = $count;
686 for ($i = 0; $i < $count; $i++) {
688 'table' => $case_func(@fbsql_field_table($id, $i)),
689 'name' => $case_func(@fbsql_field_name($id, $i)),
690 'type' => @fbsql_field_type($id, $i),
691 'len' => @fbsql_field_len($id, $i),
692 'flags' => @fbsql_field_flags($id, $i),
694 if ($mode & DB_TABLEINFO_ORDER) {
695 $res['order'][$res[$i]['name']] = $i;
697 if ($mode & DB_TABLEINFO_ORDERTABLE) {
698 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
702 // free the result only if we were called on a table
704 @fbsql_free_result($id);
710 // {{{ getSpecialQuery()
713 * Obtains the query string needed for listing a given type of objects
715 * @param string $type the kind of objects you want to retrieve
717 * @return string the SQL query string or null if the driver doesn't
718 * support the object type requested
721 * @see DB_common::getListOf()
723 function getSpecialQuery($type)
727 return 'SELECT "table_name" FROM information_schema.tables'
728 . ' t0, information_schema.schemata t1'
729 . ' WHERE t0.schema_pk=t1.schema_pk AND'
730 . ' "table_type" = \'BASE TABLE\''
731 . ' AND "schema_name" = current_schema';
733 return 'SELECT "table_name" FROM information_schema.tables'
734 . ' t0, information_schema.schemata t1'
735 . ' WHERE t0.schema_pk=t1.schema_pk AND'
736 . ' "table_type" = \'VIEW\''
737 . ' AND "schema_name" = current_schema';
739 return 'SELECT "user_name" from information_schema.users';
741 return 'SELECT "routine_name" FROM'
742 . ' information_schema.psm_routines'
743 . ' t0, information_schema.schemata t1'
744 . ' WHERE t0.schema_pk=t1.schema_pk'
745 . ' AND "routine_kind"=\'FUNCTION\''
746 . ' AND "schema_name" = current_schema';
748 return 'SELECT "routine_name" FROM'
749 . ' information_schema.psm_routines'
750 . ' t0, information_schema.schemata t1'
751 . ' WHERE t0.schema_pk=t1.schema_pk'
752 . ' AND "routine_kind"=\'PROCEDURE\''
753 . ' AND "schema_name" = current_schema';