cvs: pear /MDB MAINTAINERS package.xml /MDB/MDB fbsql.php /MDB/MDB/Modules/Manager fbsql.php
| From: | Frank M. Kromann | Date: | Thu, 26 Dec 2002 21:38:05 +0000 |
| Subject: | cvs: pear /MDB MAINTAINERS package.xml /MDB/MDB fbsql.php /MDB/MDB/Modules/Manager fbsql.php | ||
| Groups: | php.pear.cvs | ||
| Request: | Send a blank email to pear-cvs+get-7963@lists.php.net to get a copy of this message | ||
fmk Thu Dec 26 16:38:05 2002 EDT
Added files:
/pear/MDB/MDB fbsql.php
/pear/MDB/MDB/Modules/Manager fbsql.php
Modified files:
/pear/MDB MAINTAINERS package.xml
Log:
Adding support for FrontBase (fbsql) in MDB Class.
This still need some testing!
Index: pear/MDB/MAINTAINERS diff -u pear/MDB/MAINTAINERS:1.2 pear/MDB/MAINTAINERS:1.3 --- pear/MDB/MAINTAINERS:1.2 Sat Nov 23 18:50:47 2002 +++ pear/MDB/MAINTAINERS Thu Dec 26 16:38:04 2002 @@ -3,12 +3,12 @@ ibase : Paul Cooper <pgc@ucecom.com> (might write one) fbird : msql : -mssql : +mssql : Frank M. Kromann <frank@kromann.info> (is writting one) mysql : Lukas Smith <smith@backendmedia.com> oci8 : odbc : Pierre-Alain Joye <paj@pearfr.org> (is writting one) pgsql : Paul Cooper <pgc@ucecom.com> sybase : ifx : -fbsql : +fbsql : Frank M. Kromann <frank@kromann.info> (is writting one) dbase : Index: pear/MDB/package.xml diff -u pear/MDB/package.xml:1.38 pear/MDB/package.xml:1.39 --- pear/MDB/package.xml:1.38 Fri Dec 20 13:28:42 2002 +++ pear/MDB/package.xml Thu Dec 26 16:38:04 2002 @@ -78,6 +78,12 @@ <name>Manuel Lemos</name> <email>mlemos@acm.org</email> </maintainer> + <maintainer> + <user>fmk</user> + <role>contributor</role> + <name>Frank M. Kromann</name> + <email>frank@kromann.info</email> + </maintainer> </maintainers> <release> <version></version> @@ -91,6 +97,7 @@ <file role="doc">README</file> <dir name="MDB"> <file role="php">Common.php</file> + <file role="php">fbsql.php</file> <file role="php">mysql.php</file> <file role="php">pgsql.php</file> <file role="php">Date.php</file> @@ -103,6 +110,7 @@ <file role="php">LOB.php</file> <dir name="Manager"> <file role="php">Common.php</file> + <file role="php">fbsql.php</file> <file role="php">mysql.php</file> <file role="php">pgsql.php</file> </dir> Index: pear/MDB/MDB/fbsql.php +++ pear/MDB/MDB/fbsql.php <?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1998-2002 Manuel Lemos, Tomas V.V.Cox, | // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann | // | All rights reserved. | // +----------------------------------------------------------------------+ // | MDB 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 | // | are met: | // | | // | 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: Lukas Smith <smith@dybnet.de> | // +----------------------------------------------------------------------+ // // $Id: fbsql.php,v 1.1 2002/12/26 21:38:04 fmk Exp $ // require_once 'MDB/Common.php'; /** * MDB FrontBase driver * * @package MDB * @category Database * @author Lukas Smith <smith@dybnet.de> * @author Frank M. Kromann <frank@kromann.info> */ class MDB_fbsql extends MDB_Common { // {{{ properties var $connection = 0; var $connected_host; var $connected_user; var $connected_password; var $connected_port; var $opened_persistent = ''; var $escape_quotes = "\\"; var $decimal_factor = 1.0; var $highest_fetched_row = array(); var $columns = array(); // MySQL specific class variable var $default_table_type = ''; var $fixed_float = 0; var $dummy_primary_key = 'dummy_primary_key'; // }}} // {{{ constructor /** * Constructor */ function MDB_fbsql($dsninfo = NULL, $options = NULL) { if(MDB::isError($common_contructor = $this->MDB_common($dsninfo, $options))) { return $common_contructor; } $this->phptype = 'fbsql'; $this->dbsyntax = 'fbsql'; if (PEAR::isError(PEAR::loadExtension($this->phptype))) { return PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND, NULL, NULL, 'extension {$type} is not compiled into PHP', 'MDB_Error', TRUE); } $this->supported['Sequences'] = 1; $this->supported['Indexes'] = 1; $this->supported['AffectedRows'] = 1; $this->supported['Summaryfunctions'] = 1; $this->supported['OrderByText'] = 1; $this->supported['CurrId'] = 1; $this->supported['SelectRowRanges'] = 1; $this->supported['LOBs'] = 1; $this->supported['Replace'] = 0; $this->supported['SubSelects'] = 1; if(isset($this->options['UseTransactions']) && $this->options['UseTransactions']) { $this->supported['Transactions'] = 1; $this->default_table_type = 'BDB'; } else { $this->default_table_type = ''; } if(isset($this->options['DefaultTableType'])) { switch($this->default_table_type = strtoupper($this->options['DefaultTableType'])) { case 'BERKELEYDB': $this->default_table_type = 'BDB'; case 'BDB': case 'INNODB': case 'GEMINI': break; case 'HEAP': case 'ISAM': case 'MERGE': case 'MRG_MYISAM': case 'MYISAM': if(isset($this->supported['Transactions'])) { $this->warnings[] = $this->options['DefaultTableType'] .' is not a transaction-safe default table type'; } break; default: $this->warnings[] = $this->options['DefaultTableType'] .' is not a supported default table type'; } } $this->decimal_factor = pow(10.0, $this->decimal_places); $this->errorcode_map = array( 1004 => MDB_ERROR_CANNOT_CREATE, 1005 => MDB_ERROR_CANNOT_CREATE, 1006 => MDB_ERROR_CANNOT_CREATE, 1007 => MDB_ERROR_ALREADY_EXISTS, 1008 => MDB_ERROR_CANNOT_DROP, 1046 => MDB_ERROR_NODBSELECTED, 1050 => MDB_ERROR_ALREADY_EXISTS, 1051 => MDB_ERROR_NOSUCHTABLE, 1054 => MDB_ERROR_NOSUCHFIELD, 1062 => MDB_ERROR_ALREADY_EXISTS, 1064 => MDB_ERROR_SYNTAX, 1100 => MDB_ERROR_NOT_LOCKED, 1136 => MDB_ERROR_VALUE_COUNT_ON_ROW, 1146 => MDB_ERROR_NOSUCHTABLE, 1048 => MDB_ERROR_CONSTRAINT, ); } // }}} // {{{ errorNative() /** * Get the native error code of the last error (if any) that * occured on the current connection. * * @access public * * @return int native FrontBase error code */ function errorNative() { return fbsql_errno($this->connection); } // }}} // {{{ fbsqlRaiseError() /** * This method is used to communicate an error and invoke error * callbacks etc. Basically a wrapper for MDB::raiseError * that checks for native error msgs. * * @param integer $errno error code * @return object a PEAR error object * @access public * @see PEAR_Error */ function fbsqlRaiseError($errno = NULL) { if ($errno == NULL) { $errno = $this->errorCode(fbsql_errno($this->connection)); } return $this->raiseError($errno, NULL, NULL, NULL, @fbsql_error($this->connection)); } // }}} // {{{ autoCommit() /** * Define whether database changes done on the database be automatically * committed. This function may also implicitly start or end a transaction. * * @param boolean $auto_commit flag that indicates whether the database * changes should be committed right after * executing every query statement. If this * argument is 0 a transaction implicitly * started. Otherwise, if a transaction is * in progress it is ended by committing any * database changes that were pending. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function autoCommit($auto_commit) { $this->debug("AutoCommit: ".($auto_commit ? "On" : "Off")); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Auto-commit transactions: transactions are not in use'); } if (((!$this->auto_commit) == (!$auto_commit))) { return (MDB_OK); } if ($this->connection) { if ($auto_commit) { $result = $this->query('COMMIT;'); if (MDB::isError($result)) { return $result; } $result = $this->query('SET COMMIT TRUE;'); if (MDB::isError($result)) { return $result; } } else { $result = $this->query('SET COMMIT FALSE;'); if (MDB::isError($result)) { return $result; } } } $this->auto_commit = $auto_commit; return ($this->_registerTransactionShutdown($auto_commit)); } // }}} // {{{ commit() /** * Commit the database changes done during a transaction that is in * progress. This function may only be called when auto-committing is * disabled, otherwise it will fail. Therefore, a new transaction is * implicitly started after committing the pending changes. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function commit() { $this->debug("Commit Transaction"); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Commit transactions: transactions are not in use'); } if ($this->auto_commit) { return $this->raiseError(MDB_ERROR, '', '', 'Commit transactions: transaction changes are being auto commited'); } return ($this->query('COMMIT;')); } // }}} // {{{ rollback() /** * Cancel any database changes done during a transaction that is in * progress. This function may only be called when auto-committing is * disabled, otherwise it will fail. Therefore, a new transaction is * implicitly started after canceling the pending changes. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function rollback() { $this->debug("Rollback Transaction"); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Rollback transactions: transactions are not in use'); } if ($this->auto_commit) { return $this->raiseError(MDB_ERROR, '', '', 'Rollback transactions: transactions can not be rolled back when changes are auto commited'); } return ($this->query('ROLLBACK;')); } // }}} // {{{ connect() /** * Connect to the database * * @return TRUE on success, MDB_Error on failure **/ function connect() { $port = (isset($this->port) ? $this->port : ''); if ($this->connection != 0) { if (!strcmp($this->connected_host, $this->host) && !strcmp($this->connected_user, $this->user) && !strcmp($this->connected_password, $this->password) && !strcmp($this->connected_port, $port) && $this->opened_persistent == $this->options['persistent']) { return (MDB_OK); } fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; } $this->fixed_float = 30; $function = ($this->options['persistent'] ? 'fbsql_pconnect' : 'fbsql_connect'); if (!function_exists($function)) { return ($this->raiseError(MDB_ERROR_UNSUPPORTED)); } @ini_set('track_errors', TRUE); $this->connection = @$function( $this->host.(!strcmp($port,'') ? '' : ':'.$port), $this->user, $this->password); @ini_restore('track_errors'); if ($this->connection <= 0) { return ($this->raiseError(MDB_ERROR_CONNECT_FAILED, '', '', $php_errormsg)); } if (isset($this->options['fixedfloat'])) { $this->fixed_float = $this->options['fixedfloat']; } else { if (($result = fbsql_query('SELECT VERSION()', $this->connection))) { $version = explode('.',fbsql_result($result,0,0)); $major = intval($version[0]); $minor = intval($version[1]); $revision = intval($version[2]); if ($major > 3 || ($major == 3 && $minor >= 23 && ($minor > 23 || $revision >= 6))) { $this->fixed_float = 0; } fbsql_free_result($result); } } if (isset($this->supported['Transactions']) && !$this->auto_commit) { if (!fbsql_query('SET AUTOCOMMIT = 0', $this->connection)) { fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; return ($this->raiseError()); } $this->_registerTransactionShutdown(0); } $this->connected_host = $this->host; $this->connected_user = $this->user; $this->connected_password = $this->password; $this->connected_port = $port; $this->opened_persistent = $this->options['persistent']; return (MDB_OK); } // }}} // {{{ _close() /** * all the RDBMS specific things needed close a DB connection * * @return boolean * @access private **/ function _close() { if ($this->connection != 0) { if (isset($this->supported['Transactions']) && !$this->auto_commit) { $result = $this->autoCommit(TRUE); } fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; if (isset($result) && MDB::isError($result)) { return $result; } global $_MDB_databases; $_MDB_databases[$this->database] = ''; return TRUE; } return FALSE; } // }}} // {{{ query() /** * Send a query to the database and return any results * * @access public * * @param string $query the SQL query * @param array $types array that contains the types of the columns in * the result set * * @return mixed a result handle or MDB_OK on success, a MDB error on failure */ function query($query, $types = NULL) { $this->debug("Query: $query"); $ismanip = MDB::isManip($query); $this->last_query = $query; $first = $this->first_selected_row; $limit = $this->selected_row_limit; $this->first_selected_row = $this->selected_row_limit = 0; $result = $this->connect(); if (MDB::isError($result)) { return $result; } if($limit > 0) { if ($ismanip) { $query .= " LIMIT $limit"; } else { $query .= " LIMIT $first,$limit"; } } if ($this->database_name != '') { if(!fbsql_select_db($this->database_name, $this->connection)) { return $this->fbsqlRaiseError(); } } if ($result = fbsql_query($query, $this->connection)) { if ($ismanip) { $this->affected_rows = fbsql_affected_rows($this->connection); return MDB_OK; } else { $this->highest_fetched_row[$result] = -1; if ($types != NULL) { if (!is_array($types)) { $types = array($types); } if (MDB::isError($err = $this->setResultTypes($result, $types))) { $this->freeResult($result); return $err; } } return $result; } } return $this->fbsqlRaiseError(); } // }}} // {{{ subSelect() /** * simple subselect emulation for FrontBase * * @access public * * @param string $query the SQL query for the subselect that may only * return a column * @param string $quote determines if the data needs to be quoted before * being returned * * @return string the query */ function subSelect($query, $quote = FALSE) { if($this->supported['SubSelects'] == 1) { return($query); } $col = $this->queryCol($query); if (MDB::isError($col)) { return $col; } if(!is_array($col) || count($col) == 0) { return 'NULL'; } if($quote) { for($i = 0, $j = count($col); $i < $j; ++$i) { $col[$i] = $this->getTextValue($col[$i]); } } return(implode(', ', $col)); } // }}} // {{{ replace() /** * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT * query, except that if there is already a row in the table with the same * key field values, the REPLACE query just updates its values instead of * inserting a new row. * * The REPLACE type of query does not make part of the SQL standards. Since * practically only MySQL implements it natively, this type of query is * emulated through this method for other DBMS using standard types of * queries inside a transaction to assure the atomicity of the operation. * * @access public * * @param string $table name of the table on which the REPLACE query will * be executed. * @param array $fields associative array that describes the fields and the * values that will be inserted or updated in the specified table. The * indexes of the array are the names of all the fields of the table. The * values of the array are also associative arrays that describe the * values and other properties of the table fields. * * Here follows a list of field properties that need to be specified: * * Value: * Value to be assigned to the specified field. This value may be * of specified in database independent type format as this * function can perform the necessary datatype conversions. * * Default: * this property is required unless the Null property * is set to 1. * * Type * Name of the type of the field. Currently, all types Metabase * are supported except for clob and blob. * * Default: text * * Null * Boolean property that indicates that the value for this field * should be set to NULL. * * The default value for fields missing in INSERT queries may be * specified the definition of a table. Often, the default value * is already NULL, but since the REPLACE may be emulated using * an UPDATE query, make sure that all fields of the table are * listed in this function argument array. * * Default: 0 * * Key * Boolean property that indicates that this field should be * handled as a primary key or at least as part of the compound * unique index of the table that will determine the row that will * updated if it exists or inserted a new row otherwise. * * This function will fail if no key field is specified or if the * value of a key field is set to NULL because fields that are * part of unique index they may not be NULL. * * Default: 0 * * @return mixed MDB_OK on success, a MDB error on failure */ function replace($table, $fields) { $count = count($fields); for($keys = 0, $query = $values = '',reset($fields), $field = 0; $field<$count; next($fields), $field++) { $name = key($fields); if ($field>0) { $query .= ','; $values .= ','; } $query .= $name; if (isset($fields[$name]['Null']) && $fields[$name]['Null']) { $value = 'NULL'; } else { if (!isset($fields[$name]['Value'])) { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'no value for field "'.$name.'" specified'); } switch(isset($fields[$name]['Type']) ? $fields[$name]['Type'] : 'text') { case 'text': $value = $this->getTextValue($fields[$name]['Value']); break; case 'boolean': $value = $this->getBooleanValue($fields[$name]['Value']); break; case 'integer': $value = strval($fields[$name]['Value']); break; case 'decimal': $value = $this->getDecimalValue($fields[$name]['Value']); break; case 'float': $value = $this->getFloatValue($fields[$name]['Value']); break; case 'date': $value = $this->getDateValue($fields[$name]['Value']); break; case 'time': $value = $this->getTimeValue($fields[$name]['Value']); break; case 'timestamp': $value = $this->getTimestampValue($fields[$name]['Value']); break; default: return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'no supported type for field "'.$name.'" specified'); } } $values .= $value; if (isset($fields[$name]['Key']) && $fields[$name]['Key']) { if ($value == 'NULL') { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'key values may not be NULL'); } $keys++; } } if ($keys == 0) { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'not specified which fields are keys'); } return ($this->query("REPLACE INTO $table ($query) VALUES ($values)")); } // }}} // {{{ getColumnNames() /** * Retrieve the names of columns returned by the DBMS in a query result. * * @param resource $result result identifier * @return mixed an associative array variable * that will hold 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 rows. * * a MDB error on failure * @access public */ function getColumnNames($result) { $result_value = intval($result); if (!isset($this->highest_fetched_row[$result_value])) { return $this->raiseError(MDB_ERROR_INVALID, '', '', 'Get column names: it was specified an inexisting result set'); } if (!isset($this->columns[$result_value])) { $this->columns[$result_value] = array(); $columns = fbsql_num_fields($result); for($column = 0; $column < $columns; $column++) { $this->columns[$result_value][strtolower(fbsql_field_name($result, $column))] = $column; } } return ($this->columns[$result_value]); } // }}} // {{{ numCols() /** * Count the number of columns returned by the DBMS in a query result. * * @param resource $result result identifier * @access public * @return mixed integer value with the number of columns, a MDB error * on failure */ function numCols($result) { if (!isset($this->highest_fetched_row[intval($result)])) { return $this->raiseError(MDB_ERROR_INVALID, '', '', 'numCols: it was specified an inexisting result set'); } return (fbsql_num_fields($result)); } // }}} // {{{ endOfResult() /** * check if the end of the result set has been reached * * @param resource $result result identifier * @return mixed TRUE or FALSE on sucess, a MDB error on failure * @access public */ function endOfResult($result) { if (!isset($this->highest_fetched_row[$result])) { return $this->raiseError(MDB_ERROR, '', '', 'End of result: attempted to check the end of an unknown result'); } return ($this->highest_fetched_row[$result] >= $this->numRows($result)-1); } // }}} // {{{ fetch() /** * fetch value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed string on success, a MDB error on failure * @access public */ function fetch($result, $row, $field) { $this->highest_fetched_row[$result] = max($this->highest_fetched_row[$result], $row); $res = @fbsql_result($result, $row, $field); if ($res === FALSE && $res != NULL) { return $this->fbsqlRaiseError($errno); } return ($res); } // }}} // {{{ fetchClob() /** * fetch a clob value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed content of the specified data cell, a MDB error on failure, * a MDB error on failure * @access public */ function fetchClob($result, $row, $field) { return ($this->fetchLob($result, $row, $field)); } // }}} // {{{ fetchBlob() /** * fetch a blob value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed content of the specified data cell, a MDB error on failure * @access public */ function fetchBlob($result, $row, $field) { return ($this->fetchLob($result, $row, $field)); } // }}} // {{{ convertResult() /** * convert a value to a RDBMS indepdenant MDB type * * @param mixed $value value to be converted * @param int $type constant that specifies which type to convert to * @return mixed converted value * @access public */ function convertResult($value, $type) { switch($type) { case MDB_TYPE_BOOLEAN: return (strcmp($value, 'Y') ? 0 : 1); case MDB_TYPE_DECIMAL: return (sprintf('%.'.$this->decimal_places.'f', doubleval($value)/$this->decimal_factor)); case MDB_TYPE_FLOAT: return (doubleval($value)); case MDB_TYPE_DATE: return ($value); case MDB_TYPE_TIME: return ($value); case MDB_TYPE_TIMESTAMP: return ($value); default: return ($this->_baseConvertResult($value, $type)); } } // }}} // {{{ numRows() /** * returns the number of rows in a result object * * @param ressource $result a valid result ressouce pointer * @return mixed MDB_Error or the number of rows * @access public */ function numRows($result) { return (fbsql_num_rows($result)); } // }}} // {{{ freeResult() /** * Free the internal resources associated with $result. * * @param $result result identifier * @return boolean TRUE on success, FALSE if $result is invalid * @access public */ function freeResult($result) { if(isset($this->highest_fetched_row[$result])) { unset($this->highest_fetched_row[$result]); } if(isset($this->columns[$result])) { unset($this->columns[$result]); } if(isset($this->result_types[$result])) { unset($this->result_types[$result]); } return (fbsql_free_result($result)); } // }}} // {{{ getIntegerDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * unsigned * Boolean flag that indicates whether the field * should be declared as unsigned integer if * possible. * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getIntegerDeclaration($name, $field) { return ("$name INT". (isset($field['unsigned']) ? ' UNSIGNED' : ''). (isset($field['default']) ? ' DEFAULT '.$field['default'] : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getClobDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an character * large object type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the * properties of the field being declared as array * indexes. Currently, the types of supported field * properties are as follows: * * length * Integer value that determines the maximum length * of the large object field. If this argument is * missing the field should be declared to have the * longest length allowed by the DBMS. * * notnull * Boolean flag that indicates whether this field * is constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getClobDeclaration($name, $field) { if (isset($field['length'])) { $length = $field['length']; $type = "VAECHAR($length)"; } else { $type = "VAECHAR(32768)"; } return ("$name $type". (isset($field['notnull']) ? ' NOT NULL' : '')); } // }}} // {{{ getBlobDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an binary large * object type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * length * Integer value that determines the maximum length * of the large object field. If this argument is * missing the field should be declared to have the * longest length allowed by the DBMS. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getBlobDeclaration($name, $field) { if (isset($field['length'])) { $length = $field['length']; $type = "BLOB($length)"; } else { $type = "BLOB(32768)"; } return ("$name $type". (isset($field['notnull']) ? ' NOT NULL' : '')); } // }}} // {{{ getDateDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an date type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field properties * are as follows: * * default * Date value to be used as default for this field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getDateDeclaration($name, $field) { return ("$name DATE". (isset($field['default']) ? " DEFAULT DATE'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getTimestampDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an timestamp * type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Time stamp value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getTimestampDeclaration($name, $field) { return ("$name DATETIME". (isset($field['default']) ? " DEFAULT TIMESTAMP'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getTimeDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an time type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Time value to be used as default for this field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getTimeDeclaration($name, $field) { return ("$name TIME". (isset($field['default']) ? " DEFAULT TIME'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getFloatDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an float type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getFloatDeclaration($name, $field) { if (isset($this->options['fixedfloat'])) { $this->fixed_float = $this->options['fixedfloat']; } else { if ($this->connection == 0) { // XXX needs more checking $this->connect(); } } return ("$name DOUBLE". ($this->fixed_float ? '('.($this->fixed_float + 2).','.$this->fixed_float.')' : ''). (isset($field['default']) ? ' DEFAULT '.$this->getFloatValue($field['default']) : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getDecimalDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an decimal type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getDecimalDeclaration($name, $field) { return ("$name REAL". (isset($field['default']) ? ' DEFAULT '.$this->getDecimalValue($field['default']) : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getClobValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param resource $prepared_query query handle from prepare() * @param $parameter * @param $clob * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getClobValue($prepared_query, $parameter, $clob) { $value = "'"; while(!$this->endOfLob($clob)) { if (MDB::isError($result = $this->readLob($clob, $data, $this->options['lob_buffer_length']))) { return $result; } $value .= $this->_quote($data); } $value .= "'"; return ($value); } // }}} // {{{ freeClobValue() /** * free a character large object * * @param resource $prepared_query query handle from prepare() * @param string $clob * @return MDB_OK * @access public */ function freeClobValue($prepared_query, $clob) { unset($this->lobs[$clob]); return (MDB_OK); } // }}} // {{{ getBlobValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param resource $prepared_query query handle from prepare() * @param $parameter * @param $blob * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getBlobValue($prepared_query, $parameter, $blob) { $value = "'"; while(!$this->endOfLob($blob)) { if (MDB::isError($result = $this->readLob($blob, $data, $this->options['lob_buffer_length']))) { return $result; } $value .= addslashes($data); } $value .= "'"; return ($value); } // }}} // {{{ freeBlobValue() /** * free a binary large object * * @param resource $prepared_query query handle from prepare() * @param string $blob * @return MDB_OK * @access public */ function freeBlobValue($prepared_query, $blob) { unset($this->lobs[$blob]); return (MDB_OK); } // }}} // {{{ getFloatValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param string $value text string value that is intended to be converted. * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getFloatValue($value) { return (!strcmp($value, 'NULL') ? 'NULL' : "$value"); } // }}} // {{{ getDecimalValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param string $value text string value that is intended to be converted. * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getDecimalValue($value) { return (!strcmp($value, 'NULL') ? 'NULL' : strval(round(doubleval($value)*$this->decimal_factor))); } // }}} // {{{ nextId() /** * 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 * not exists * * @return mixed MDB_Error or id * @access public */ function nextId($seq_name, $ondemand = TRUE) { $sequence_name = $this->getSequenceName($seq_name); $result = $this->query("INSERT INTO $sequence_name (sequence) VALUES (NULL);"); if ($ondemand && MDB::isError($result) && $result->getCode() == MDB_ERROR_NOSUCHTABLE) { $result = $this->createSequence($seq_name, 2); // Since we are create the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 if (MDB::isError($result)) { return $this->raiseError(MDB_ERROR, '', '', 'Next ID: on demand sequence could not be created'); } else { // First ID of a newly created sequence is 1 return 1; } } $value = intval(fbsql_insert_id()); $res = $this->query("DELETE FROM $sequence_name WHERE sequence < $value;"); if (MDB::isError($res)) { $this->warnings[] = 'Next ID: could not delete previous sequence table values'; } return ($value); } // }}} // {{{ currId() /** * returns the current id of a sequence * * @param string $seq_name name of the sequence * @return mixed MDB_Error or id * @access public */ function currId($seq_name) { $sequence_name = $this->getSequenceName($seq_name); $result = $this->query("SELECT MAX(sequence) FROM $sequence_name;", 'integer'); if (MDB::isError($result)) { return $result; } return ($this->fetchOne($result)); } // }}} // {{{ fetchInto() /** * Fetch a row and insert the data into an existing array. * * @param resource $result result identifier * @param int $fetchmode how the array data should be indexed * @param int $rownum the row number to fetch * @return int data array on success, a MDB error on failure * @access public */ function fetchInto($result, $fetchmode = MDB_FETCHMODE_DEFAULT, $rownum = NULL) { if ($rownum == NULL) { ++$this->highest_fetched_row[$result]; } else { if (!@fbsql_data_seek($result, $rownum)) { return NULL; } $this->highest_fetched_row[$result] = max($this->highest_fetched_row[$result], $rownum); } if ($fetchmode == MDB_FETCHMODE_DEFAULT) { $fetchmode = $this->fetchmode; } if ($fetchmode & MDB_FETCHMODE_ASSOC) { $array = @fbsql_fetch_array($result, FBSQL_ASSOC); } else { $array = @fbsql_fetch_row($result); } if (!$array) { $errno = @fbsql_errno($this->connection); if (!$errno) { if($this->options['autofree']) { $this->freeResult($result); } return NULL; } return $this->fbsqlRaiseError($errno); } if (isset($this->result_types[$result])) { $array = $this->convertResultRow($result, $array); } return ($array); } // }}} // {{{ nextResult() /** * Move the internal fbsql result pointer to the next available result * Currently not supported * * @param a valid result resource * @return true if a result is available otherwise return false * @access public */ function nextResult($result) { return FALSE; } // }}} // {{{ tableInfo() /** * returns meta data about the result set * * @param resource $result result identifier * @param mixed $mode depends on implementation * @return array an nested array, or a MDB error * @access public */ function tableInfo($result, $mode = NULL) { $count = 0; $id = 0; $res = array(); /* * depending on $mode, metadata returns the following values: * * - mode is false (default): * $result[]: * [0]['table'] table name * [0]['name'] field name * [0]['type'] field type * [0]['len'] field length * [0]['flags'] field flags * * - mode is MDB_TABLEINFO_ORDER * $result[]: * ['num_fields'] number of metadata records * [0]['table'] table name * [0]['name'] field name * [0]['type'] field type * [0]['len'] field length * [0]['flags'] field flags * ['order'][field name] index of field named "field name" * The last one is used, if you have a field name, but no index. * Test: if (isset($result['meta']['myfield'])) { ... * * - mode is MDB_TABLEINFO_ORDERTABLE * the same as above. but additionally * ['ordertable'][table name][field name] index of field * named 'field name' * * this is, because if you have fields from different * tables with the same field name * they override each * other with MDB_TABLEINFO_ORDER * * you can combine MDB_TABLEINFO_ORDER and * MDB_TABLEINFO_ORDERTABLE with MDB_TABLEINFO_ORDER | * MDB_TABLEINFO_ORDERTABLE * or with MDB_TABLEINFO_FULL */ // if $result is a string, then we want information about a // table without a resultset if (is_string($result)) { $id = @fbsql_list_fields($this->database_name, $result, $this->connection); if (empty($id)) { return $this->fbsqlRaiseError(); } } else { // else we want information about a resultset $id = $result; if (empty($id)) { return $this->fbsqlRaiseError(); } } $count = @fbsql_num_fields($id); // made this IF due to performance (one if is faster than $count if's) if (empty($mode)) { for ($i = 0; $i<$count; $i++) { $res[$i]['table'] = @fbsql_field_table ($id, $i); $res[$i]['name'] = @fbsql_field_name ($id, $i); $res[$i]['type'] = @fbsql_field_type ($id, $i); $res[$i]['len'] = @fbsql_field_len ($id, $i); $res[$i]['flags'] = @fbsql_field_flags ($id, $i); } } else { // full $res['num_fields'] = $count; for ($i = 0; $i<$count; $i++) { $res[$i]['table'] = @fbsql_field_table ($id, $i); $res[$i]['name'] = @fbsql_field_name ($id, $i); $res[$i]['type'] = @fbsql_field_type ($id, $i); $res[$i]['len'] = @fbsql_field_len ($id, $i); $res[$i]['flags'] = @fbsql_field_flags ($id, $i); if ($mode & MDB_TABLEINFO_ORDER) { $res['order'][$res[$i]['name']] = $i; } if ($mode & MDB_TABLEINFO_ORDERTABLE) { $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; } } } // free the result only if we were called on a table if (is_string($result)) { @fbsql_free_result($id); } return $res; } } ?> Index: pear/MDB/MDB/Modules/Manager/fbsql.php +++ pear/MDB/MDB/Modules/Manager/fbsql.php <?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1998-2002 Manuel Lemos, Tomas V.V.Cox, | // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann | // | All rights reserved. | // +----------------------------------------------------------------------+ // | MDB 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 | // | are met: | // | | // | 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: Lukas Smith <smith@dybnet.de> | // +----------------------------------------------------------------------+ // // $Id: fbsql.php,v 1.1 2002/12/26 21:38:05 fmk Exp $ // if(!defined('MDB_MANAGER_FBSQL_INCLUDED')) { define('MDB_MANAGER_FBSQL_INCLUDED', 1); require_once 'MDB/Modules/Manager/Common.php'; /** * MDB FrontBase driver for the management modules * * @package MDB * @category Database * @access private * @author Lukas Smith <smith@dybnet.de> * @author Frank M. Kromann <frank@kromann.info> */ class MDB_Manager_fbsql extends MDB_Manager_Common { // {{{ properties var $verified_table_types = array(); // }}} // {{{ _verifyTransactionalTableType() /** * verify that chosen transactional table hanlder is available in the database * * @param object $dbs database object that is extended by this class * @param string $table_type name of the table handler * @return mixed MDB_OK on success, a MDB error on failure * @access private */ function _verifyTransactionalTableType(&$db, $table_type) { switch(strtoupper($table_type)) { case 'BERKELEYDB': case 'BDB': $check = 'have_bdb'; break; case 'INNODB': $check = 'have_innobase'; break; case 'GEMINI': $check = 'have_gemini'; break; case 'HEAP': case 'ISAM': case 'MERGE': case 'MRG_MYISAM': case 'MYISAM': case '': return(MDB_OK); default: return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table', $table_type.' is not a supported table type')); } if(!$db->connect()) { return($db->raiseError()); } if(isset($this->verified_table_types[$table_type]) && $this->verified_table_types[$table_type] == $db->connection) { return(MDB_OK); } if(MDB::isError($has = $db->queryAll("SHOW VARIABLES LIKE '$check'", NULL, MDB_FETCHMODE_ORDERED))) { return($db->raiseError()); } if(count($has) == 0) { return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table',"could not tell if ".$table_type.' is a supported table type')); } if(strcmp($has[0][1], 'YES')) { return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table', $table_type.' is not a supported table type by this FrontBase database server')); } $this->verified_table_types[$table_type] = $db->connection; return (MDB_OK); } // }}} // {{{ createDatabase() /** * create a new database * * @param object $dbs database object that is extended by this class * @param string $name name of the database that should be created * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createDatabase(&$db, $name) { if (MDB::isError($result = $db->connect())) { return $result; } if (!fbsql_create_db($name, $db->connection)) { return $db->fbsqlRaiseError(); } return (MDB_OK); } // }}} // {{{ dropDatabase() /** * drop an existing database * * @param object $dbs database object that is extended by this class * @param string $name name of the database that should be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropDatabase(&$db, $name) { if (MDB::isError($result = $db->connect())) { return $result; } if (!fbsql_drop_db($name, $db->connection)) { return $db->fbsqlRaiseError(); } return (MDB_OK); } // }}} // {{{ createTable() /** * create a new table * * @param object $dbs database object that is extended by this class * @param string $name Name of the database that should be created * @param array $fields Associative array that contains the definition of each field of the new table * The indexes of the array entries are the names of the fields of the table an * the array entry values are associative arrays like those that are meant to be * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( * * 'id' => array( * 'type' => 'integer', * 'unsigned' => 1 * 'notnull' => 1 * 'default' => 0 * ), * 'name' => array( * 'type' => 'text', * 'length' => 12 * ), * 'password' => array( * 'type' => 'text', * 'length' => 12 * ) * ); * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createTable(&$db, $name, $fields) { if (!isset($name) || !strcmp($name, '')) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'no valid table name specified'); } if (count($fields) == 0) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'no fields specified for table "'.$name.'"'); } if(MDB::isError($verify = $this->_verifyTransactionalTableType($db, $db->default_table_type))) { return($verify); } if (MDB::isError($query_fields = $db->getFieldDeclarationList($fields))) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'unkown error'); } if (isset($db->supported['Transactions']) && $db->default_table_type=='BDB') { $query_fields .= ', dummy_primary_key INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (dummy_primary_key)'; } $query = "CREATE TABLE $name ($query_fields)".(strlen($db->default_table_type) ? ' TYPE='.$db->default_table_type : ''); return ($db->query($query)); } // }}} // {{{ alterTable() /** * alter an existing table * * @param object $dbs database object that is extended by this class * @param string $name name of the table that is intended to be changed. * @param array $changes associative array that contains the details of each type * of change that is intended to be performed. The types of * changes that are currently supported are defined as follows: * * name * * New name for the table. * * AddedFields * * Associative array with the names of fields to be added as * indexes of the array. The value of each entry of the array * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. * * Additionally, there should be an entry named Declaration that * is expected to contain the portion of the field declaration already * in DBMS specific SQL code as it is used in the CREATE TABLE statement. * * RemovedFields * * Associative array with the names of fields to be removed as indexes * of the array. Currently the values assigned to each entry are ignored. * An empty array should be used for future compatibility. * * RenamedFields * * Associative array with the names of fields to be renamed as indexes * of the array. The value of each entry of the array should be set to * another associative array with the entry named name with the new * field name and the entry named Declaration that is expected to contain * the portion of the field declaration already in DBMS specific SQL code * as it is used in the CREATE TABLE statement. * * ChangedFields * * Associative array with the names of the fields to be changed as indexes * of the array. Keep in mind that if it is intended to change either the * name of a field and any other properties, the ChangedFields array entries * should have the new names of the fields as array indexes. * * The value of each entry of the array should be set to another associative * array with the properties of the fields to that are meant to be changed as * array entries. These entries should be assigned to the new values of the * respective properties. The properties of the fields should be the same * as defined by the Metabase parser. * * If the default property is meant to be added, removed or changed, there * should also be an entry with index ChangedDefault assigned to 1. Similarly, * if the notnull constraint is to be added or removed, there should also be * an entry with index ChangedNotNull assigned to 1. * * Additionally, there should be an entry named Declaration that is expected * to contain the portion of the field changed declaration already in DBMS * specific SQL code as it is used in the CREATE TABLE statement. * Example * array( * 'name' => 'userlist', * 'AddedFields' => array( * 'quota' => array( * 'type' => 'integer', * 'unsigned' => 1 * 'Declaration' => 'quota INT' * ) * ), * 'RemovedFields' => array( * 'file_limit' => array(), * 'time_limit' => array() * ), * 'ChangedFields' => array( * 'gender' => array( * 'default' => 'M', * 'ChangeDefault' => 1, * 'Declaration' => "gender CHAR(1) DEFAULT 'M'" * ) * ), * 'RenamedFields' => array( * 'sex' => array( * 'name' => 'gender', * 'Declaration' => "gender CHAR(1) DEFAULT 'M'" * ) * ) * ) * * @param boolean $check indicates whether the function should just check if the DBMS driver * can perform the requested table alterations if the value is true or * actually perform them otherwise. * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function alterTable(&$db, $name, $changes, $check) { if ($check) { for($change = 0,reset($changes); $change < count($changes); next($changes), $change++) { switch(key($changes)) { case 'AddedFields': case 'RemovedFields': case 'ChangedFields': case 'RenamedFields': case 'name': break; default: return $db->raiseError(MDB_ERROR_CANNOT_ALTER, '', '', 'Alter table: change type "'.Key($changes).'" not yet supported'); } } return (MDB_OK); } else { $query = (isset($changes['name']) ? 'RENAME AS '.$changes['name'] : ''); if (isset($changes['AddedFields'])) { $fields = $changes['AddedFields']; for($field = 0, reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $query .= 'ADD '.$fields[key($fields)]['Declaration']; } } if (isset($changes['RemovedFields'])) { $fields = $changes['RemovedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $query .= 'DROP '.key($fields); } } $renamed_fields = array(); if (isset($changes['RenamedFields'])) { $fields = $changes['RenamedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { $renamed_fields[$fields[key($fields)]['name']] = key($fields); } } if (isset($changes['ChangedFields'])) { $fields = $changes['ChangedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } if (isset($renamed_fields[key($fields)])) { $field_name = $renamed_fields[key($fields)]; unset($renamed_fields[key($fields)]); } else { $field_name = key($fields); } $query .= "CHANGE $field_name ".$fields[key($fields)]['Declaration']; } } if (count($renamed_fields)) { for($field = 0,reset($renamed_fields); $field<count($renamed_fields); next($renamed_fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $old_field_name = $renamed_fields[Key($renamed_fields)]; $query .= "CHANGE $old_field_name ".$changes['RenamedFields'][$old_field_name]['Declaration']; } } return ($db->query("ALTER TABLE $name $query")); } } // }}} // {{{ listDatabases() /** * list all databases * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listDatabases(&$db) { $result = $db->queryCol('SHOW DATABASES'); if(MDB::isError($result)) { return $result; } return ($result); } // }}} // {{{ listUsers() /** * list all users * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listUsers(&$db) { $result = $db->queryCol('SELECT DISTINCT USER FROM USER'); if(MDB::isError($result)) { return $result; } return ($result); } // }}} // {{{ listTables() /** * list all tables in the current database * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listTables(&$db) { $table_names = $db->queryCol('SHOW TABLES'); if(MDB::isError($table_names)) { return $table_names; } for($i = 0, $j = count($table_names), $tables = array(); $i < $j; ++$i) { if (!$db->_isSequenceName($table_names[$i])) $tables[] = $table_names[$i]; } return ($tables); } // }}} // {{{ listTableFields() /** * list all fields in a tables in the current database * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function listTableFields(&$db, $table) { $result = $db->query("SHOW COLUMNS FROM $table"); if(MDB::isError($result)) { return $result; } $columns = $db->getColumnNames($result); if(MDB::isError($columns)) { $db->freeResult($columns); return $columns; } if(!isset($columns['field'])) { $db->freeResult($result); return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'List table fields: show columns does not return the table field names'); } $field_column = $columns['field']; for($fields = array(), $field = 0; !$db->endOfResult($result); ++$field) { $field_name = $db->fetch($result, $field, $field_column); if ($field_name != $db->dummy_primary_key) $fields[] = $field_name; } $db->freeResult($result); return ($fields); } // }}} // {{{ getTableFieldDefinition() /** * get the stucture of a field into an array * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $field_name name of field that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function getTableFieldDefinition(&$db, $table, $field_name) { if ($field_name == $db->dummy_primary_key) { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definiton: '.$db->dummy_primary_key.' is an hidden column'); } $result = $db->query("SHOW COLUMNS FROM $table"); if(MDB::isError($result)) { return $result; } $columns = $db->getColumnNames($result); if(MDB::isError($columns)) { $db->freeResult($columns); return $columns; } if (!isset($columns[$column = 'field']) || !isset($columns[$column = 'type'])) { $db->freeResult($result); return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definition: show columns does not return the column '.$column); } $field_column = $columns['field']; $type_column = $columns['type']; while (is_array($row = $db->fetchInto($result))) { if ($field_name == $row[$field_column]) { $db_type = strtolower($row[$type_column]); $db_type = strtok($db_type, '(), '); if ($db_type == 'national') { $db_type = strtok('(), '); } $length = strtok('(), '); $decimal = strtok('(), '); $type = array(); switch($db_type) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'integer': case 'bigint': $type[0] = 'integer'; if($length == '1') { $type[1] = 'boolean'; if (preg_match('/^[is|has]/', $field_name)) { $type = array_reverse($type); } } break; case 'tinytext': case 'mediumtext': case 'longtext': case 'text': case 'char': case 'varchar': $type[0] = 'text'; if($decimal == 'binary') { $type[1] = 'blob'; } elseif($length == '1') { $type[1] = 'boolean'; if (preg_match('/[is|has]/', $field_name)) { $type = array_reverse($type); } } elseif(strstr($db_type, 'text')) $type[1] = 'clob'; break; case 'enum': preg_match_all('/\'.+\'/U',$row[$type_column], $matches); $length = 0; if(is_array($matches)) { foreach($matches[0] as $value) { $length = max($length, strlen($value)-2); } } unset($decimal); case 'set': $type[0] = 'text'; $type[1] = 'integer'; break; case 'date': $type[0] = 'date'; break; case 'datetime': case 'timestamp': $type[0] = 'timestamp'; break; case 'time': $type[0] = 'time'; break; case 'float': case 'double': case 'real': $type[0] = 'float'; break; case 'decimal': case 'numeric': $type[0] = 'decimal'; break; case 'tinyblob': case 'mediumblob': case 'longblob': case 'blob': $type[0] = 'blob'; $type[1] = 'text'; break; case 'year': $type[0] = 'integer'; $type[1] = 'date'; break; default: return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'List table fields: unknown database attribute type'); } unset($notnull); if (isset($columns['null']) && $row[$columns['null']] != 'YES') { $notnull = 1; } unset($default); if (isset($columns['default']) && isset($row[$columns['default']])) { $default = $row[$columns['default']]; } $definition = array(); for($field_choices = array(), $datatype = 0; $datatype < count($type); $datatype++) { $field_choices[$datatype] = array('type' => $type[$datatype]); if(isset($notnull)) { $field_choices[$datatype]['notnull'] = 1; } if(isset($default)) { $field_choices[$datatype]['default'] = $default; } if($type[$datatype] != 'boolean' && $type[$datatype] != 'time' && $type[$datatype] != 'date' && $type[$datatype] != 'timestamp') { if(strlen($length)) { $field_choices[$datatype]['length'] = $length; } } } $definition[0] = $field_choices; if (isset($columns['extra']) && isset($row[$columns['extra']]) && $row[$columns['extra']] == 'auto_increment') { $implicit_sequence = array(); $implicit_sequence['on'] = array(); $implicit_sequence['on']['table'] = $table; $implicit_sequence['on']['field'] = $field_name; $definition[1]['name'] = $table.'_'.$field_name; $definition[1]['definition'] = $implicit_sequence; } if (isset($columns['key']) && isset($row[$columns['key']]) && $row[$columns['key']] == 'PRI') { // check that its not just a unique field if(MDB::isError($indexes = $db->queryAll("SHOW INDEX FROM $table", NULL, MDB_FETCHMODE_ASSOC))) { return($indexes); } $is_primary = FALSE; foreach($indexes as $index) { if ($index['Key_name'] == 'PRIMARY' && $index['Column_name'] == $field_name) { $is_primary = TRUE; break; } } if($is_primary) { $implicit_index = array(); $implicit_index['unique'] = 1; $implicit_index['FIELDS'][$field_name] = ''; $definition[2]['name'] = $field_name; $definition[2]['definition'] = $implicit_index; } } $db->freeResult($result); return ($definition); } } if(!$db->options['autofree']) { $db->freeResult($result); } if(MDB::isError($row)) { return($row); } return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definition: it was not specified an existing table column'); } // }}} // {{{ createIndex() /** * get the stucture of a field into an array * * @param object $dbs database object that is extended by this class * @param string $table name of the table on which the index is to be created * @param string $name name of the index to be created * @param array $definition associative array that defines properties of the index to be created. * Currently, only one property named FIELDS is supported. This property * is also an associative with the names of the index fields as array * indexes. Each entry of this array is set to another type of associative * array that specifies properties of the index that are specific to * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either * ascending or descending. * * Not all DBMS support index sorting direction configuration. The DBMS * drivers of those that do not support it ignore this property. Use the * function support() to determine whether the DBMS driver can manage indexes. * Example * array( * 'FIELDS' => array( * 'user_name' => array( * 'sorting' => 'ascending' * ), * 'last_login' => array() * ) * ) * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createIndex(&$db, $table, $name, $definition) { $query = "ALTER TABLE $table ADD ".(isset($definition['unique']) ? 'UNIQUE' : 'INDEX')." $name ("; for($field = 0, reset($definition['FIELDS']); $field < count($definition['FIELDS']); $field++, next($definition['FIELDS'])) { if ($field > 0) { $query .= ','; } $query .= key($definition['FIELDS']); } $query .= ')'; return ($db->query($query)); } // }}} // {{{ dropIndex() /** * drop existing index * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $name name of the index to be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropIndex(&$db, $table, $name) { return ($db->query("ALTER TABLE $table DROP INDEX $name")); } // }}} // {{{ listTableIndexes() /** * list all indexes in a table * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function listTableIndexes(&$db, $table) { if(MDB::isError($result = $db->query("SHOW INDEX FROM $table"))) { return($result); } $indexes_all = $db->fetchCol($result, 'Key_name'); for($found = $indexes = array(), $index = 0, $indexes_all_cnt = count($indexes_all); $index < $indexes_all_cnt; $index++) { if ($indexes_all[$index] != 'PRIMARY' && !isset($found[$indexes_all[$index]])) { $indexes[] = $indexes_all[$index]; $found[$indexes_all[$index]] = 1; } } $db->freeResult($result); return($indexes); } // }}} // {{{ getTableIndexDefinition() /** * get the stucture of an index into an array * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $index_name name of index that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function getTableIndexDefinition(&$db, $table, $index_name) { if($index_name == 'PRIMARY') { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table index definition: PRIMARY is an hidden index'); } if(MDB::isError($result = $db->query("SHOW INDEX FROM $table"))) { return($result); } $definition = array(); while (is_array($row = $db->fetchInto($result, MDB_FETCHMODE_ASSOC))) { $key_name = $row['Key_name']; if(!strcmp($index_name, $key_name)) { if(!$row['Non_unique']) { $definition[$index_name]['unique'] = 1; } $column_name = $row['Column_name']; $definition['FIELDS'][$column_name] = array(); if(isset($row['Collation'])) { $definition['FIELDS'][$column_name]['sorting'] = ($row['Collation'] == 'A' ? 'ascending' : 'descending'); } } } $db->freeResult($result); if (!isset($definition['FIELDS'])) { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table index definition: it was not specified an existing table index'); } return ($definition); } // }}} // {{{ createSequence() /** * create sequence * * @param object $dbs database object that is extended by this class * @param string $seq_name name of the sequence to be created * @param string $start start value of the sequence; default is 1 * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createSequence(&$db, $seq_name, $start) { $sequence_name = $db->getSequenceName($seq_name); $res = $db->query("CREATE TABLE $sequence_name (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence))"); if (MDB::isError($res)) { return $res; } if ($start == 1) { return MDB_OK; } $res = $db->query("INSERT INTO $sequence_name (sequence) VALUES (".($start-1).")"); if (!MDB::isError($res)) { return MDB_OK; } // Handle error $result = $db->query("DROP TABLE $sequence_name"); if (MDB::isError($result)) { return $db->raiseError(MDB_ERROR, '', '', 'Create sequence: could not drop inconsistent sequence table ('. $result->getMessage().' ('.$result->getUserinfo().'))'); } return $db->raiseError(MDB_ERROR, '', '', 'Create sequence: could not create sequence table ('. $res->getMessage().' ('.$res->getUserinfo().'))'); } // }}} // {{{ dropSequence() /** * drop existing sequence * * @param object $dbs database object that is extended by this class * @param string $seq_name name of the sequence to be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropSequence(&$db, $seq_name) { $sequence_name = $db->getSequenceName($seq_name); return ($db->query("DROP TABLE $sequence_name")); } // }}} // {{{ listSequences() /** * list all sequences in the current database * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listSequences(&$db) { $table_names = $db->queryCol('SHOW TABLES'); if(MDB::isError($table_names)) { return $table_names; } for($i = 0, $j = count($table_names), $sequences = array(); $i < $j; ++$i) { if ($sqn = $db->_isSequenceName($table_names[$i])) $sequences[] = $sqn; } return ($sequences); } // }}} } }; ?>
Index: pear/MDB/MAINTAINERS diff -u pear/MDB/MAINTAINERS:1.2 pear/MDB/MAINTAINERS:1.3 --- pear/MDB/MAINTAINERS:1.2 Sat Nov 23 18:50:47 2002 +++ pear/MDB/MAINTAINERS Thu Dec 26 16:38:04 2002 @@ -3,12 +3,12 @@ ibase : Paul Cooper <pgc@ucecom.com> (might write one) fbird : msql : -mssql : +mssql : Frank M. Kromann <frank@kromann.info> (is writting one) mysql : Lukas Smith <smith@backendmedia.com> oci8 : odbc : Pierre-Alain Joye <paj@pearfr.org> (is writting one) pgsql : Paul Cooper <pgc@ucecom.com> sybase : ifx : -fbsql : +fbsql : Frank M. Kromann <frank@kromann.info> (is writting one) dbase : Index: pear/MDB/package.xml diff -u pear/MDB/package.xml:1.38 pear/MDB/package.xml:1.39 --- pear/MDB/package.xml:1.38 Fri Dec 20 13:28:42 2002 +++ pear/MDB/package.xml Thu Dec 26 16:38:04 2002 @@ -78,6 +78,12 @@ <name>Manuel Lemos</name> <email>mlemos@acm.org</email> </maintainer> + <maintainer> + <user>fmk</user> + <role>contributor</role> + <name>Frank M. Kromann</name> + <email>frank@kromann.info</email> + </maintainer> </maintainers> <release> <version></version> @@ -91,6 +97,7 @@ <file role="doc">README</file> <dir name="MDB"> <file role="php">Common.php</file> + <file role="php">fbsql.php</file> <file role="php">mysql.php</file> <file role="php">pgsql.php</file> <file role="php">Date.php</file> @@ -103,6 +110,7 @@ <file role="php">LOB.php</file> <dir name="Manager"> <file role="php">Common.php</file> + <file role="php">fbsql.php</file> <file role="php">mysql.php</file> <file role="php">pgsql.php</file> </dir> Index: pear/MDB/MDB/fbsql.php +++ pear/MDB/MDB/fbsql.php <?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1998-2002 Manuel Lemos, Tomas V.V.Cox, | // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann | // | All rights reserved. | // +----------------------------------------------------------------------+ // | MDB 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 | // | are met: | // | | // | 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: Lukas Smith <smith@dybnet.de> | // +----------------------------------------------------------------------+ // // $Id: fbsql.php,v 1.1 2002/12/26 21:38:04 fmk Exp $ // require_once 'MDB/Common.php'; /** * MDB FrontBase driver * * @package MDB * @category Database * @author Lukas Smith <smith@dybnet.de> * @author Frank M. Kromann <frank@kromann.info> */ class MDB_fbsql extends MDB_Common { // {{{ properties var $connection = 0; var $connected_host; var $connected_user; var $connected_password; var $connected_port; var $opened_persistent = ''; var $escape_quotes = "\\"; var $decimal_factor = 1.0; var $highest_fetched_row = array(); var $columns = array(); // MySQL specific class variable var $default_table_type = ''; var $fixed_float = 0; var $dummy_primary_key = 'dummy_primary_key'; // }}} // {{{ constructor /** * Constructor */ function MDB_fbsql($dsninfo = NULL, $options = NULL) { if(MDB::isError($common_contructor = $this->MDB_common($dsninfo, $options))) { return $common_contructor; } $this->phptype = 'fbsql'; $this->dbsyntax = 'fbsql'; if (PEAR::isError(PEAR::loadExtension($this->phptype))) { return PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND, NULL, NULL, 'extension {$type} is not compiled into PHP', 'MDB_Error', TRUE); } $this->supported['Sequences'] = 1; $this->supported['Indexes'] = 1; $this->supported['AffectedRows'] = 1; $this->supported['Summaryfunctions'] = 1; $this->supported['OrderByText'] = 1; $this->supported['CurrId'] = 1; $this->supported['SelectRowRanges'] = 1; $this->supported['LOBs'] = 1; $this->supported['Replace'] = 0; $this->supported['SubSelects'] = 1; if(isset($this->options['UseTransactions']) && $this->options['UseTransactions']) { $this->supported['Transactions'] = 1; $this->default_table_type = 'BDB'; } else { $this->default_table_type = ''; } if(isset($this->options['DefaultTableType'])) { switch($this->default_table_type = strtoupper($this->options['DefaultTableType'])) { case 'BERKELEYDB': $this->default_table_type = 'BDB'; case 'BDB': case 'INNODB': case 'GEMINI': break; case 'HEAP': case 'ISAM': case 'MERGE': case 'MRG_MYISAM': case 'MYISAM': if(isset($this->supported['Transactions'])) { $this->warnings[] = $this->options['DefaultTableType'] .' is not a transaction-safe default table type'; } break; default: $this->warnings[] = $this->options['DefaultTableType'] .' is not a supported default table type'; } } $this->decimal_factor = pow(10.0, $this->decimal_places); $this->errorcode_map = array( 1004 => MDB_ERROR_CANNOT_CREATE, 1005 => MDB_ERROR_CANNOT_CREATE, 1006 => MDB_ERROR_CANNOT_CREATE, 1007 => MDB_ERROR_ALREADY_EXISTS, 1008 => MDB_ERROR_CANNOT_DROP, 1046 => MDB_ERROR_NODBSELECTED, 1050 => MDB_ERROR_ALREADY_EXISTS, 1051 => MDB_ERROR_NOSUCHTABLE, 1054 => MDB_ERROR_NOSUCHFIELD, 1062 => MDB_ERROR_ALREADY_EXISTS, 1064 => MDB_ERROR_SYNTAX, 1100 => MDB_ERROR_NOT_LOCKED, 1136 => MDB_ERROR_VALUE_COUNT_ON_ROW, 1146 => MDB_ERROR_NOSUCHTABLE, 1048 => MDB_ERROR_CONSTRAINT, ); } // }}} // {{{ errorNative() /** * Get the native error code of the last error (if any) that * occured on the current connection. * * @access public * * @return int native FrontBase error code */ function errorNative() { return fbsql_errno($this->connection); } // }}} // {{{ fbsqlRaiseError() /** * This method is used to communicate an error and invoke error * callbacks etc. Basically a wrapper for MDB::raiseError * that checks for native error msgs. * * @param integer $errno error code * @return object a PEAR error object * @access public * @see PEAR_Error */ function fbsqlRaiseError($errno = NULL) { if ($errno == NULL) { $errno = $this->errorCode(fbsql_errno($this->connection)); } return $this->raiseError($errno, NULL, NULL, NULL, @fbsql_error($this->connection)); } // }}} // {{{ autoCommit() /** * Define whether database changes done on the database be automatically * committed. This function may also implicitly start or end a transaction. * * @param boolean $auto_commit flag that indicates whether the database * changes should be committed right after * executing every query statement. If this * argument is 0 a transaction implicitly * started. Otherwise, if a transaction is * in progress it is ended by committing any * database changes that were pending. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function autoCommit($auto_commit) { $this->debug("AutoCommit: ".($auto_commit ? "On" : "Off")); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Auto-commit transactions: transactions are not in use'); } if (((!$this->auto_commit) == (!$auto_commit))) { return (MDB_OK); } if ($this->connection) { if ($auto_commit) { $result = $this->query('COMMIT;'); if (MDB::isError($result)) { return $result; } $result = $this->query('SET COMMIT TRUE;'); if (MDB::isError($result)) { return $result; } } else { $result = $this->query('SET COMMIT FALSE;'); if (MDB::isError($result)) { return $result; } } } $this->auto_commit = $auto_commit; return ($this->_registerTransactionShutdown($auto_commit)); } // }}} // {{{ commit() /** * Commit the database changes done during a transaction that is in * progress. This function may only be called when auto-committing is * disabled, otherwise it will fail. Therefore, a new transaction is * implicitly started after committing the pending changes. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function commit() { $this->debug("Commit Transaction"); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Commit transactions: transactions are not in use'); } if ($this->auto_commit) { return $this->raiseError(MDB_ERROR, '', '', 'Commit transactions: transaction changes are being auto commited'); } return ($this->query('COMMIT;')); } // }}} // {{{ rollback() /** * Cancel any database changes done during a transaction that is in * progress. This function may only be called when auto-committing is * disabled, otherwise it will fail. Therefore, a new transaction is * implicitly started after canceling the pending changes. * * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function rollback() { $this->debug("Rollback Transaction"); if (!isset($this->supported['Transactions'])) { return $this->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Rollback transactions: transactions are not in use'); } if ($this->auto_commit) { return $this->raiseError(MDB_ERROR, '', '', 'Rollback transactions: transactions can not be rolled back when changes are auto commited'); } return ($this->query('ROLLBACK;')); } // }}} // {{{ connect() /** * Connect to the database * * @return TRUE on success, MDB_Error on failure **/ function connect() { $port = (isset($this->port) ? $this->port : ''); if ($this->connection != 0) { if (!strcmp($this->connected_host, $this->host) && !strcmp($this->connected_user, $this->user) && !strcmp($this->connected_password, $this->password) && !strcmp($this->connected_port, $port) && $this->opened_persistent == $this->options['persistent']) { return (MDB_OK); } fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; } $this->fixed_float = 30; $function = ($this->options['persistent'] ? 'fbsql_pconnect' : 'fbsql_connect'); if (!function_exists($function)) { return ($this->raiseError(MDB_ERROR_UNSUPPORTED)); } @ini_set('track_errors', TRUE); $this->connection = @$function( $this->host.(!strcmp($port,'') ? '' : ':'.$port), $this->user, $this->password); @ini_restore('track_errors'); if ($this->connection <= 0) { return ($this->raiseError(MDB_ERROR_CONNECT_FAILED, '', '', $php_errormsg)); } if (isset($this->options['fixedfloat'])) { $this->fixed_float = $this->options['fixedfloat']; } else { if (($result = fbsql_query('SELECT VERSION()', $this->connection))) { $version = explode('.',fbsql_result($result,0,0)); $major = intval($version[0]); $minor = intval($version[1]); $revision = intval($version[2]); if ($major > 3 || ($major == 3 && $minor >= 23 && ($minor > 23 || $revision >= 6))) { $this->fixed_float = 0; } fbsql_free_result($result); } } if (isset($this->supported['Transactions']) && !$this->auto_commit) { if (!fbsql_query('SET AUTOCOMMIT = 0', $this->connection)) { fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; return ($this->raiseError()); } $this->_registerTransactionShutdown(0); } $this->connected_host = $this->host; $this->connected_user = $this->user; $this->connected_password = $this->password; $this->connected_port = $port; $this->opened_persistent = $this->options['persistent']; return (MDB_OK); } // }}} // {{{ _close() /** * all the RDBMS specific things needed close a DB connection * * @return boolean * @access private **/ function _close() { if ($this->connection != 0) { if (isset($this->supported['Transactions']) && !$this->auto_commit) { $result = $this->autoCommit(TRUE); } fbsql_close($this->connection); $this->connection = 0; $this->affected_rows = -1; if (isset($result) && MDB::isError($result)) { return $result; } global $_MDB_databases; $_MDB_databases[$this->database] = ''; return TRUE; } return FALSE; } // }}} // {{{ query() /** * Send a query to the database and return any results * * @access public * * @param string $query the SQL query * @param array $types array that contains the types of the columns in * the result set * * @return mixed a result handle or MDB_OK on success, a MDB error on failure */ function query($query, $types = NULL) { $this->debug("Query: $query"); $ismanip = MDB::isManip($query); $this->last_query = $query; $first = $this->first_selected_row; $limit = $this->selected_row_limit; $this->first_selected_row = $this->selected_row_limit = 0; $result = $this->connect(); if (MDB::isError($result)) { return $result; } if($limit > 0) { if ($ismanip) { $query .= " LIMIT $limit"; } else { $query .= " LIMIT $first,$limit"; } } if ($this->database_name != '') { if(!fbsql_select_db($this->database_name, $this->connection)) { return $this->fbsqlRaiseError(); } } if ($result = fbsql_query($query, $this->connection)) { if ($ismanip) { $this->affected_rows = fbsql_affected_rows($this->connection); return MDB_OK; } else { $this->highest_fetched_row[$result] = -1; if ($types != NULL) { if (!is_array($types)) { $types = array($types); } if (MDB::isError($err = $this->setResultTypes($result, $types))) { $this->freeResult($result); return $err; } } return $result; } } return $this->fbsqlRaiseError(); } // }}} // {{{ subSelect() /** * simple subselect emulation for FrontBase * * @access public * * @param string $query the SQL query for the subselect that may only * return a column * @param string $quote determines if the data needs to be quoted before * being returned * * @return string the query */ function subSelect($query, $quote = FALSE) { if($this->supported['SubSelects'] == 1) { return($query); } $col = $this->queryCol($query); if (MDB::isError($col)) { return $col; } if(!is_array($col) || count($col) == 0) { return 'NULL'; } if($quote) { for($i = 0, $j = count($col); $i < $j; ++$i) { $col[$i] = $this->getTextValue($col[$i]); } } return(implode(', ', $col)); } // }}} // {{{ replace() /** * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT * query, except that if there is already a row in the table with the same * key field values, the REPLACE query just updates its values instead of * inserting a new row. * * The REPLACE type of query does not make part of the SQL standards. Since * practically only MySQL implements it natively, this type of query is * emulated through this method for other DBMS using standard types of * queries inside a transaction to assure the atomicity of the operation. * * @access public * * @param string $table name of the table on which the REPLACE query will * be executed. * @param array $fields associative array that describes the fields and the * values that will be inserted or updated in the specified table. The * indexes of the array are the names of all the fields of the table. The * values of the array are also associative arrays that describe the * values and other properties of the table fields. * * Here follows a list of field properties that need to be specified: * * Value: * Value to be assigned to the specified field. This value may be * of specified in database independent type format as this * function can perform the necessary datatype conversions. * * Default: * this property is required unless the Null property * is set to 1. * * Type * Name of the type of the field. Currently, all types Metabase * are supported except for clob and blob. * * Default: text * * Null * Boolean property that indicates that the value for this field * should be set to NULL. * * The default value for fields missing in INSERT queries may be * specified the definition of a table. Often, the default value * is already NULL, but since the REPLACE may be emulated using * an UPDATE query, make sure that all fields of the table are * listed in this function argument array. * * Default: 0 * * Key * Boolean property that indicates that this field should be * handled as a primary key or at least as part of the compound * unique index of the table that will determine the row that will * updated if it exists or inserted a new row otherwise. * * This function will fail if no key field is specified or if the * value of a key field is set to NULL because fields that are * part of unique index they may not be NULL. * * Default: 0 * * @return mixed MDB_OK on success, a MDB error on failure */ function replace($table, $fields) { $count = count($fields); for($keys = 0, $query = $values = '',reset($fields), $field = 0; $field<$count; next($fields), $field++) { $name = key($fields); if ($field>0) { $query .= ','; $values .= ','; } $query .= $name; if (isset($fields[$name]['Null']) && $fields[$name]['Null']) { $value = 'NULL'; } else { if (!isset($fields[$name]['Value'])) { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'no value for field "'.$name.'" specified'); } switch(isset($fields[$name]['Type']) ? $fields[$name]['Type'] : 'text') { case 'text': $value = $this->getTextValue($fields[$name]['Value']); break; case 'boolean': $value = $this->getBooleanValue($fields[$name]['Value']); break; case 'integer': $value = strval($fields[$name]['Value']); break; case 'decimal': $value = $this->getDecimalValue($fields[$name]['Value']); break; case 'float': $value = $this->getFloatValue($fields[$name]['Value']); break; case 'date': $value = $this->getDateValue($fields[$name]['Value']); break; case 'time': $value = $this->getTimeValue($fields[$name]['Value']); break; case 'timestamp': $value = $this->getTimestampValue($fields[$name]['Value']); break; default: return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'no supported type for field "'.$name.'" specified'); } } $values .= $value; if (isset($fields[$name]['Key']) && $fields[$name]['Key']) { if ($value == 'NULL') { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'key values may not be NULL'); } $keys++; } } if ($keys == 0) { return $this->raiseError(MDB_ERROR_CANNOT_REPLACE, '', '', 'not specified which fields are keys'); } return ($this->query("REPLACE INTO $table ($query) VALUES ($values)")); } // }}} // {{{ getColumnNames() /** * Retrieve the names of columns returned by the DBMS in a query result. * * @param resource $result result identifier * @return mixed an associative array variable * that will hold 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 rows. * * a MDB error on failure * @access public */ function getColumnNames($result) { $result_value = intval($result); if (!isset($this->highest_fetched_row[$result_value])) { return $this->raiseError(MDB_ERROR_INVALID, '', '', 'Get column names: it was specified an inexisting result set'); } if (!isset($this->columns[$result_value])) { $this->columns[$result_value] = array(); $columns = fbsql_num_fields($result); for($column = 0; $column < $columns; $column++) { $this->columns[$result_value][strtolower(fbsql_field_name($result, $column))] = $column; } } return ($this->columns[$result_value]); } // }}} // {{{ numCols() /** * Count the number of columns returned by the DBMS in a query result. * * @param resource $result result identifier * @access public * @return mixed integer value with the number of columns, a MDB error * on failure */ function numCols($result) { if (!isset($this->highest_fetched_row[intval($result)])) { return $this->raiseError(MDB_ERROR_INVALID, '', '', 'numCols: it was specified an inexisting result set'); } return (fbsql_num_fields($result)); } // }}} // {{{ endOfResult() /** * check if the end of the result set has been reached * * @param resource $result result identifier * @return mixed TRUE or FALSE on sucess, a MDB error on failure * @access public */ function endOfResult($result) { if (!isset($this->highest_fetched_row[$result])) { return $this->raiseError(MDB_ERROR, '', '', 'End of result: attempted to check the end of an unknown result'); } return ($this->highest_fetched_row[$result] >= $this->numRows($result)-1); } // }}} // {{{ fetch() /** * fetch value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed string on success, a MDB error on failure * @access public */ function fetch($result, $row, $field) { $this->highest_fetched_row[$result] = max($this->highest_fetched_row[$result], $row); $res = @fbsql_result($result, $row, $field); if ($res === FALSE && $res != NULL) { return $this->fbsqlRaiseError($errno); } return ($res); } // }}} // {{{ fetchClob() /** * fetch a clob value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed content of the specified data cell, a MDB error on failure, * a MDB error on failure * @access public */ function fetchClob($result, $row, $field) { return ($this->fetchLob($result, $row, $field)); } // }}} // {{{ fetchBlob() /** * fetch a blob value from a result set * * @param resource $result result identifier * @param int $row number of the row where the data can be found * @param int $field field number where the data can be found * @return mixed content of the specified data cell, a MDB error on failure * @access public */ function fetchBlob($result, $row, $field) { return ($this->fetchLob($result, $row, $field)); } // }}} // {{{ convertResult() /** * convert a value to a RDBMS indepdenant MDB type * * @param mixed $value value to be converted * @param int $type constant that specifies which type to convert to * @return mixed converted value * @access public */ function convertResult($value, $type) { switch($type) { case MDB_TYPE_BOOLEAN: return (strcmp($value, 'Y') ? 0 : 1); case MDB_TYPE_DECIMAL: return (sprintf('%.'.$this->decimal_places.'f', doubleval($value)/$this->decimal_factor)); case MDB_TYPE_FLOAT: return (doubleval($value)); case MDB_TYPE_DATE: return ($value); case MDB_TYPE_TIME: return ($value); case MDB_TYPE_TIMESTAMP: return ($value); default: return ($this->_baseConvertResult($value, $type)); } } // }}} // {{{ numRows() /** * returns the number of rows in a result object * * @param ressource $result a valid result ressouce pointer * @return mixed MDB_Error or the number of rows * @access public */ function numRows($result) { return (fbsql_num_rows($result)); } // }}} // {{{ freeResult() /** * Free the internal resources associated with $result. * * @param $result result identifier * @return boolean TRUE on success, FALSE if $result is invalid * @access public */ function freeResult($result) { if(isset($this->highest_fetched_row[$result])) { unset($this->highest_fetched_row[$result]); } if(isset($this->columns[$result])) { unset($this->columns[$result]); } if(isset($this->result_types[$result])) { unset($this->result_types[$result]); } return (fbsql_free_result($result)); } // }}} // {{{ getIntegerDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * unsigned * Boolean flag that indicates whether the field * should be declared as unsigned integer if * possible. * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getIntegerDeclaration($name, $field) { return ("$name INT". (isset($field['unsigned']) ? ' UNSIGNED' : ''). (isset($field['default']) ? ' DEFAULT '.$field['default'] : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getClobDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an character * large object type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the * properties of the field being declared as array * indexes. Currently, the types of supported field * properties are as follows: * * length * Integer value that determines the maximum length * of the large object field. If this argument is * missing the field should be declared to have the * longest length allowed by the DBMS. * * notnull * Boolean flag that indicates whether this field * is constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getClobDeclaration($name, $field) { if (isset($field['length'])) { $length = $field['length']; $type = "VAECHAR($length)"; } else { $type = "VAECHAR(32768)"; } return ("$name $type". (isset($field['notnull']) ? ' NOT NULL' : '')); } // }}} // {{{ getBlobDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an binary large * object type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * length * Integer value that determines the maximum length * of the large object field. If this argument is * missing the field should be declared to have the * longest length allowed by the DBMS. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getBlobDeclaration($name, $field) { if (isset($field['length'])) { $length = $field['length']; $type = "BLOB($length)"; } else { $type = "BLOB(32768)"; } return ("$name $type". (isset($field['notnull']) ? ' NOT NULL' : '')); } // }}} // {{{ getDateDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an date type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field properties * are as follows: * * default * Date value to be used as default for this field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getDateDeclaration($name, $field) { return ("$name DATE". (isset($field['default']) ? " DEFAULT DATE'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getTimestampDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an timestamp * type field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Time stamp value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getTimestampDeclaration($name, $field) { return ("$name DATETIME". (isset($field['default']) ? " DEFAULT TIMESTAMP'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getTimeDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an time type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Time value to be used as default for this field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getTimeDeclaration($name, $field) { return ("$name TIME". (isset($field['default']) ? " DEFAULT TIME'".$field['default']."'" : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getFloatDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an float type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getFloatDeclaration($name, $field) { if (isset($this->options['fixedfloat'])) { $this->fixed_float = $this->options['fixedfloat']; } else { if ($this->connection == 0) { // XXX needs more checking $this->connect(); } } return ("$name DOUBLE". ($this->fixed_float ? '('.($this->fixed_float + 2).','.$this->fixed_float.')' : ''). (isset($field['default']) ? ' DEFAULT '.$this->getFloatValue($field['default']) : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getDecimalDeclaration() /** * Obtain DBMS specific SQL code portion needed to declare an decimal type * field to be used in statements like CREATE TABLE. * * @param string $name name the field to be declared. * @param string $field associative array with the name of the properties * of the field being declared as array indexes. * Currently, the types of supported field * properties are as follows: * * default * Integer value to be used as default for this * field. * * notnull * Boolean flag that indicates whether this field is * constrained to not be set to NULL. * @return string DBMS specific SQL code portion that should be used to * declare the specified field. * @access public */ function getDecimalDeclaration($name, $field) { return ("$name REAL". (isset($field['default']) ? ' DEFAULT '.$this->getDecimalValue($field['default']) : ''). (isset($field['notnull']) ? ' NOT NULL' : '') ); } // }}} // {{{ getClobValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param resource $prepared_query query handle from prepare() * @param $parameter * @param $clob * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getClobValue($prepared_query, $parameter, $clob) { $value = "'"; while(!$this->endOfLob($clob)) { if (MDB::isError($result = $this->readLob($clob, $data, $this->options['lob_buffer_length']))) { return $result; } $value .= $this->_quote($data); } $value .= "'"; return ($value); } // }}} // {{{ freeClobValue() /** * free a character large object * * @param resource $prepared_query query handle from prepare() * @param string $clob * @return MDB_OK * @access public */ function freeClobValue($prepared_query, $clob) { unset($this->lobs[$clob]); return (MDB_OK); } // }}} // {{{ getBlobValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param resource $prepared_query query handle from prepare() * @param $parameter * @param $blob * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getBlobValue($prepared_query, $parameter, $blob) { $value = "'"; while(!$this->endOfLob($blob)) { if (MDB::isError($result = $this->readLob($blob, $data, $this->options['lob_buffer_length']))) { return $result; } $value .= addslashes($data); } $value .= "'"; return ($value); } // }}} // {{{ freeBlobValue() /** * free a binary large object * * @param resource $prepared_query query handle from prepare() * @param string $blob * @return MDB_OK * @access public */ function freeBlobValue($prepared_query, $blob) { unset($this->lobs[$blob]); return (MDB_OK); } // }}} // {{{ getFloatValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param string $value text string value that is intended to be converted. * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getFloatValue($value) { return (!strcmp($value, 'NULL') ? 'NULL' : "$value"); } // }}} // {{{ getDecimalValue() /** * Convert a text value into a DBMS specific format that is suitable to * compose query statements. * * @param string $value text string value that is intended to be converted. * @return string text string that represents the given argument value in * a DBMS specific format. * @access public */ function getDecimalValue($value) { return (!strcmp($value, 'NULL') ? 'NULL' : strval(round(doubleval($value)*$this->decimal_factor))); } // }}} // {{{ nextId() /** * 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 * not exists * * @return mixed MDB_Error or id * @access public */ function nextId($seq_name, $ondemand = TRUE) { $sequence_name = $this->getSequenceName($seq_name); $result = $this->query("INSERT INTO $sequence_name (sequence) VALUES (NULL);"); if ($ondemand && MDB::isError($result) && $result->getCode() == MDB_ERROR_NOSUCHTABLE) { $result = $this->createSequence($seq_name, 2); // Since we are create the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 if (MDB::isError($result)) { return $this->raiseError(MDB_ERROR, '', '', 'Next ID: on demand sequence could not be created'); } else { // First ID of a newly created sequence is 1 return 1; } } $value = intval(fbsql_insert_id()); $res = $this->query("DELETE FROM $sequence_name WHERE sequence < $value;"); if (MDB::isError($res)) { $this->warnings[] = 'Next ID: could not delete previous sequence table values'; } return ($value); } // }}} // {{{ currId() /** * returns the current id of a sequence * * @param string $seq_name name of the sequence * @return mixed MDB_Error or id * @access public */ function currId($seq_name) { $sequence_name = $this->getSequenceName($seq_name); $result = $this->query("SELECT MAX(sequence) FROM $sequence_name;", 'integer'); if (MDB::isError($result)) { return $result; } return ($this->fetchOne($result)); } // }}} // {{{ fetchInto() /** * Fetch a row and insert the data into an existing array. * * @param resource $result result identifier * @param int $fetchmode how the array data should be indexed * @param int $rownum the row number to fetch * @return int data array on success, a MDB error on failure * @access public */ function fetchInto($result, $fetchmode = MDB_FETCHMODE_DEFAULT, $rownum = NULL) { if ($rownum == NULL) { ++$this->highest_fetched_row[$result]; } else { if (!@fbsql_data_seek($result, $rownum)) { return NULL; } $this->highest_fetched_row[$result] = max($this->highest_fetched_row[$result], $rownum); } if ($fetchmode == MDB_FETCHMODE_DEFAULT) { $fetchmode = $this->fetchmode; } if ($fetchmode & MDB_FETCHMODE_ASSOC) { $array = @fbsql_fetch_array($result, FBSQL_ASSOC); } else { $array = @fbsql_fetch_row($result); } if (!$array) { $errno = @fbsql_errno($this->connection); if (!$errno) { if($this->options['autofree']) { $this->freeResult($result); } return NULL; } return $this->fbsqlRaiseError($errno); } if (isset($this->result_types[$result])) { $array = $this->convertResultRow($result, $array); } return ($array); } // }}} // {{{ nextResult() /** * Move the internal fbsql result pointer to the next available result * Currently not supported * * @param a valid result resource * @return true if a result is available otherwise return false * @access public */ function nextResult($result) { return FALSE; } // }}} // {{{ tableInfo() /** * returns meta data about the result set * * @param resource $result result identifier * @param mixed $mode depends on implementation * @return array an nested array, or a MDB error * @access public */ function tableInfo($result, $mode = NULL) { $count = 0; $id = 0; $res = array(); /* * depending on $mode, metadata returns the following values: * * - mode is false (default): * $result[]: * [0]['table'] table name * [0]['name'] field name * [0]['type'] field type * [0]['len'] field length * [0]['flags'] field flags * * - mode is MDB_TABLEINFO_ORDER * $result[]: * ['num_fields'] number of metadata records * [0]['table'] table name * [0]['name'] field name * [0]['type'] field type * [0]['len'] field length * [0]['flags'] field flags * ['order'][field name] index of field named "field name" * The last one is used, if you have a field name, but no index. * Test: if (isset($result['meta']['myfield'])) { ... * * - mode is MDB_TABLEINFO_ORDERTABLE * the same as above. but additionally * ['ordertable'][table name][field name] index of field * named 'field name' * * this is, because if you have fields from different * tables with the same field name * they override each * other with MDB_TABLEINFO_ORDER * * you can combine MDB_TABLEINFO_ORDER and * MDB_TABLEINFO_ORDERTABLE with MDB_TABLEINFO_ORDER | * MDB_TABLEINFO_ORDERTABLE * or with MDB_TABLEINFO_FULL */ // if $result is a string, then we want information about a // table without a resultset if (is_string($result)) { $id = @fbsql_list_fields($this->database_name, $result, $this->connection); if (empty($id)) { return $this->fbsqlRaiseError(); } } else { // else we want information about a resultset $id = $result; if (empty($id)) { return $this->fbsqlRaiseError(); } } $count = @fbsql_num_fields($id); // made this IF due to performance (one if is faster than $count if's) if (empty($mode)) { for ($i = 0; $i<$count; $i++) { $res[$i]['table'] = @fbsql_field_table ($id, $i); $res[$i]['name'] = @fbsql_field_name ($id, $i); $res[$i]['type'] = @fbsql_field_type ($id, $i); $res[$i]['len'] = @fbsql_field_len ($id, $i); $res[$i]['flags'] = @fbsql_field_flags ($id, $i); } } else { // full $res['num_fields'] = $count; for ($i = 0; $i<$count; $i++) { $res[$i]['table'] = @fbsql_field_table ($id, $i); $res[$i]['name'] = @fbsql_field_name ($id, $i); $res[$i]['type'] = @fbsql_field_type ($id, $i); $res[$i]['len'] = @fbsql_field_len ($id, $i); $res[$i]['flags'] = @fbsql_field_flags ($id, $i); if ($mode & MDB_TABLEINFO_ORDER) { $res['order'][$res[$i]['name']] = $i; } if ($mode & MDB_TABLEINFO_ORDERTABLE) { $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; } } } // free the result only if we were called on a table if (is_string($result)) { @fbsql_free_result($id); } return $res; } } ?> Index: pear/MDB/MDB/Modules/Manager/fbsql.php +++ pear/MDB/MDB/Modules/Manager/fbsql.php <?php // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1998-2002 Manuel Lemos, Tomas V.V.Cox, | // | Stig. S. Bakken, Lukas Smith, Frank M. Kromann | // | All rights reserved. | // +----------------------------------------------------------------------+ // | MDB 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 | // | are met: | // | | // | 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: Lukas Smith <smith@dybnet.de> | // +----------------------------------------------------------------------+ // // $Id: fbsql.php,v 1.1 2002/12/26 21:38:05 fmk Exp $ // if(!defined('MDB_MANAGER_FBSQL_INCLUDED')) { define('MDB_MANAGER_FBSQL_INCLUDED', 1); require_once 'MDB/Modules/Manager/Common.php'; /** * MDB FrontBase driver for the management modules * * @package MDB * @category Database * @access private * @author Lukas Smith <smith@dybnet.de> * @author Frank M. Kromann <frank@kromann.info> */ class MDB_Manager_fbsql extends MDB_Manager_Common { // {{{ properties var $verified_table_types = array(); // }}} // {{{ _verifyTransactionalTableType() /** * verify that chosen transactional table hanlder is available in the database * * @param object $dbs database object that is extended by this class * @param string $table_type name of the table handler * @return mixed MDB_OK on success, a MDB error on failure * @access private */ function _verifyTransactionalTableType(&$db, $table_type) { switch(strtoupper($table_type)) { case 'BERKELEYDB': case 'BDB': $check = 'have_bdb'; break; case 'INNODB': $check = 'have_innobase'; break; case 'GEMINI': $check = 'have_gemini'; break; case 'HEAP': case 'ISAM': case 'MERGE': case 'MRG_MYISAM': case 'MYISAM': case '': return(MDB_OK); default: return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table', $table_type.' is not a supported table type')); } if(!$db->connect()) { return($db->raiseError()); } if(isset($this->verified_table_types[$table_type]) && $this->verified_table_types[$table_type] == $db->connection) { return(MDB_OK); } if(MDB::isError($has = $db->queryAll("SHOW VARIABLES LIKE '$check'", NULL, MDB_FETCHMODE_ORDERED))) { return($db->raiseError()); } if(count($has) == 0) { return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table',"could not tell if ".$table_type.' is a supported table type')); } if(strcmp($has[0][1], 'YES')) { return($db->raiseError(MDB_ERROR_UNSUPPORTED, '', '', 'Verify transactional table', $table_type.' is not a supported table type by this FrontBase database server')); } $this->verified_table_types[$table_type] = $db->connection; return (MDB_OK); } // }}} // {{{ createDatabase() /** * create a new database * * @param object $dbs database object that is extended by this class * @param string $name name of the database that should be created * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createDatabase(&$db, $name) { if (MDB::isError($result = $db->connect())) { return $result; } if (!fbsql_create_db($name, $db->connection)) { return $db->fbsqlRaiseError(); } return (MDB_OK); } // }}} // {{{ dropDatabase() /** * drop an existing database * * @param object $dbs database object that is extended by this class * @param string $name name of the database that should be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropDatabase(&$db, $name) { if (MDB::isError($result = $db->connect())) { return $result; } if (!fbsql_drop_db($name, $db->connection)) { return $db->fbsqlRaiseError(); } return (MDB_OK); } // }}} // {{{ createTable() /** * create a new table * * @param object $dbs database object that is extended by this class * @param string $name Name of the database that should be created * @param array $fields Associative array that contains the definition of each field of the new table * The indexes of the array entries are the names of the fields of the table an * the array entry values are associative arrays like those that are meant to be * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( * * 'id' => array( * 'type' => 'integer', * 'unsigned' => 1 * 'notnull' => 1 * 'default' => 0 * ), * 'name' => array( * 'type' => 'text', * 'length' => 12 * ), * 'password' => array( * 'type' => 'text', * 'length' => 12 * ) * ); * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createTable(&$db, $name, $fields) { if (!isset($name) || !strcmp($name, '')) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'no valid table name specified'); } if (count($fields) == 0) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'no fields specified for table "'.$name.'"'); } if(MDB::isError($verify = $this->_verifyTransactionalTableType($db, $db->default_table_type))) { return($verify); } if (MDB::isError($query_fields = $db->getFieldDeclarationList($fields))) { return $db->raiseError(MDB_ERROR_CANNOT_CREATE, '', '', 'unkown error'); } if (isset($db->supported['Transactions']) && $db->default_table_type=='BDB') { $query_fields .= ', dummy_primary_key INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (dummy_primary_key)'; } $query = "CREATE TABLE $name ($query_fields)".(strlen($db->default_table_type) ? ' TYPE='.$db->default_table_type : ''); return ($db->query($query)); } // }}} // {{{ alterTable() /** * alter an existing table * * @param object $dbs database object that is extended by this class * @param string $name name of the table that is intended to be changed. * @param array $changes associative array that contains the details of each type * of change that is intended to be performed. The types of * changes that are currently supported are defined as follows: * * name * * New name for the table. * * AddedFields * * Associative array with the names of fields to be added as * indexes of the array. The value of each entry of the array * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. * * Additionally, there should be an entry named Declaration that * is expected to contain the portion of the field declaration already * in DBMS specific SQL code as it is used in the CREATE TABLE statement. * * RemovedFields * * Associative array with the names of fields to be removed as indexes * of the array. Currently the values assigned to each entry are ignored. * An empty array should be used for future compatibility. * * RenamedFields * * Associative array with the names of fields to be renamed as indexes * of the array. The value of each entry of the array should be set to * another associative array with the entry named name with the new * field name and the entry named Declaration that is expected to contain * the portion of the field declaration already in DBMS specific SQL code * as it is used in the CREATE TABLE statement. * * ChangedFields * * Associative array with the names of the fields to be changed as indexes * of the array. Keep in mind that if it is intended to change either the * name of a field and any other properties, the ChangedFields array entries * should have the new names of the fields as array indexes. * * The value of each entry of the array should be set to another associative * array with the properties of the fields to that are meant to be changed as * array entries. These entries should be assigned to the new values of the * respective properties. The properties of the fields should be the same * as defined by the Metabase parser. * * If the default property is meant to be added, removed or changed, there * should also be an entry with index ChangedDefault assigned to 1. Similarly, * if the notnull constraint is to be added or removed, there should also be * an entry with index ChangedNotNull assigned to 1. * * Additionally, there should be an entry named Declaration that is expected * to contain the portion of the field changed declaration already in DBMS * specific SQL code as it is used in the CREATE TABLE statement. * Example * array( * 'name' => 'userlist', * 'AddedFields' => array( * 'quota' => array( * 'type' => 'integer', * 'unsigned' => 1 * 'Declaration' => 'quota INT' * ) * ), * 'RemovedFields' => array( * 'file_limit' => array(), * 'time_limit' => array() * ), * 'ChangedFields' => array( * 'gender' => array( * 'default' => 'M', * 'ChangeDefault' => 1, * 'Declaration' => "gender CHAR(1) DEFAULT 'M'" * ) * ), * 'RenamedFields' => array( * 'sex' => array( * 'name' => 'gender', * 'Declaration' => "gender CHAR(1) DEFAULT 'M'" * ) * ) * ) * * @param boolean $check indicates whether the function should just check if the DBMS driver * can perform the requested table alterations if the value is true or * actually perform them otherwise. * @access public * * @return mixed MDB_OK on success, a MDB error on failure */ function alterTable(&$db, $name, $changes, $check) { if ($check) { for($change = 0,reset($changes); $change < count($changes); next($changes), $change++) { switch(key($changes)) { case 'AddedFields': case 'RemovedFields': case 'ChangedFields': case 'RenamedFields': case 'name': break; default: return $db->raiseError(MDB_ERROR_CANNOT_ALTER, '', '', 'Alter table: change type "'.Key($changes).'" not yet supported'); } } return (MDB_OK); } else { $query = (isset($changes['name']) ? 'RENAME AS '.$changes['name'] : ''); if (isset($changes['AddedFields'])) { $fields = $changes['AddedFields']; for($field = 0, reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $query .= 'ADD '.$fields[key($fields)]['Declaration']; } } if (isset($changes['RemovedFields'])) { $fields = $changes['RemovedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $query .= 'DROP '.key($fields); } } $renamed_fields = array(); if (isset($changes['RenamedFields'])) { $fields = $changes['RenamedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { $renamed_fields[$fields[key($fields)]['name']] = key($fields); } } if (isset($changes['ChangedFields'])) { $fields = $changes['ChangedFields']; for($field = 0,reset($fields); $field<count($fields); next($fields), $field++) { if (strcmp($query, '')) { $query .= ','; } if (isset($renamed_fields[key($fields)])) { $field_name = $renamed_fields[key($fields)]; unset($renamed_fields[key($fields)]); } else { $field_name = key($fields); } $query .= "CHANGE $field_name ".$fields[key($fields)]['Declaration']; } } if (count($renamed_fields)) { for($field = 0,reset($renamed_fields); $field<count($renamed_fields); next($renamed_fields), $field++) { if (strcmp($query, '')) { $query .= ','; } $old_field_name = $renamed_fields[Key($renamed_fields)]; $query .= "CHANGE $old_field_name ".$changes['RenamedFields'][$old_field_name]['Declaration']; } } return ($db->query("ALTER TABLE $name $query")); } } // }}} // {{{ listDatabases() /** * list all databases * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listDatabases(&$db) { $result = $db->queryCol('SHOW DATABASES'); if(MDB::isError($result)) { return $result; } return ($result); } // }}} // {{{ listUsers() /** * list all users * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listUsers(&$db) { $result = $db->queryCol('SELECT DISTINCT USER FROM USER'); if(MDB::isError($result)) { return $result; } return ($result); } // }}} // {{{ listTables() /** * list all tables in the current database * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listTables(&$db) { $table_names = $db->queryCol('SHOW TABLES'); if(MDB::isError($table_names)) { return $table_names; } for($i = 0, $j = count($table_names), $tables = array(); $i < $j; ++$i) { if (!$db->_isSequenceName($table_names[$i])) $tables[] = $table_names[$i]; } return ($tables); } // }}} // {{{ listTableFields() /** * list all fields in a tables in the current database * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function listTableFields(&$db, $table) { $result = $db->query("SHOW COLUMNS FROM $table"); if(MDB::isError($result)) { return $result; } $columns = $db->getColumnNames($result); if(MDB::isError($columns)) { $db->freeResult($columns); return $columns; } if(!isset($columns['field'])) { $db->freeResult($result); return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'List table fields: show columns does not return the table field names'); } $field_column = $columns['field']; for($fields = array(), $field = 0; !$db->endOfResult($result); ++$field) { $field_name = $db->fetch($result, $field, $field_column); if ($field_name != $db->dummy_primary_key) $fields[] = $field_name; } $db->freeResult($result); return ($fields); } // }}} // {{{ getTableFieldDefinition() /** * get the stucture of a field into an array * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $field_name name of field that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function getTableFieldDefinition(&$db, $table, $field_name) { if ($field_name == $db->dummy_primary_key) { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definiton: '.$db->dummy_primary_key.' is an hidden column'); } $result = $db->query("SHOW COLUMNS FROM $table"); if(MDB::isError($result)) { return $result; } $columns = $db->getColumnNames($result); if(MDB::isError($columns)) { $db->freeResult($columns); return $columns; } if (!isset($columns[$column = 'field']) || !isset($columns[$column = 'type'])) { $db->freeResult($result); return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definition: show columns does not return the column '.$column); } $field_column = $columns['field']; $type_column = $columns['type']; while (is_array($row = $db->fetchInto($result))) { if ($field_name == $row[$field_column]) { $db_type = strtolower($row[$type_column]); $db_type = strtok($db_type, '(), '); if ($db_type == 'national') { $db_type = strtok('(), '); } $length = strtok('(), '); $decimal = strtok('(), '); $type = array(); switch($db_type) { case 'tinyint': case 'smallint': case 'mediumint': case 'int': case 'integer': case 'bigint': $type[0] = 'integer'; if($length == '1') { $type[1] = 'boolean'; if (preg_match('/^[is|has]/', $field_name)) { $type = array_reverse($type); } } break; case 'tinytext': case 'mediumtext': case 'longtext': case 'text': case 'char': case 'varchar': $type[0] = 'text'; if($decimal == 'binary') { $type[1] = 'blob'; } elseif($length == '1') { $type[1] = 'boolean'; if (preg_match('/[is|has]/', $field_name)) { $type = array_reverse($type); } } elseif(strstr($db_type, 'text')) $type[1] = 'clob'; break; case 'enum': preg_match_all('/\'.+\'/U',$row[$type_column], $matches); $length = 0; if(is_array($matches)) { foreach($matches[0] as $value) { $length = max($length, strlen($value)-2); } } unset($decimal); case 'set': $type[0] = 'text'; $type[1] = 'integer'; break; case 'date': $type[0] = 'date'; break; case 'datetime': case 'timestamp': $type[0] = 'timestamp'; break; case 'time': $type[0] = 'time'; break; case 'float': case 'double': case 'real': $type[0] = 'float'; break; case 'decimal': case 'numeric': $type[0] = 'decimal'; break; case 'tinyblob': case 'mediumblob': case 'longblob': case 'blob': $type[0] = 'blob'; $type[1] = 'text'; break; case 'year': $type[0] = 'integer'; $type[1] = 'date'; break; default: return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'List table fields: unknown database attribute type'); } unset($notnull); if (isset($columns['null']) && $row[$columns['null']] != 'YES') { $notnull = 1; } unset($default); if (isset($columns['default']) && isset($row[$columns['default']])) { $default = $row[$columns['default']]; } $definition = array(); for($field_choices = array(), $datatype = 0; $datatype < count($type); $datatype++) { $field_choices[$datatype] = array('type' => $type[$datatype]); if(isset($notnull)) { $field_choices[$datatype]['notnull'] = 1; } if(isset($default)) { $field_choices[$datatype]['default'] = $default; } if($type[$datatype] != 'boolean' && $type[$datatype] != 'time' && $type[$datatype] != 'date' && $type[$datatype] != 'timestamp') { if(strlen($length)) { $field_choices[$datatype]['length'] = $length; } } } $definition[0] = $field_choices; if (isset($columns['extra']) && isset($row[$columns['extra']]) && $row[$columns['extra']] == 'auto_increment') { $implicit_sequence = array(); $implicit_sequence['on'] = array(); $implicit_sequence['on']['table'] = $table; $implicit_sequence['on']['field'] = $field_name; $definition[1]['name'] = $table.'_'.$field_name; $definition[1]['definition'] = $implicit_sequence; } if (isset($columns['key']) && isset($row[$columns['key']]) && $row[$columns['key']] == 'PRI') { // check that its not just a unique field if(MDB::isError($indexes = $db->queryAll("SHOW INDEX FROM $table", NULL, MDB_FETCHMODE_ASSOC))) { return($indexes); } $is_primary = FALSE; foreach($indexes as $index) { if ($index['Key_name'] == 'PRIMARY' && $index['Column_name'] == $field_name) { $is_primary = TRUE; break; } } if($is_primary) { $implicit_index = array(); $implicit_index['unique'] = 1; $implicit_index['FIELDS'][$field_name] = ''; $definition[2]['name'] = $field_name; $definition[2]['definition'] = $implicit_index; } } $db->freeResult($result); return ($definition); } } if(!$db->options['autofree']) { $db->freeResult($result); } if(MDB::isError($row)) { return($row); } return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table field definition: it was not specified an existing table column'); } // }}} // {{{ createIndex() /** * get the stucture of a field into an array * * @param object $dbs database object that is extended by this class * @param string $table name of the table on which the index is to be created * @param string $name name of the index to be created * @param array $definition associative array that defines properties of the index to be created. * Currently, only one property named FIELDS is supported. This property * is also an associative with the names of the index fields as array * indexes. Each entry of this array is set to another type of associative * array that specifies properties of the index that are specific to * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either * ascending or descending. * * Not all DBMS support index sorting direction configuration. The DBMS * drivers of those that do not support it ignore this property. Use the * function support() to determine whether the DBMS driver can manage indexes. * Example * array( * 'FIELDS' => array( * 'user_name' => array( * 'sorting' => 'ascending' * ), * 'last_login' => array() * ) * ) * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createIndex(&$db, $table, $name, $definition) { $query = "ALTER TABLE $table ADD ".(isset($definition['unique']) ? 'UNIQUE' : 'INDEX')." $name ("; for($field = 0, reset($definition['FIELDS']); $field < count($definition['FIELDS']); $field++, next($definition['FIELDS'])) { if ($field > 0) { $query .= ','; } $query .= key($definition['FIELDS']); } $query .= ')'; return ($db->query($query)); } // }}} // {{{ dropIndex() /** * drop existing index * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $name name of the index to be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropIndex(&$db, $table, $name) { return ($db->query("ALTER TABLE $table DROP INDEX $name")); } // }}} // {{{ listTableIndexes() /** * list all indexes in a table * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function listTableIndexes(&$db, $table) { if(MDB::isError($result = $db->query("SHOW INDEX FROM $table"))) { return($result); } $indexes_all = $db->fetchCol($result, 'Key_name'); for($found = $indexes = array(), $index = 0, $indexes_all_cnt = count($indexes_all); $index < $indexes_all_cnt; $index++) { if ($indexes_all[$index] != 'PRIMARY' && !isset($found[$indexes_all[$index]])) { $indexes[] = $indexes_all[$index]; $found[$indexes_all[$index]] = 1; } } $db->freeResult($result); return($indexes); } // }}} // {{{ getTableIndexDefinition() /** * get the stucture of an index into an array * * @param object $dbs database object that is extended by this class * @param string $table name of table that should be used in method * @param string $index_name name of index that should be used in method * @return mixed data array on success, a MDB error on failure * @access public */ function getTableIndexDefinition(&$db, $table, $index_name) { if($index_name == 'PRIMARY') { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table index definition: PRIMARY is an hidden index'); } if(MDB::isError($result = $db->query("SHOW INDEX FROM $table"))) { return($result); } $definition = array(); while (is_array($row = $db->fetchInto($result, MDB_FETCHMODE_ASSOC))) { $key_name = $row['Key_name']; if(!strcmp($index_name, $key_name)) { if(!$row['Non_unique']) { $definition[$index_name]['unique'] = 1; } $column_name = $row['Column_name']; $definition['FIELDS'][$column_name] = array(); if(isset($row['Collation'])) { $definition['FIELDS'][$column_name]['sorting'] = ($row['Collation'] == 'A' ? 'ascending' : 'descending'); } } } $db->freeResult($result); if (!isset($definition['FIELDS'])) { return $db->raiseError(MDB_ERROR_MANAGER, '', '', 'Get table index definition: it was not specified an existing table index'); } return ($definition); } // }}} // {{{ createSequence() /** * create sequence * * @param object $dbs database object that is extended by this class * @param string $seq_name name of the sequence to be created * @param string $start start value of the sequence; default is 1 * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function createSequence(&$db, $seq_name, $start) { $sequence_name = $db->getSequenceName($seq_name); $res = $db->query("CREATE TABLE $sequence_name (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence))"); if (MDB::isError($res)) { return $res; } if ($start == 1) { return MDB_OK; } $res = $db->query("INSERT INTO $sequence_name (sequence) VALUES (".($start-1).")"); if (!MDB::isError($res)) { return MDB_OK; } // Handle error $result = $db->query("DROP TABLE $sequence_name"); if (MDB::isError($result)) { return $db->raiseError(MDB_ERROR, '', '', 'Create sequence: could not drop inconsistent sequence table ('. $result->getMessage().' ('.$result->getUserinfo().'))'); } return $db->raiseError(MDB_ERROR, '', '', 'Create sequence: could not create sequence table ('. $res->getMessage().' ('.$res->getUserinfo().'))'); } // }}} // {{{ dropSequence() /** * drop existing sequence * * @param object $dbs database object that is extended by this class * @param string $seq_name name of the sequence to be dropped * @return mixed MDB_OK on success, a MDB error on failure * @access public */ function dropSequence(&$db, $seq_name) { $sequence_name = $db->getSequenceName($seq_name); return ($db->query("DROP TABLE $sequence_name")); } // }}} // {{{ listSequences() /** * list all sequences in the current database * * @param object $dbs database object that is extended by this class * @return mixed data array on success, a MDB error on failure * @access public */ function listSequences(&$db) { $table_names = $db->queryCol('SHOW TABLES'); if(MDB::isError($table_names)) { return $table_names; } for($i = 0, $j = count($table_names), $sequences = array(); $i < $j; ++$i) { if ($sqn = $db->_isSequenceName($table_names[$i])) $sequences[] = $sqn; } return ($sequences); } // }}} } }; ?>