2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license, |
9 // | that is bundled with this package in the file LICENSE, and is |
10 // | available at through the world-wide-web at |
11 // | http://www.php.net/license/2_02.txt. |
12 // | If you did not receive a copy of the PHP license and are unable to |
13 // | obtain it through the world-wide-web, please send a note to |
14 // | license@php.net so we can mail you a copy immediately. |
15 // +----------------------------------------------------------------------+
16 // | Author: Frank M. Kromann <frank@frontbase.com> |
17 // | Maintainer: Daniel Convissor <danielc@php.net> |
18 // +----------------------------------------------------------------------+
24 // XXX ERRORMSG: The error message from the fbsql function should
25 // be registered here.
31 require_once 'DB/common.php';
34 * Database independent query interface definition for PHP's FrontBase
40 * @author Frank M. Kromann <frank@frontbase.com>
42 class DB_fbsql extends DB_common
47 var $phptype, $dbsyntax;
48 var $prepare_tokens = array();
49 var $prepare_types = array();
50 var $num_rows = array();
51 var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
57 * DB_fbsql constructor.
64 $this->phptype = 'fbsql';
65 $this->dbsyntax = 'fbsql';
66 $this->features = array(
69 'transactions' => true,
72 $this->errorcode_map = array(
73 1004 => DB_ERROR_CANNOT_CREATE,
74 1005 => DB_ERROR_CANNOT_CREATE,
75 1006 => DB_ERROR_CANNOT_CREATE,
76 1007 => DB_ERROR_ALREADY_EXISTS,
77 1008 => DB_ERROR_CANNOT_DROP,
78 1046 => DB_ERROR_NODBSELECTED,
79 1050 => DB_ERROR_ALREADY_EXISTS,
80 1051 => DB_ERROR_NOSUCHTABLE,
81 1054 => DB_ERROR_NOSUCHFIELD,
82 1062 => DB_ERROR_ALREADY_EXISTS,
83 1064 => DB_ERROR_SYNTAX,
84 1100 => DB_ERROR_NOT_LOCKED,
85 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
86 1146 => DB_ERROR_NOSUCHTABLE,
94 * Connect to a database and log in as the specified user.
96 * @param $dsn the data source name (see DB::parseDSN for syntax)
97 * @param $persistent (optional) whether the connection should
100 * @return int DB_OK on success, a DB error on failure
102 function connect($dsninfo, $persistent = false)
104 if (!DB::assertExtension('fbsql')) {
105 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
108 $this->dsn = $dsninfo;
109 $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
112 $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
114 if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
115 $conn = @$connect_function($dbhost, $dsninfo['username'],
116 $dsninfo['password']);
117 } elseif ($dbhost && $dsninfo['username']) {
118 $conn = @$connect_function($dbhost, $dsninfo['username']);
120 $conn = @$connect_function($dbhost);
125 if (empty($php_errormsg)) {
126 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
128 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
129 null, $php_errormsg);
133 if ($dsninfo['database']) {
134 if (!fbsql_select_db($dsninfo['database'], $conn)) {
135 return $this->fbsqlRaiseError();
139 $this->connection = $conn;
147 * Log out and disconnect from the database.
151 * @return bool true on success, false if not connected.
153 function disconnect()
155 $ret = @fbsql_close($this->connection);
156 $this->connection = null;
164 * Send a query to fbsql and return the results as a fbsql resource
167 * @param the SQL query
171 * @return mixed returns a valid fbsql result for successful SELECT
172 * queries, DB_OK for other successful queries. A DB error is
173 * returned on failure.
175 function simpleQuery($query)
177 $this->last_query = $query;
178 $query = $this->modifyQuery($query);
179 $result = @fbsql_query("$query;", $this->connection);
181 return $this->fbsqlRaiseError();
183 // Determine which queries that should return data, and which
184 // should return an error code only.
185 if (DB::isManip($query)) {
188 $numrows = $this->numrows($result);
189 if (is_object($numrows)) {
192 $this->num_rows[$result] = $numrows;
200 * Move the internal fbsql result pointer to the next available result
202 * @param a valid fbsql result resource
206 * @return true if a result is available otherwise return false
208 function nextResult($result)
210 return @fbsql_next_result($result);
217 * Fetch a row and insert the data into an existing array.
219 * Formating of the array and the data therein are configurable.
220 * See DB_result::fetchInto() for more information.
222 * @param resource $result query result identifier
223 * @param array $arr (reference) array where data from the row
225 * @param int $fetchmode how the resulting array should be indexed
226 * @param int $rownum the row number to fetch
228 * @return mixed DB_OK on success, null when end of result set is
229 * reached or on failure
231 * @see DB_result::fetchInto()
234 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
236 if ($rownum !== null) {
237 if (!@fbsql_data_seek($result, $rownum)) {
241 if ($fetchmode & DB_FETCHMODE_ASSOC) {
242 $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
243 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
244 $arr = array_change_key_case($arr, CASE_LOWER);
247 $arr = @fbsql_fetch_row($result);
250 $errno = @fbsql_errno($this->connection);
254 return $this->fbsqlRaiseError($errno);
256 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
257 $this->_rtrimArrayValues($arr);
259 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
260 $this->_convertNullArrayValuesToEmpty($arr);
269 * Free the internal resources associated with $result.
271 * @param $result fbsql result identifier
275 * @return bool true on success, false if $result is invalid
277 function freeResult($result)
279 return @fbsql_free_result($result);
285 function autoCommit($onoff=false)
288 $this->query("SET COMMIT TRUE");
290 $this->query("SET COMMIT FALSE");
314 * Get the number of columns in a result set.
316 * @param $result fbsql result identifier
320 * @return int the number of columns per row in $result
322 function numCols($result)
324 $cols = @fbsql_num_fields($result);
327 return $this->fbsqlRaiseError();
337 * Get the number of rows in a result set.
339 * @param $result fbsql result identifier
343 * @return int the number of rows in $result
345 function numRows($result)
347 $rows = @fbsql_num_rows($result);
348 if ($rows === null) {
349 return $this->fbsqlRaiseError();
355 // {{{ affectedRows()
358 * Gets the number of rows affected by the data manipulation
359 * query. For other queries, this function returns 0.
361 * @return number of rows affected by the last query
363 function affectedRows()
365 if (DB::isManip($this->last_query)) {
366 $result = @fbsql_affected_rows($this->connection);
377 * Get the native error code of the last error (if any) that
378 * occured on the current connection.
382 * @return int native fbsql error code
384 function errorNative()
386 return @fbsql_errno($this->connection);
393 * Returns the next free id in a sequence
395 * @param string $seq_name name of the sequence
396 * @param boolean $ondemand when true, the seqence is automatically
397 * created if it does not exist
399 * @return int the next id number in the sequence. DB_Error if problem.
402 * @see DB_common::nextID()
405 function nextId($seq_name, $ondemand = true)
407 $seqname = $this->getSequenceName($seq_name);
410 $result = $this->query("INSERT INTO ${seqname} VALUES(NULL)");
411 if ($ondemand && DB::isError($result) &&
412 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
414 $result = $this->createSequence($seq_name);
415 if (DB::isError($result)) {
422 if (DB::isError($result)) {
425 return @fbsql_insert_id($this->connection);
429 * Creates a new sequence
431 * @param string $seq_name name of the new sequence
433 * @return int DB_OK on success. A DB_Error object is returned if
437 * @see DB_common::createSequence()
440 function createSequence($seq_name)
442 $seqname = $this->getSequenceName($seq_name);
443 return $this->query("CREATE TABLE ${seqname} ".
444 '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
445 ' PRIMARY KEY(id))');
449 // {{{ dropSequence()
454 * @param string $seq_name name of the sequence to be deleted
456 * @return int DB_OK on success. DB_Error if problems.
459 * @see DB_common::dropSequence()
462 function dropSequence($seq_name)
464 $seqname = $this->getSequenceName($seq_name);
465 return $this->query("DROP TABLE ${seqname} RESTRICT");
471 function modifyQuery($query)
473 if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
474 // "DELETE FROM table" gives 0 affected rows in fbsql.
475 // This little hack lets you know how many rows were deleted.
476 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
477 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
478 'DELETE FROM \1 WHERE 1=1', $query);
488 * Format input so it can be safely used in a query
490 * @param mixed $in data to be quoted
492 * @return mixed Submitted variable's type = returned value:
493 * + null = the string <samp>NULL</samp>
494 * + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
495 * + integer or double = the unquoted number
496 * + other (including strings and numeric strings) =
497 * the data escaped according to MySQL's settings
498 * then encapsulated between single quotes
502 function quoteSmart($in)
504 if (is_int($in) || is_double($in)) {
506 } elseif (is_bool($in)) {
507 return $in ? 'TRUE' : 'FALSE';
508 } elseif (is_null($in)) {
511 return "'" . $this->escapeSimple($in) . "'";
516 // {{{ fbsqlRaiseError()
519 * Gather information about an error, then use that info to create a
520 * DB error object and finally return that object.
522 * @param integer $errno PEAR error number (usually a DB constant) if
523 * manually raising an error
524 * @return object DB error object
525 * @see DB_common::errorCode()
526 * @see DB_common::raiseError()
528 function fbsqlRaiseError($errno = null)
530 if ($errno === null) {
531 $errno = $this->errorCode(fbsql_errno($this->connection));
533 return $this->raiseError($errno, null, null, null,
534 @fbsql_error($this->connection));
541 * Returns information about a table or a result set.
543 * @param object|string $result DB_result object from a query or a
544 * string containing the name of a table
545 * @param int $mode a valid tableInfo mode
546 * @return array an associative array with the information requested
547 * or an error object if something is wrong
550 * @see DB_common::tableInfo()
552 function tableInfo($result, $mode = null) {
553 if (isset($result->result)) {
555 * Probably received a result object.
556 * Extract the result resource identifier.
558 $id = $result->result;
560 } elseif (is_string($result)) {
562 * Probably received a table name.
563 * Create a result resource identifier.
565 $id = @fbsql_list_fields($this->dsn['database'],
566 $result, $this->connection);
570 * Probably received a result resource identifier.
572 * Depricated. Here for compatibility only.
578 if (!is_resource($id)) {
579 return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
582 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
583 $case_func = 'strtolower';
585 $case_func = 'strval';
588 $count = @fbsql_num_fields($id);
590 // made this IF due to performance (one if is faster than $count if's)
592 for ($i=0; $i<$count; $i++) {
593 $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
594 $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i));
595 $res[$i]['type'] = @fbsql_field_type($id, $i);
596 $res[$i]['len'] = @fbsql_field_len($id, $i);
597 $res[$i]['flags'] = @fbsql_field_flags($id, $i);
600 $res["num_fields"]= $count;
602 for ($i=0; $i<$count; $i++) {
603 $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
604 $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i));
605 $res[$i]['type'] = @fbsql_field_type($id, $i);
606 $res[$i]['len'] = @fbsql_field_len($id, $i);
607 $res[$i]['flags'] = @fbsql_field_flags($id, $i);
609 if ($mode & DB_TABLEINFO_ORDER) {
610 $res['order'][$res[$i]['name']] = $i;
612 if ($mode & DB_TABLEINFO_ORDERTABLE) {
613 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
618 // free the result only if we were called on a table
620 @fbsql_free_result($id);
626 // {{{ getSpecialQuery()
629 * Returns the query needed to get some backend info
630 * @param string $type What kind of info you want to retrieve
631 * @return string The SQL query string
633 function getSpecialQuery($type)
637 return 'select "table_name" from information_schema.tables';