initial commit

This commit is contained in:
Chris Sewell
2012-11-28 03:55:08 -05:00
parent 7adb399b2e
commit cf140a2e97
3247 changed files with 492437 additions and 0 deletions

View File

@ -0,0 +1,290 @@
<?php
/*
* $Id: MySQLConnection.php,v 1.18 2004/09/01 14:00:28 dlawson_mi Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/Connection.php';
require_once 'creole/common/ConnectionCommon.php';
include_once 'creole/drivers/mysql/MySQLResultSet.php';
/**
* MySQL implementation of Connection.
*
*
* @author Hans Lellelid <hans@xmpl.org>
* @author Stig Bakken <ssb@fast.no>
* @author Lukas Smith
* @version $Revision: 1.18 $
* @package creole.drivers.mysql
*/
class MySQLConnection extends ConnectionCommon implements Connection {
/** Current database (used in mysql_select_db()). */
private $database;
/**
* Connect to a database and log in as the specified user.
*
* @param $dsn the data source name (see DB::parseDSN for syntax)
* @param $flags Any conneciton flags.
* @access public
* @throws SQLException
* @return void
*/
function connect($dsninfo, $flags = 0)
{
if (!extension_loaded('mysql')) {
throw new SQLException('mysql extension not loaded');
}
$this->dsn = $dsninfo;
$this->flags = $flags;
$persistent = ($flags & Creole::PERSISTENT) === Creole::PERSISTENT;
if (isset($dsninfo['protocol']) && $dsninfo['protocol'] == 'unix') {
$dbhost = ':' . $dsninfo['socket'];
} else {
$dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
if (!empty($dsninfo['port'])) {
$dbhost .= ':' . $dsninfo['port'];
}
}
$user = $dsninfo['username'];
$pw = $dsninfo['password'];
$encoding = !empty($dsninfo['encoding']) ? $dsninfo['encoding'] : null;
$connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
@ini_set('track_errors', true);
if ($dbhost && $user && $pw) {
$conn = @$connect_function($dbhost, $user, $pw);
} elseif ($dbhost && $user) {
$conn = @$connect_function($dbhost, $user);
} elseif ($dbhost) {
$conn = @$connect_function($dbhost);
} else {
$conn = false;
}
@ini_restore('track_errors');
if (empty($conn)) {
if (($err = @mysql_error()) != '') {
throw new SQLException("connect failed", $err);
} elseif (empty($php_errormsg)) {
throw new SQLException("connect failed");
} else {
throw new SQLException("connect failed", $php_errormsg);
}
}
if ($dsninfo['database']) {
if (!@mysql_select_db($dsninfo['database'], $conn)) {
switch(mysql_errno($conn)) {
case 1049:
$exc = new SQLException("no such database", mysql_error($conn));
break;
case 1044:
$exc = new SQLException("access violation", mysql_error($conn));
break;
default:
$exc = new SQLException("cannot select database", mysql_error($conn));
}
throw $exc;
}
// fix to allow calls to different databases in the same script
$this->database = $dsninfo['database'];
}
$this->dblink = $conn;
if ($encoding) {
$this->executeUpdate("SET NAMES " . $encoding);
}
}
/**
* @see Connection::getDatabaseInfo()
*/
public function getDatabaseInfo()
{
require_once 'creole/drivers/mysql/metadata/MySQLDatabaseInfo.php';
return new MySQLDatabaseInfo($this);
}
/**
* @see Connection::getIdGenerator()
*/
public function getIdGenerator()
{
require_once 'creole/drivers/mysql/MySQLIdGenerator.php';
return new MySQLIdGenerator($this);
}
/**
* @see Connection::prepareStatement()
*/
public function prepareStatement($sql)
{
require_once 'creole/drivers/mysql/MySQLPreparedStatement.php';
return new MySQLPreparedStatement($this, $sql);
}
/**
* @see Connection::prepareCall()
*/
public function prepareCall($sql) {
throw new SQLException('MySQL does not support stored procedures.');
}
/**
* @see Connection::createStatement()
*/
public function createStatement()
{
require_once 'creole/drivers/mysql/MySQLStatement.php';
return new MySQLStatement($this);
}
/**
* @see Connection::disconnect()
*/
function close()
{
$ret = mysql_close($this->dblink);
$this->dblink = null;
return $ret;
}
/**
* @see Connection::applyLimit()
*/
public function applyLimit(&$sql, $offset, $limit)
{
if ( $limit > 0 ) {
$sql .= " LIMIT " . ($offset > 0 ? $offset . ", " : "") . $limit;
} else if ( $offset > 0 ) {
$sql .= " LIMIT " . $offset . ", 18446744073709551615";
}
}
/**
* @see Connection::executeQuery()
*/
function executeQuery($sql, $fetchmode = null)
{
$this->lastQuery = $sql;
if ($this->database) {
if (!@mysql_select_db($this->database, $this->dblink)) {
throw new SQLException('No database selected', mysql_error($this->dblink));
}
}
$result = @mysql_query($sql, $this->dblink);
if (!$result) {
throw new SQLException('Could not execute query', mysql_error($this->dblink), $sql);
}
return new MySQLResultSet($this, $result, $fetchmode);
}
/**
* @see Connection::executeUpdate()
*/
function executeUpdate($sql)
{
$this->lastQuery = $sql;
if ($this->database) {
if (!@mysql_select_db($this->database, $this->dblink)) {
throw new SQLException('No database selected', mysql_error($this->dblink));
}
}
$result = @mysql_query($sql, $this->dblink);
if (!$result) {
throw new SQLException('Could not execute update', mysql_error($this->dblink), $sql);
}
return (int) mysql_affected_rows($this->dblink);
}
/**
* Start a database transaction.
* @throws SQLException
* @return void
*/
protected function beginTrans()
{
$result = @mysql_query('SET AUTOCOMMIT=0', $this->dblink);
$result = @mysql_query('BEGIN', $this->dblink);
if (!$result) {
throw new SQLException('Could not begin transaction', mysql_error($this->dblink));
}
}
/**
* Commit the current transaction.
* @throws SQLException
* @return void
*/
protected function commitTrans()
{
if ($this->database) {
if (!@mysql_select_db($this->database, $this->dblink)) {
throw new SQLException('No database selected', mysql_error($this->dblink));
}
}
$result = @mysql_query('COMMIT', $this->dblink);
$result = @mysql_query('SET AUTOCOMMIT=1', $this->dblink);
if (!$result) {
throw new SQLException('Can not commit transaction', mysql_error($this->dblink));
}
}
/**
* Roll back (undo) the current transaction.
* @throws SQLException
* @return void
*/
protected function rollbackTrans()
{
if ($this->database) {
if (!@mysql_select_db($this->database, $this->dblink)) {
throw new SQLException('No database selected', mysql_error($this->dblink));
}
}
$result = @mysql_query('ROLLBACK', $this->dblink);
$result = @mysql_query('SET AUTOCOMMIT=1', $this->dblink);
if (!$result) {
throw new SQLException('Could not rollback transaction', mysql_error($this->dblink));
}
}
/**
* Gets the number of rows affected by the data manipulation
* query.
*
* @return int Number of rows affected by the last query.
*/
function getUpdateCount()
{
return (int) @mysql_affected_rows($this->dblink);
}
}

View File

@ -0,0 +1,75 @@
<?php
require_once 'creole/IdGenerator.php';
/**
* MySQL IdGenerator implimenation.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.6 $
* @package creole.drivers.mysql
*/
class MySQLIdGenerator implements IdGenerator {
/** Connection object that instantiated this class */
private $conn;
/**
* Creates a new IdGenerator class, saves passed connection for use
* later by getId() method.
* @param Connection $conn
*/
public function __construct(Connection $conn)
{
$this->conn = $conn;
}
/**
* @see IdGenerator::isBeforeInsert()
*/
public function isBeforeInsert()
{
return false;
}
/**
* @see IdGenerator::isAfterInsert()
*/
public function isAfterInsert()
{
return true;
}
/**
* @see IdGenerator::getIdMethod()
*/
public function getIdMethod()
{
return self::AUTOINCREMENT;
}
/**
* Returns last-generated auto-increment ID.
*
* Note that for very large values (2,147,483,648 to 9,223,372,036,854,775,807) a string
* will be returned, because these numbers are larger than supported by PHP's native
* numeric datatypes.
*
* @see IdGenerator::getId()
*/
public function getId($unused = null)
{
$insert_id = mysql_insert_id($this->conn->getResource());
if ( $insert_id < 0 ) {
$insert_id = null;
$result = mysql_query('SELECT LAST_INSERT_ID()', $this->conn->getResource());
if ( $result ) {
$row = mysql_fetch_row($result);
$insert_id = $row ? $row[0] : null;
}
}
return $insert_id;
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* $Id: MySQLPreparedStatement.php,v 1.7 2005/12/10 13:46:55 hlellelid Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/PreparedStatement.php';
require_once 'creole/common/PreparedStatementCommon.php';
/**
* MySQL subclass for prepared statements.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.7 $
* @package creole.drivers.mysql
*/
class MySQLPreparedStatement extends PreparedStatementCommon implements PreparedStatement {
/**
* Quotes string using native mysql function (mysql_real_escape_string()).
* @param string $str
* @return string
*/
protected function escape($str)
{
return mysql_real_escape_string($str, $this->conn->getResource());
}
}

View File

@ -0,0 +1,149 @@
<?php
/*
* $Id: MySQLResultSet.php,v 1.24 2006/01/17 19:44:39 hlellelid Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/ResultSet.php';
require_once 'creole/common/ResultSetCommon.php';
/**
* MySQL implementation of ResultSet class.
*
* MySQL supports OFFSET / LIMIT natively; this means that no adjustments or checking
* are performed. We will assume that if the lmitSQL() operation failed that an
* exception was thrown, and that OFFSET/LIMIT will never be emulated for MySQL.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.24 $
* @package creole.drivers.mysql
*/
class MySQLResultSet extends ResultSetCommon implements ResultSet {
/**
* @see ResultSet::seek()
*/
public function seek($rownum)
{
// MySQL rows start w/ 0, but this works, because we are
// looking to move the position _before_ the next desired position
if (!@mysql_data_seek($this->result, $rownum)) {
return false;
}
$this->cursorPos = $rownum;
return true;
}
/**
* @see ResultSet::next()
*/
public function next()
{
$this->fields = mysql_fetch_array($this->result, $this->fetchmode);
if (!$this->fields) {
$errno = mysql_errno($this->conn->getResource());
if (!$errno) {
// We've advanced beyond end of recordset.
$this->afterLast();
return false;
} else {
throw new SQLException("Error fetching result", mysql_error($this->conn->getResource()));
}
}
if ($this->fetchmode === ResultSet::FETCHMODE_ASSOC && $this->lowerAssocCase) {
$this->fields = array_change_key_case($this->fields, CASE_LOWER);
}
// Advance cursor position
$this->cursorPos++;
return true;
}
/**
* @see ResultSet::getRecordCount()
*/
function getRecordCount()
{
$rows = @mysql_num_rows($this->result);
if ($rows === null) {
throw new SQLException("Error fetching num rows", mysql_error($this->conn->getResource()));
}
return (int) $rows;
}
/**
* @see ResultSet::close()
*/
function close()
{
if(is_resource($this->result))
@mysql_free_result($this->result);
$this->fields = array();
}
/**
* Get string version of column.
* No rtrim() necessary for MySQL, as this happens natively.
* @see ResultSet::getString()
*/
public function getString($column)
{
$idx = (is_int($column) ? $column - 1 : $column);
if (!array_key_exists($idx, $this->fields)) { throw new SQLException("Invalid resultset column: " . $column); }
if ($this->fields[$idx] === null) { return null; }
return (string) $this->fields[$idx];
}
/**
* Returns a unix epoch timestamp based on either a TIMESTAMP or DATETIME field.
* @param mixed $column Column name (string) or index (int) starting with 1.
* @return string
* @throws SQLException - If the column specified is not a valid key in current field array.
*/
function getTimestamp($column, $format='Y-m-d H:i:s')
{
if (is_int($column)) { $column--; } // because Java convention is to start at 1
if (!array_key_exists($column, $this->fields)) { throw new SQLException("Invalid resultset column: " . (is_int($column) ? $column + 1 : $column)); }
if ($this->fields[$column] === null) { return null; }
$ts = strtotime($this->fields[$column]);
if ($ts === -1 || $ts === false) { // in PHP 5.1 return value changes to FALSE
// otherwise it's an ugly MySQL timestamp!
// YYYYMMDDHHMMSS
if (preg_match('/([\d]{4})([\d]{2})([\d]{2})([\d]{2})([\d]{2})([\d]{2})/', $this->fields[$column], $matches)) {
// YYYY MM DD HH MM SS
// $1 $2 $3 $4 $5 $6
$ts = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
}
}
if ($ts === -1 || $ts === false) { // if it's still -1, then there's nothing to be done; use a different method.
throw new SQLException("Unable to convert value at column " . (is_int($column) ? $column + 1 : $column) . " to timestamp: " . $this->fields[$column]);
}
if ($format === null) {
return $ts;
}
if (strpos($format, '%') !== false) {
return strftime($format, $ts);
} else {
return date($format, $ts);
}
}
}

View File

@ -0,0 +1,36 @@
<?php
/*
* $Id: MySQLStatement.php,v 1.1 2004/02/19 02:49:42 hlellelid Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/Statement.php';
require_once 'creole/common/StatementCommon.php';
/**
* MySQL Statement
*
* @author Hans Lellelid <hans@xmpl.org>
* @author Stig Bakken <ssb@fast.no>
* @author Lukas Smith
* @version $Revision: 1.1 $
* @package creole.drivers.mysql
*/
class MySQLStatement extends StatementCommon implements Statement {
}

View File

@ -0,0 +1,102 @@
<?php
/*
* $Id: MySQLTypes.php,v 1.8 2005/02/10 09:22:40 pachanga Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/CreoleTypes.php';
/**
* MySQL types / type map.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.8 $
* @package creole.drivers.mysql
*/
class MySQLTypes extends CreoleTypes {
/** Map MySQL native types to Creole (JDBC) types. */
private static $typeMap = array(
'tinyint' => CreoleTypes::TINYINT,
'smallint' => CreoleTypes::SMALLINT,
'mediumint' => CreoleTypes::SMALLINT,
'int' => CreoleTypes::INTEGER,
'integer' => CreoleTypes::INTEGER,
'bigint' => CreoleTypes::BIGINT,
'int24' => CreoleTypes::BIGINT,
'real' => CreoleTypes::REAL,
'float' => CreoleTypes::FLOAT,
'decimal' => CreoleTypes::DECIMAL,
'numeric' => CreoleTypes::NUMERIC,
'double' => CreoleTypes::DOUBLE,
'char' => CreoleTypes::CHAR,
'varchar' => CreoleTypes::VARCHAR,
'date' => CreoleTypes::DATE,
'time' => CreoleTypes::TIME,
'year' => CreoleTypes::YEAR,
'datetime' => CreoleTypes::TIMESTAMP,
'timestamp' => CreoleTypes::TIMESTAMP,
'tinyblob' => CreoleTypes::BINARY,
'blob' => CreoleTypes::VARBINARY,
'mediumblob' => CreoleTypes::VARBINARY,
'longblob' => CreoleTypes::VARBINARY,
'longtext' => CreoleTypes::LONGVARCHAR,
'tinytext' => CreoleTypes::VARCHAR,
'mediumtext' => CreoleTypes::LONGVARCHAR,
'text' => CreoleTypes::LONGVARCHAR,
'enum' => CreoleTypes::CHAR,
'set' => CreoleTypes::CHAR,
);
/** Reverse mapping, created on demand. */
private static $reverseMap = null;
/**
* This method returns the generic Creole (JDBC-like) type
* when given the native db type.
* @param string $nativeType DB native type (e.g. 'TEXT', 'byetea', etc.).
* @return int Creole native type (e.g. CreoleTypes::LONGVARCHAR, CreoleTypes::BINARY, etc.).
*/
public static function getType($nativeType)
{
$t = strtolower($nativeType);
if (isset(self::$typeMap[$t])) {
return self::$typeMap[$t];
} else {
return CreoleTypes::OTHER;
}
}
/**
* This method will return a native type that corresponds to the specified
* Creole (JDBC-like) type.
* If there is more than one matching native type, then the LAST defined
* native type will be returned.
* @param int $creoleType
* @return string Native type string.
*/
public static function getNativeType($creoleType)
{
if (self::$reverseMap === null) {
self::$reverseMap = array_flip(self::$typeMap);
}
return @self::$reverseMap[$creoleType];
}
}

View File

@ -0,0 +1,66 @@
<?php
/*
* $Id: MySQLDatabaseInfo.php,v 1.13 2006/01/17 19:44:39 hlellelid Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/metadata/DatabaseInfo.php';
/**
* MySQL implementation of DatabaseInfo.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.13 $
* @package creole.drivers.mysql.metadata
*/
class MySQLDatabaseInfo extends DatabaseInfo {
/**
* @throws SQLException
* @return void
*/
protected function initTables()
{
include_once 'creole/drivers/mysql/metadata/MySQLTableInfo.php';
// using $this->dblink was causing tests to break
// perhaps dblink is changed by another test ... ?
$result = @mysql_query("SHOW TABLES FROM `" . $this->dbname . "`", $this->conn->getResource());
if (!$result) {
throw new SQLException("Could not list tables", mysql_error($this->conn->getResource()));
}
while ($row = mysql_fetch_row($result)) {
$this->tables[strtoupper($row[0])] = new MySQLTableInfo($this, $row[0]);
}
$this->tablesLoaded = true;
}
/**
* MySQL does not support sequences.
*
* @return void
* @throws SQLException
*/
protected function initSequences()
{
// throw new SQLException("MySQL does not support sequences natively.");
}
}

View File

@ -0,0 +1,252 @@
<?php
/*
* $Id: MySQLTableInfo.php,v 1.20 2006/01/17 19:44:39 hlellelid Exp $
*
* 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 COPYRIGHT
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>.
*/
require_once 'creole/metadata/TableInfo.php';
/**
* MySQL implementation of TableInfo.
*
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision: 1.20 $
* @package creole.drivers.mysql.metadata
*/
class MySQLTableInfo extends TableInfo {
/** Loads the columns for this table. */
protected function initColumns()
{
include_once 'creole/metadata/ColumnInfo.php';
include_once 'creole/drivers/mysql/MySQLTypes.php';
if (!@mysql_select_db($this->dbname, $this->conn->getResource())) {
throw new SQLException('No database selected');
}
// To get all of the attributes we need, we use
// the MySQL "SHOW COLUMNS FROM $tablename" SQL. We cannot
// use the API functions (e.g. mysql_list_fields() because they
// do not return complete information -- e.g. precision / scale, default
// values).
$res = mysql_query("SHOW COLUMNS FROM `" . $this->name . "`", $this->conn->getResource());
$defaults = array();
$nativeTypes = array();
$precisions = array();
while($row = mysql_fetch_assoc($res)) {
$name = $row['Field'];
$is_nullable = ($row['Null'] == 'YES');
$is_auto_increment = (strpos($row['Extra'], 'auto_increment') !== false);
$size = null;
$precision = null;
$scale = null;
if (preg_match('/^(\w+)[\(]?([\d,]*)[\)]?( |$)/', $row['Type'], $matches)) {
// colname[1] size/precision[2]
$nativeType = $matches[1];
if ($matches[2]) {
if ( ($cpos = strpos($matches[2], ',')) !== false) {
$size = (int) substr($matches[2], 0, $cpos);
$precision = $size;
$scale = (int) substr($matches[2], $cpos + 1);
} else {
$size = (int) $matches[2];
}
}
} elseif (preg_match('/^(\w+)\(/', $row['Type'], $matches)) {
$nativeType = $matches[1];
} else {
$nativeType = $row['Type'];
}
//BLOBs can't have any default values in MySQL
$default = preg_match('~blob|text~', $nativeType) ? null : $row['Default'];
$this->columns[$name] = new ColumnInfo($this,
$name,
MySQLTypes::getType($nativeType),
$nativeType,
$size,
$precision,
$scale,
$is_nullable,
$default,
$is_auto_increment,
$row);
}
$this->colsLoaded = true;
}
/** Loads the primary key information for this table. */
protected function initPrimaryKey()
{
include_once 'creole/metadata/PrimaryKeyInfo.php';
// columns have to be loaded first
if (!$this->colsLoaded) $this->initColumns();
if (!@mysql_select_db($this->dbname, $this->conn->getResource())) {
throw new SQLException('No database selected');
}
// Primary Keys
$res = mysql_query("SHOW KEYS FROM `" . $this->name . "`", $this->conn->getResource());
// Loop through the returned results, grouping the same key_name together
// adding each column for that key.
while($row = mysql_fetch_assoc($res)) {
// Skip any non-primary keys.
if ($row['Key_name'] !== 'PRIMARY') {
continue;
}
$name = $row["Column_name"];
if (!isset($this->primaryKey)) {
$this->primaryKey = new PrimaryKeyInfo($name, $row);
}
$this->primaryKey->addColumn($this->columns[$name]);
}
$this->pkLoaded = true;
}
/** Loads the indexes for this table. */
protected function initIndexes() {
include_once 'creole/metadata/IndexInfo.php';
// columns have to be loaded first
if (!$this->colsLoaded) $this->initColumns();
if (!@mysql_select_db($this->dbname, $this->conn->getResource())) {
throw new SQLException('No database selected');
}
// Indexes
$res = mysql_query("SHOW INDEX FROM `" . $this->name . "`", $this->conn->getResource());
// Loop through the returned results, grouping the same key_name together
// adding each column for that key.
while($row = mysql_fetch_assoc($res)) {
$colName = $row["Column_name"];
$name = $row["Key_name"];
if($name == "PRIMARY") {
continue;
}
if (!isset($this->indexes[$name])) {
$isUnique = ($row["Non_unique"] == 0);
$this->indexes[$name] = new IndexInfo($name, $isUnique, $row);
}
$this->indexes[$name]->addColumn($this->columns[$colName]);
}
$this->indexesLoaded = true;
}
/**
* Load foreign keys for supporting versions of MySQL.
* @author Tony Bibbs
*/
protected function initForeignKeys() {
// First make sure we have supported version of MySQL:
$res = mysql_query("SELECT VERSION()");
$row = mysql_fetch_row($res);
// Yes, it is OK to hardcode this...this was the first version of MySQL
// that supported foreign keys
if ($row[0] < '3.23.44') {
$this->fksLoaded = true;
return;
}
include_once 'creole/metadata/ForeignKeyInfo.php';
// columns have to be loaded first
if (!$this->colsLoaded) $this->initColumns();
if (!@mysql_select_db($this->dbname, $this->conn->getResource())) {
throw new SQLException('No database selected');
}
// Get the CREATE TABLE syntax
$res = mysql_query("SHOW CREATE TABLE `" . $this->name . "`", $this->conn->getResource());
$row = mysql_fetch_row($res);
// Get the information on all the foreign keys
$regEx = '/FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)(.*)/';
if (preg_match_all($regEx,$row[1],$matches)) {
$tmpArray = array_keys($matches[0]);
foreach ($tmpArray as $curKey) {
$name = $matches[1][$curKey];
$ftbl = $matches[2][$curKey];
$fcol = $matches[3][$curKey];
$fkey = $matches[4][$curKey];
if (!isset($this->foreignKeys[$name])) {
$this->foreignKeys[$name] = new ForeignKeyInfo($name);
if ($this->database->hasTable($ftbl)) {
$foreignTable = $this->database->getTable($ftbl);
} else {
$foreignTable = new MySQLTableInfo($this->database, $ftbl);
$this->database->addTable($foreignTable);
}
if ($foreignTable->hasColumn($fcol)) {
$foreignCol = $foreignTable->getColumn($fcol);
} else {
$foreignCol = new ColumnInfo($foreignTable, $fcol);
$foreignTable->addColumn($foreignCol);
}
//typical for mysql is RESTRICT
$fkactions = array(
'ON DELETE' => ForeignKeyInfo::RESTRICT,
'ON UPDATE' => ForeignKeyInfo::RESTRICT,
);
if ($fkey) {
//split foreign key information -> search for ON DELETE and afterwords for ON UPDATE action
foreach (array_keys($fkactions) as $fkaction) {
$result = NULL;
preg_match('/' . $fkaction . ' (' . ForeignKeyInfo::CASCADE . '|' . ForeignKeyInfo::SETNULL . ')/', $fkey, $result);
if ($result && is_array($result) && isset($result[1])) {
$fkactions[$fkaction] = $result[1];
}
}
}
$this->foreignKeys[$name]->addReference($this->columns[$name], $foreignCol, $fkactions['ON DELETE'], $fkactions['ON UPDATE']);
}
}
}
$this->fksLoaded = true;
}
protected function initVendorSpecificInfo()
{
$res = mysql_query("SHOW TABLE STATUS LIKE '" . $this->name . "'", $this->conn->getResource());
$this->vendorSpecificInfo = mysql_fetch_assoc($res);
$this->vendorLoaded = true;
}
}