first commit

This commit is contained in:
alazhar
2020-01-02 22:20:31 +07:00
commit 10eb3340ad
5753 changed files with 631345 additions and 0 deletions

View File

@ -0,0 +1,174 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Database connector class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
* @deprecated 13.3 (Platform) & 4.0 (CMS)
*/
abstract class JDatabase
{
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws RuntimeException
* @deprecated 13.1 (Platform) & 4.0 (CMS)
*/
public function query()
{
JLog::add('JDatabase::query() is deprecated, use JDatabaseDriver::execute() instead.', JLog::WARNING, 'deprecated');
return $this->execute();
}
/**
* Get a list of available database connectors. The list will only be populated with connectors that both
* the class exists and the static test method returns true. This gives us the ability to have a multitude
* of connector classes that are self-aware as to whether or not they are able to be used on a given system.
*
* @return array An array of available database connectors.
*
* @since 11.1
* @deprecated 13.1 (Platform) & 4.0 (CMS)
*/
public static function getConnectors()
{
JLog::add('JDatabase::getConnectors() is deprecated, use JDatabaseDriver::getConnectors() instead.', JLog::WARNING, 'deprecated');
return JDatabaseDriver::getConnectors();
}
/**
* Gets the error message from the database connection.
*
* @param boolean $escaped True to escape the message string for use in JavaScript.
*
* @return string The error message for the most recent query.
*
* @deprecated 13.3 (Platform) & 4.0 (CMS)
* @since 11.1
*/
public function getErrorMsg($escaped = false)
{
JLog::add('JDatabase::getErrorMsg() is deprecated, use exception handling instead.', JLog::WARNING, 'deprecated');
if ($escaped)
{
return addslashes($this->errorMsg);
}
else
{
return $this->errorMsg;
}
}
/**
* Gets the error number from the database connection.
*
* @return integer The error number for the most recent query.
*
* @since 11.1
* @deprecated 13.3 (Platform) & 4.0 (CMS)
*/
public function getErrorNum()
{
JLog::add('JDatabase::getErrorNum() is deprecated, use exception handling instead.', JLog::WARNING, 'deprecated');
return $this->errorNum;
}
/**
* Method to return a JDatabaseDriver instance based on the given options. There are three global options and then
* the rest are specific to the database driver. The 'driver' option defines which JDatabaseDriver class is
* used for the connection -- the default is 'mysqli'. The 'database' option determines which database is to
* be used for the connection. The 'select' option determines whether the connector should automatically select
* the chosen database.
*
* Instances are unique to the given options and new objects are only created when a unique options array is
* passed into the method. This ensures that we don't end up with unnecessary database connection resources.
*
* @param array $options Parameters to be passed to the database driver.
*
* @return JDatabaseDriver A database object.
*
* @since 11.1
* @deprecated 13.1 (Platform) & 4.0 (CMS)
*/
public static function getInstance($options = array())
{
JLog::add('JDatabase::getInstance() is deprecated, use JDatabaseDriver::getInstance() instead.', JLog::WARNING, 'deprecated');
return JDatabaseDriver::getInstance($options);
}
/**
* Splits a string of multiple queries into an array of individual queries.
*
* @param string $query Input SQL string with which to split into individual queries.
*
* @return array The queries from the input string separated into an array.
*
* @since 11.1
* @deprecated 13.1 (Platform) & 4.0 (CMS)
*/
public static function splitSql($query)
{
JLog::add('JDatabase::splitSql() is deprecated, use JDatabaseDriver::splitSql() instead.', JLog::WARNING, 'deprecated');
return JDatabaseDriver::splitSql($query);
}
/**
* Return the most recent error message for the database connector.
*
* @param boolean $showSQL True to display the SQL statement sent to the database as well as the error.
*
* @return string The error message for the most recent query.
*
* @since 11.1
* @deprecated 13.3 (Platform) & 4.0 (CMS)
*/
public function stderr($showSQL = false)
{
JLog::add('JDatabase::stderr() is deprecated.', JLog::WARNING, 'deprecated');
if ($this->errorNum != 0)
{
return JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $this->errorNum, $this->errorMsg)
. ($showSQL ? "<br />SQL = <pre>$this->sql</pre>" : '');
}
else
{
return JText::_('JLIB_DATABASE_FUNCTION_NOERROR');
}
}
/**
* Test to see if the connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
* @deprecated 12.3 (Platform) & 4.0 (CMS) - Use JDatabaseDriver::isSupported() instead.
*/
public static function test()
{
JLog::add('JDatabase::test() is deprecated. Use JDatabaseDriver::isSupported() instead.', JLog::WARNING, 'deprecated');
return static::isSupported();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,463 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQL database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://dev.mysql.com/doc/
* @since 12.1
*/
class JDatabaseDriverMysql extends JDatabaseDriverMysqli
{
/**
* The name of the database driver.
*
* @var string
* @since 12.1
*/
public $name = 'mysql';
/**
* Constructor.
*
* @param array $options Array of database options with keys: host, user, password, database, select.
*
* @since 12.1
*/
public function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
// Finalize initialisation.
parent::__construct($options);
}
/**
* Destructor.
*
* @since 12.1
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Connects to the database if needed.
*
* @return void Returns void if the database connected successfully.
*
* @since 12.1
* @throws RuntimeException
*/
public function connect()
{
if ($this->connection)
{
return;
}
// Make sure the MySQL extension for PHP is installed and enabled.
if (!function_exists('mysql_connect'))
{
throw new RuntimeException('Could not connect to MySQL.');
}
// Attempt to connect to the server.
if (!($this->connection = @ mysql_connect($this->options['host'], $this->options['user'], $this->options['password'], true)))
{
throw new RuntimeException('Could not connect to MySQL.');
}
// Set sql_mode to non_strict mode
mysql_query("SET @@SESSION.sql_mode = '';", $this->connection);
// If auto-select is enabled select the given database.
if ($this->options['select'] && !empty($this->options['database']))
{
$this->select($this->options['database']);
}
// Set charactersets (needed for MySQL 4.1.2+).
$this->setUTF();
// Turn MySQL profiling ON in debug mode:
if ($this->debug && $this->hasProfiling())
{
mysql_query("SET profiling = 1;", $this->connection);
}
}
/**
* Disconnects the database.
*
* @return void
*
* @since 12.1
*/
public function disconnect()
{
// Close the connection.
if (is_resource($this->connection))
{
foreach ($this->disconnectHandlers as $h)
{
call_user_func_array($h, array( &$this));
}
mysql_close($this->connection);
}
$this->connection = null;
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 12.1
*/
public function escape($text, $extra = false)
{
$this->connect();
$result = mysql_real_escape_string($text, $this->getConnection());
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
public static function isSupported()
{
return (function_exists('mysql_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 12.1
*/
public function connected()
{
if (is_resource($this->connection))
{
return @mysql_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 12.1
*/
public function getAffectedRows()
{
$this->connect();
return mysql_affected_rows($this->connection);
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 12.1
*/
public function getNumRows($cursor = null)
{
$this->connect();
return mysql_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 12.1
*/
public function getVersion()
{
$this->connect();
return mysql_get_server_info($this->connection);
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 12.1
*/
public function insertid()
{
$this->connect();
return mysql_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 12.1
* @throws RuntimeException
*/
public function execute()
{
$this->connect();
if (!is_resource($this->connection))
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
// Take a local copy so that we don't modify the original query and cause issues later
$query = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$query .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// Increment the query counter.
$this->count++;
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Add the query to the object queue.
$this->log[] = $query;
JLog::add($query, JLog::DEBUG, 'databasequery');
$this->timings[] = microtime(true);
}
// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
$this->cursor = @mysql_query($query, $this->connection);
if ($this->debug)
{
$this->timings[] = microtime(true);
if (defined('DEBUG_BACKTRACE_IGNORE_ARGS'))
{
$this->callStacks[] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
else
{
$this->callStacks[] = debug_backtrace();
}
}
// If an error occurred handle it.
if (!$this->cursor)
{
// Check if the server was disconnected.
if (!$this->connected())
{
try
{
// Attempt to reconnect.
$this->connection = null;
$this->connect();
}
// If connect fails, ignore that exception and throw the normal exception.
catch (RuntimeException $e)
{
// Get the error number and message.
$this->errorNum = (int) mysql_errno($this->connection);
$this->errorMsg = (string) mysql_error($this->connection) . ' SQL=' . $query;
// Throw the normal query exception.
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
// Since we were able to reconnect, run the query again.
return $this->execute();
}
// The server was not disconnected.
else
{
// Get the error number and message.
$this->errorNum = (int) mysql_errno($this->connection);
$this->errorMsg = (string) mysql_error($this->connection) . ' SQL=' . $query;
// Throw the normal query exception.
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 12.1
* @throws RuntimeException
*/
public function select($database)
{
$this->connect();
if (!$database)
{
return false;
}
if (!mysql_select_db($database, $this->connection))
{
throw new RuntimeException('Could not connect to database');
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 12.1
*/
public function setUTF()
{
$this->connect();
return mysql_set_charset('utf8', $this->connection);
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchArray($cursor = null)
{
return mysql_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchAssoc($cursor = null)
{
return mysql_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysql_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 12.1
*/
protected function freeResult($cursor = null)
{
mysql_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Internal function to check if profiling is available
*
* @return boolean
*
* @since 3.1.3
*/
private function hasProfiling()
{
try
{
$res = mysql_query("SHOW VARIABLES LIKE 'have_profiling'", $this->connection);
$row = mysql_fetch_assoc($res);
return isset($row);
}
catch (Exception $e)
{
return false;
}
}
}

View File

@ -0,0 +1,834 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 12.1
*/
class JDatabaseDriverMysqli extends JDatabaseDriver
{
/**
* The name of the database driver.
*
* @var string
* @since 12.1
*/
public $name = 'mysqli';
/**
* The character(s) used to quote SQL statement names such as table names or field names,
* etc. The child classes should define this as necessary. If a single character string the
* same character is used for both sides of the quoted name, else the first character will be
* used for the opening quote and the second for the closing quote.
*
* @var string
* @since 12.2
*/
protected $nameQuote = '`';
/**
* The null or zero representation of a timestamp for the database driver. This should be
* defined in child classes to hold the appropriate value for the engine.
*
* @var string
* @since 12.2
*/
protected $nullDate = '0000-00-00 00:00:00';
/**
* @var string The minimum supported database version.
* @since 12.2
*/
protected static $dbMinimum = '5.0.4';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 12.1
*/
public function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
// Finalize initialisation.
parent::__construct($options);
}
/**
* Destructor.
*
* @since 12.1
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Connects to the database if needed.
*
* @return void Returns void if the database connected successfully.
*
* @since 12.1
* @throws RuntimeException
*/
public function connect()
{
if ($this->connection)
{
return;
}
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($this->options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$this->options['port'] = $tmp;
}
else
{
$this->options['socket'] = $tmp;
}
// Extract the host name only
$this->options['host'] = substr($this->options['host'], 0, strlen($this->options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($this->options['host'] == '')
{
$this->options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
throw new RuntimeException('The MySQL adapter mysqli is not available');
}
$this->connection = @mysqli_connect(
$this->options['host'], $this->options['user'], $this->options['password'], null, $this->options['port'], $this->options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
throw new RuntimeException('Could not connect to MySQL.');
}
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($this->options['select'] && !empty($this->options['database']))
{
$this->select($this->options['database']);
}
// Set charactersets (needed for MySQL 4.1.2+).
$this->setUTF();
// Turn MySQL profiling ON in debug mode:
if ($this->debug && $this->hasProfiling())
{
mysqli_query($this->connection, "SET profiling_history_size = 100;");
mysqli_query($this->connection, "SET profiling = 1;");
}
}
/**
* Disconnects the database.
*
* @return void
*
* @since 12.1
*/
public function disconnect()
{
// Close the connection.
if ($this->connection)
{
foreach ($this->disconnectHandlers as $h)
{
call_user_func_array($h, array( &$this));
}
mysqli_close($this->connection);
}
$this->connection = null;
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 12.1
*/
public function escape($text, $extra = false)
{
$this->connect();
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
public static function isSupported()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 12.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Drops a table from the database.
*
* @param string $tableName The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
*
* @return JDatabaseDriverMysqli Returns this object to support chaining.
*
* @since 12.2
* @throws RuntimeException
*/
public function dropTable($tableName, $ifExists = true)
{
$this->connect();
$query = $this->getQuery(true);
$this->setQuery('DROP TABLE ' . ($ifExists ? 'IF EXISTS ' : '') . $query->quoteName($tableName));
$this->execute();
return $this;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 12.1
*/
public function getAffectedRows()
{
$this->connect();
return mysqli_affected_rows($this->connection);
}
/**
* Method to get the database collation in use by sampling a text field of a table in the database.
*
* @return mixed The collation in use by the database (string) or boolean false if not supported.
*
* @since 12.2
* @throws RuntimeException
*/
public function getCollation()
{
$this->connect();
$tables = $this->getTableList();
$this->setQuery('SHOW FULL COLUMNS FROM ' . $tables[0]);
$array = $this->loadAssocList();
foreach ($array as $field)
{
if (!is_null($field['Collation']))
{
return $field['Collation'];
}
}
return null;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 12.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Shows the table CREATE statement that creates the given tables.
*
* @param mixed $tables A table name or a list of table names.
*
* @return array A list of the create SQL for the tables.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableCreate($tables)
{
$this->connect();
$result = array();
// Sanitize input to an array and iterate over the list.
settype($tables, 'array');
foreach ($tables as $table)
{
// Set the query to get the table CREATE statement.
$this->setQuery('SHOW CREATE table ' . $this->quoteName($this->escape($table)));
$row = $this->loadRow();
// Populate the result array based on the create statements.
$result[$table] = $row[1];
}
return $result;
}
/**
* Retrieves field information about a given table.
*
* @param string $table The name of the database table.
* @param boolean $typeOnly True to only return field types.
*
* @return array An array of fields for the database table.
*
* @since 12.2
* @throws RuntimeException
*/
public function getTableColumns($table, $typeOnly = true)
{
$this->connect();
$result = array();
// Set the query to get the table fields statement.
$this->setQuery('SHOW FULL COLUMNS FROM ' . $this->quoteName($this->escape($table)));
$fields = $this->loadObjectList();
// If we only want the type as the value add just that to the list.
if ($typeOnly)
{
foreach ($fields as $field)
{
$result[$field->Field] = preg_replace("/[(0-9)]/", '', $field->Type);
}
}
// If we want the whole field data object add that to the list.
else
{
foreach ($fields as $field)
{
$result[$field->Field] = $field;
}
}
return $result;
}
/**
* Get the details list of keys for a table.
*
* @param string $table The name of the table.
*
* @return array An array of the column specification for the table.
*
* @since 12.2
* @throws RuntimeException
*/
public function getTableKeys($table)
{
$this->connect();
// Get the details columns information.
$this->setQuery('SHOW KEYS FROM ' . $this->quoteName($table));
$keys = $this->loadObjectList();
return $keys;
}
/**
* Method to get an array of all tables in the database.
*
* @return array An array of all the tables in the database.
*
* @since 12.2
* @throws RuntimeException
*/
public function getTableList()
{
$this->connect();
// Set the query to get the tables statement.
$this->setQuery('SHOW TABLES');
$tables = $this->loadColumn();
return $tables;
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 12.1
*/
public function getVersion()
{
$this->connect();
return mysqli_get_server_info($this->connection);
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return mixed The value of the auto-increment field from the last inserted row.
* If the value is greater than maximal int value, it will return a string.
*
* @since 12.1
*/
public function insertid()
{
$this->connect();
return mysqli_insert_id($this->connection);
}
/**
* Locks a table in the database.
*
* @param string $table The name of the table to unlock.
*
* @return JDatabaseDriverMysqli Returns this object to support chaining.
*
* @since 12.2
* @throws RuntimeException
*/
public function lockTable($table)
{
$this->setQuery('LOCK TABLES ' . $this->quoteName($table) . ' WRITE')->execute();
return $this;
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 12.1
* @throws RuntimeException
*/
public function execute()
{
$this->connect();
if (!is_object($this->connection))
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
// Take a local copy so that we don't modify the original query and cause issues later
$query = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$query .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// Increment the query counter.
$this->count++;
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
$memoryBefore = null;
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Add the query to the object queue.
$this->log[] = $query;
JLog::add($query, JLog::DEBUG, 'databasequery');
$this->timings[] = microtime(true);
if (is_object($this->cursor))
{
$this->freeResult();
}
$memoryBefore = memory_get_usage();
}
// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
$this->cursor = @mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->timings[] = microtime(true);
if (defined('DEBUG_BACKTRACE_IGNORE_ARGS'))
{
$this->callStacks[] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
}
else
{
$this->callStacks[] = debug_backtrace();
}
$this->callStacks[count($this->callStacks) - 1][0]['memory'] = array($memoryBefore, memory_get_usage(), is_object($this->cursor) ? $this->getNumRows() : null);
}
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $query;
// Check if the server was disconnected.
if (!$this->connected())
{
try
{
// Attempt to reconnect.
$this->connection = null;
$this->connect();
}
// If connect fails, ignore that exception and throw the normal exception.
catch (RuntimeException $e)
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
// Since we were able to reconnect, run the query again.
return $this->execute();
}
// The server was not disconnected.
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new RuntimeException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Not used by MySQL.
* @param string $prefix Not used by MySQL.
*
* @return JDatabaseDriverMysqli Returns this object to support chaining.
*
* @since 12.2
* @throws RuntimeException
*/
public function renameTable($oldTable, $newTable, $backup = null, $prefix = null)
{
$this->setQuery('RENAME TABLE ' . $oldTable . ' TO ' . $newTable)->execute();
return $this;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 12.1
* @throws RuntimeException
*/
public function select($database)
{
$this->connect();
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
throw new RuntimeException('Could not connect to database.');
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 12.1
*/
public function setUTF()
{
$this->connect();
return $this->connection->set_charset('utf8');
}
/**
* Method to commit a transaction.
*
* @param boolean $toSavepoint If true, commit to the last savepoint.
*
* @return void
*
* @since 12.2
* @throws RuntimeException
*/
public function transactionCommit($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
if ($this->setQuery('COMMIT')->execute())
{
$this->transactionDepth = 0;
}
return;
}
$this->transactionDepth--;
}
/**
* Method to roll back a transaction.
*
* @param boolean $toSavepoint If true, rollback to the last savepoint.
*
* @return void
*
* @since 12.2
* @throws RuntimeException
*/
public function transactionRollback($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
if ($this->setQuery('ROLLBACK')->execute())
{
$this->transactionDepth = 0;
}
return;
}
$savepoint = 'SP_' . ($this->transactionDepth - 1);
$this->setQuery('ROLLBACK TO SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth--;
}
}
/**
* Method to initialize a transaction.
*
* @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
*
* @return void
*
* @since 12.2
* @throws RuntimeException
*/
public function transactionStart($asSavepoint = false)
{
$this->connect();
if (!$asSavepoint || !$this->transactionDepth)
{
if ($this->setQuery('START TRANSACTION')->execute())
{
$this->transactionDepth = 1;
}
return;
}
$savepoint = 'SP_' . $this->transactionDepth;
$this->setQuery('SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth++;
}
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 12.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
if ((! $cursor) || ($cursor === $this->cursor))
{
$this->cursor = null;
}
}
/**
* Unlocks tables in the database.
*
* @return JDatabaseDriverMysqli Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function unlockTables()
{
$this->setQuery('UNLOCK TABLES')->execute();
return $this;
}
/**
* Internal function to check if profiling is available
*
* @return boolean
*
* @since 3.1.3
*/
private function hasProfiling()
{
try
{
$res = mysqli_query($this->connection, "SHOW VARIABLES LIKE 'have_profiling'");
$row = mysqli_fetch_assoc($res);
return isset($row);
}
catch (Exception $e)
{
return false;
}
}
}

View File

@ -0,0 +1,680 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Oracle database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/pdo
* @since 12.1
*/
class JDatabaseDriverOracle extends JDatabaseDriverPdo
{
/**
* The name of the database driver.
*
* @var string
* @since 12.1
*/
public $name = 'oracle';
/**
* The character(s) used to quote SQL statement names such as table names or field names,
* etc. The child classes should define this as necessary. If a single character string the
* same character is used for both sides of the quoted name, else the first character will be
* used for the opening quote and the second for the closing quote.
*
* @var string
* @since 12.1
*/
protected $nameQuote = '"';
/**
* Returns the current dateformat
*
* @var string
* @since 12.1
*/
protected $dateformat;
/**
* Returns the current character set
*
* @var string
* @since 12.1
*/
protected $charset;
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 12.1
*/
public function __construct($options)
{
$options['driver'] = 'oci';
$options['charset'] = (isset($options['charset'])) ? $options['charset'] : 'AL32UTF8';
$options['dateformat'] = (isset($options['dateformat'])) ? $options['dateformat'] : 'RRRR-MM-DD HH24:MI:SS';
$this->charset = $options['charset'];
$this->dateformat = $options['dateformat'];
// Finalize initialisation
parent::__construct($options);
}
/**
* Destructor.
*
* @since 12.1
*/
public function __destruct()
{
$this->freeResult();
unset($this->connection);
}
/**
* Connects to the database if needed.
*
* @return void Returns void if the database connected successfully.
*
* @since 12.1
* @throws RuntimeException
*/
public function connect()
{
if ($this->connection)
{
return;
}
parent::connect();
if (isset($this->options['schema']))
{
$this->setQuery('ALTER SESSION SET CURRENT_SCHEMA = ' . $this->quoteName($this->options['schema']))->execute();
}
$this->setDateFormat($this->dateformat);
}
/**
* Disconnects the database.
*
* @return void
*
* @since 12.1
*/
public function disconnect()
{
// Close the connection.
$this->freeResult();
unset($this->connection);
}
/**
* Drops a table from the database.
*
* Note: The IF EXISTS flag is unused in the Oracle driver.
*
* @param string $tableName The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
*
* @return JDatabaseDriverOracle Returns this object to support chaining.
*
* @since 12.1
*/
public function dropTable($tableName, $ifExists = true)
{
$this->connect();
$query = $this->getQuery(true)
->setQuery('DROP TABLE :tableName');
$query->bind(':tableName', $tableName);
$this->setQuery($query);
$this->execute();
return $this;
}
/**
* Method to get the database collation in use by sampling a text field of a table in the database.
*
* @return mixed The collation in use by the database or boolean false if not supported.
*
* @since 12.1
*/
public function getCollation()
{
return $this->charset;
}
/**
* Get a query to run and verify the database is operational.
*
* @return string The query to check the health of the DB.
*
* @since 12.2
*/
public function getConnectedQuery()
{
return 'SELECT 1 FROM dual';
}
/**
* Returns the current date format
* This method should be useful in the case that
* somebody actually wants to use a different
* date format and needs to check what the current
* one is to see if it needs to be changed.
*
* @return string The current date format
*
* @since 12.1
*/
public function getDateFormat()
{
return $this->dateformat;
}
/**
* Shows the table CREATE statement that creates the given tables.
*
* Note: You must have the correct privileges before this method
* will return usable results!
*
* @param mixed $tables A table name or a list of table names.
*
* @return array A list of the create SQL for the tables.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableCreate($tables)
{
$this->connect();
$result = array();
$query = $this->getQuery(true)
->select('dbms_metadata.get_ddl(:type, :tableName)')
->from('dual')
->bind(':type', 'TABLE');
// Sanitize input to an array and iterate over the list.
settype($tables, 'array');
foreach ($tables as $table)
{
$query->bind(':tableName', $table);
$this->setQuery($query);
$statement = (string) $this->loadResult();
$result[$table] = $statement;
}
return $result;
}
/**
* Retrieves field information about a given table.
*
* @param string $table The name of the database table.
* @param boolean $typeOnly True to only return field types.
*
* @return array An array of fields for the database table.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableColumns($table, $typeOnly = true)
{
$this->connect();
$columns = array();
$query = $this->getQuery(true);
$fieldCasing = $this->getOption(PDO::ATTR_CASE);
$this->setOption(PDO::ATTR_CASE, PDO::CASE_UPPER);
$table = strtoupper($table);
$query->select('*');
$query->from('ALL_TAB_COLUMNS');
$query->where('table_name = :tableName');
$prefixedTable = str_replace('#__', strtoupper($this->tablePrefix), $table);
$query->bind(':tableName', $prefixedTable);
$this->setQuery($query);
$fields = $this->loadObjectList();
if ($typeOnly)
{
foreach ($fields as $field)
{
$columns[$field->COLUMN_NAME] = $field->DATA_TYPE;
}
}
else
{
foreach ($fields as $field)
{
$columns[$field->COLUMN_NAME] = $field;
$columns[$field->COLUMN_NAME]->Default = null;
}
}
$this->setOption(PDO::ATTR_CASE, $fieldCasing);
return $columns;
}
/**
* Get the details list of keys for a table.
*
* @param string $table The name of the table.
*
* @return array An array of the column specification for the table.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableKeys($table)
{
$this->connect();
$query = $this->getQuery(true);
$fieldCasing = $this->getOption(PDO::ATTR_CASE);
$this->setOption(PDO::ATTR_CASE, PDO::CASE_UPPER);
$table = strtoupper($table);
$query->select('*')
->from('ALL_CONSTRAINTS')
->where('table_name = :tableName')
->bind(':tableName', $table);
$this->setQuery($query);
$keys = $this->loadObjectList();
$this->setOption(PDO::ATTR_CASE, $fieldCasing);
return $keys;
}
/**
* Method to get an array of all tables in the database (schema).
*
* @param string $databaseName The database (schema) name
* @param boolean $includeDatabaseName Whether to include the schema name in the results
*
* @return array An array of all the tables in the database.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableList($databaseName = null, $includeDatabaseName = false)
{
$this->connect();
$query = $this->getQuery(true);
if ($includeDatabaseName)
{
$query->select('owner, table_name');
}
else
{
$query->select('table_name');
}
$query->from('all_tables');
if ($databaseName)
{
$query->where('owner = :database')
->bind(':database', $databaseName);
}
$query->order('table_name');
$this->setQuery($query);
if ($includeDatabaseName)
{
$tables = $this->loadAssocList();
}
else
{
$tables = $this->loadColumn();
}
return $tables;
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 12.1
*/
public function getVersion()
{
$this->connect();
$this->setQuery("select value from nls_database_parameters where parameter = 'NLS_RDBMS_VERSION'");
return $this->loadResult();
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 12.1
* @throws RuntimeException
*/
public function select($database)
{
$this->connect();
return true;
}
/**
* Sets the Oracle Date Format for the session
* Default date format for Oracle is = DD-MON-RR
* The default date format for this driver is:
* 'RRRR-MM-DD HH24:MI:SS' since it is the format
* that matches the MySQL one used within most Joomla
* tables.
*
* @param string $dateFormat Oracle Date Format String
*
* @return boolean
*
* @since 12.1
*/
public function setDateFormat($dateFormat = 'DD-MON-RR')
{
$this->connect();
$this->setQuery("ALTER SESSION SET NLS_DATE_FORMAT = '$dateFormat'");
if (!$this->execute())
{
return false;
}
$this->setQuery("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = '$dateFormat'");
if (!$this->execute())
{
return false;
}
$this->dateformat = $dateFormat;
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* Returns false automatically for the Oracle driver since
* you can only set the character set when the connection
* is created.
*
* @return boolean True on success.
*
* @since 12.1
*/
public function setUTF()
{
return false;
}
/**
* Locks a table in the database.
*
* @param string $table The name of the table to unlock.
*
* @return JDatabaseDriverOracle Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function lockTable($table)
{
$this->setQuery('LOCK TABLE ' . $this->quoteName($table) . ' IN EXCLUSIVE MODE')->execute();
return $this;
}
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Not used by Oracle.
* @param string $prefix Not used by Oracle.
*
* @return JDatabaseDriverOracle Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function renameTable($oldTable, $newTable, $backup = null, $prefix = null)
{
$this->setQuery('RENAME ' . $oldTable . ' TO ' . $newTable)->execute();
return $this;
}
/**
* Unlocks tables in the database.
*
* @return JDatabaseDriverOracle Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function unlockTables()
{
$this->setQuery('COMMIT')->execute();
return $this;
}
/**
* Test to see if the PDO ODBC connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
public static function isSupported()
{
return class_exists('PDO') && in_array('oci', PDO::getAvailableDrivers());
}
/**
* This function replaces a string identifier <var>$prefix</var> with the string held is the
* <var>tablePrefix</var> class variable.
*
* @param string $query The SQL statement to prepare.
* @param string $prefix The common table prefix.
*
* @return string The processed SQL statement.
*
* @since 11.1
*/
public function replacePrefix($query, $prefix = '#__')
{
$startPos = 0;
$quoteChar = "'";
$literal = '';
$query = trim($query);
$n = strlen($query);
while ($startPos < $n)
{
$ip = strpos($query, $prefix, $startPos);
if ($ip === false)
{
break;
}
$j = strpos($query, "'", $startPos);
if ($j === false)
{
$j = $n;
}
$literal .= str_replace($prefix, $this->tablePrefix, substr($query, $startPos, $j - $startPos));
$startPos = $j;
$j = $startPos + 1;
if ($j >= $n)
{
break;
}
// Quote comes first, find end of quote
while (true)
{
$k = strpos($query, $quoteChar, $j);
$escaped = false;
if ($k === false)
{
break;
}
$l = $k - 1;
while ($l >= 0 && $query{$l} == '\\')
{
$l--;
$escaped = !$escaped;
}
if ($escaped)
{
$j = $k + 1;
continue;
}
break;
}
if ($k === false)
{
// Error in the query - no end quote; ignore it
break;
}
$literal .= substr($query, $startPos, $k - $startPos + 1);
$startPos = $k + 1;
}
if ($startPos < $n)
{
$literal .= substr($query, $startPos, $n - $startPos);
}
return $literal;
}
/**
* Method to commit a transaction.
*
* @param boolean $toSavepoint If true, commit to the last savepoint.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionCommit($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
parent::transactionCommit($toSavepoint);
}
else
{
$this->transactionDepth--;
}
}
/**
* Method to roll back a transaction.
*
* @param boolean $toSavepoint If true, rollback to the last savepoint.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionRollback($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
parent::transactionRollback($toSavepoint);
}
else
{
$savepoint = 'SP_' . ($this->transactionDepth - 1);
$this->setQuery('ROLLBACK TO SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth--;
}
}
}
/**
* Method to initialize a transaction.
*
* @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionStart($asSavepoint = false)
{
$this->connect();
if (!$asSavepoint || !$this->transactionDepth)
{
return parent::transactionStart($asSavepoint);
}
$savepoint = 'SP_' . $this->transactionDepth;
$this->setQuery('SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth++;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQL Server database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://msdn.microsoft.com/en-us/library/ee336279.aspx
* @since 12.1
*/
class JDatabaseDriverSqlazure extends JDatabaseDriverSqlsrv
{
/**
* The name of the database driver.
*
* @var string
* @since 12.1
*/
public $name = 'sqlzure';
}

View File

@ -0,0 +1,464 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQLite database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/pdo
* @since 12.1
*/
class JDatabaseDriverSqlite extends JDatabaseDriverPdo
{
/**
* The name of the database driver.
*
* @var string
* @since 12.1
*/
public $name = 'sqlite';
/**
* The character(s) used to quote SQL statement names such as table names or field names,
* etc. The child classes should define this as necessary. If a single character string the
* same character is used for both sides of the quoted name, else the first character will be
* used for the opening quote and the second for the closing quote.
*
* @var string
* @since 12.1
*/
protected $nameQuote = '`';
/**
* Destructor.
*
* @since 12.1
*/
public function __destruct()
{
$this->freeResult();
unset($this->connection);
}
/**
* Disconnects the database.
*
* @return void
*
* @since 12.1
*/
public function disconnect()
{
$this->freeResult();
unset($this->connection);
}
/**
* Drops a table from the database.
*
* @param string $tableName The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
*
* @return JDatabaseDriverSqlite Returns this object to support chaining.
*
* @since 12.1
*/
public function dropTable($tableName, $ifExists = true)
{
$this->connect();
$query = $this->getQuery(true);
$this->setQuery('DROP TABLE ' . ($ifExists ? 'IF EXISTS ' : '') . $query->quoteName($tableName));
$this->execute();
return $this;
}
/**
* Method to escape a string for usage in an SQLite statement.
*
* Note: Using query objects with bound variables is
* preferable to the below.
*
* @param string $text The string to be escaped.
* @param boolean $extra Unused optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 12.1
*/
public function escape($text, $extra = false)
{
if (is_int($text) || is_float($text))
{
return $text;
}
return SQLite3::escapeString($text);
}
/**
* Method to get the database collation in use by sampling a text field of a table in the database.
*
* @return mixed The collation in use by the database or boolean false if not supported.
*
* @since 12.1
*/
public function getCollation()
{
return $this->charset;
}
/**
* Shows the table CREATE statement that creates the given tables.
*
* Note: Doesn't appear to have support in SQLite
*
* @param mixed $tables A table name or a list of table names.
*
* @return array A list of the create SQL for the tables.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableCreate($tables)
{
$this->connect();
// Sanitize input to an array and iterate over the list.
settype($tables, 'array');
return $tables;
}
/**
* Retrieves field information about a given table.
*
* @param string $table The name of the database table.
* @param boolean $typeOnly True to only return field types.
*
* @return array An array of fields for the database table.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableColumns($table, $typeOnly = true)
{
$this->connect();
$columns = array();
$query = $this->getQuery(true);
$fieldCasing = $this->getOption(PDO::ATTR_CASE);
$this->setOption(PDO::ATTR_CASE, PDO::CASE_UPPER);
$table = strtoupper($table);
$query->setQuery('pragma table_info(' . $table . ')');
$this->setQuery($query);
$fields = $this->loadObjectList();
if ($typeOnly)
{
foreach ($fields as $field)
{
$columns[$field->NAME] = $field->TYPE;
}
}
else
{
foreach ($fields as $field)
{
// Do some dirty translation to MySQL output.
// TODO: Come up with and implement a standard across databases.
$columns[$field->NAME] = (object) array(
'Field' => $field->NAME,
'Type' => $field->TYPE,
'Null' => ($field->NOTNULL == '1' ? 'NO' : 'YES'),
'Default' => $field->DFLT_VALUE,
'Key' => ($field->PK == '1' ? 'PRI' : '')
);
}
}
$this->setOption(PDO::ATTR_CASE, $fieldCasing);
return $columns;
}
/**
* Get the details list of keys for a table.
*
* @param string $table The name of the table.
*
* @return array An array of the column specification for the table.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableKeys($table)
{
$this->connect();
$keys = array();
$query = $this->getQuery(true);
$fieldCasing = $this->getOption(PDO::ATTR_CASE);
$this->setOption(PDO::ATTR_CASE, PDO::CASE_UPPER);
$table = strtoupper($table);
$query->setQuery('pragma table_info( ' . $table . ')');
// $query->bind(':tableName', $table);
$this->setQuery($query);
$rows = $this->loadObjectList();
foreach ($rows as $column)
{
if ($column->PK == 1)
{
$keys[$column->NAME] = $column;
}
}
$this->setOption(PDO::ATTR_CASE, $fieldCasing);
return $keys;
}
/**
* Method to get an array of all tables in the database (schema).
*
* @return array An array of all the tables in the database.
*
* @since 12.1
* @throws RuntimeException
*/
public function getTableList()
{
$this->connect();
$type = 'table';
$query->$this->getQuery(true)
->select('name')
->from('sqlite_master')
->where('type = :type')
->bind(':type', $type)
->order('name');
$this->setQuery($query);
$tables = $this->loadColumn();
return $tables;
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 12.1
*/
public function getVersion()
{
$this->connect();
$this->setQuery("SELECT sqlite_version()");
return $this->loadResult();
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 12.1
* @throws RuntimeException
*/
public function select($database)
{
$this->connect();
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* Returns false automatically for the Oracle driver since
* you can only set the character set when the connection
* is created.
*
* @return boolean True on success.
*
* @since 12.1
*/
public function setUTF()
{
$this->connect();
return false;
}
/**
* Locks a table in the database.
*
* @param string $table The name of the table to unlock.
*
* @return JDatabaseDriverSqlite Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function lockTable($table)
{
return $this;
}
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Not used by Sqlite.
* @param string $prefix Not used by Sqlite.
*
* @return JDatabaseDriverSqlite Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function renameTable($oldTable, $newTable, $backup = null, $prefix = null)
{
$this->setQuery('ALTER TABLE ' . $oldTable . ' RENAME TO ' . $newTable)->execute();
return $this;
}
/**
* Unlocks tables in the database.
*
* @return JDatabaseDriverSqlite Returns this object to support chaining.
*
* @since 12.1
* @throws RuntimeException
*/
public function unlockTables()
{
return $this;
}
/**
* Test to see if the PDO ODBC connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
public static function isSupported()
{
return class_exists('PDO') && in_array('sqlite', PDO::getAvailableDrivers());
}
/**
* Method to commit a transaction.
*
* @param boolean $toSavepoint If true, commit to the last savepoint.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionCommit($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
parent::transactionCommit($toSavepoint);
}
else
{
$this->transactionDepth--;
}
}
/**
* Method to roll back a transaction.
*
* @param boolean $toSavepoint If true, rollback to the last savepoint.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionRollback($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1)
{
parent::transactionRollback($toSavepoint);
}
else
{
$savepoint = 'SP_' . ($this->transactionDepth - 1);
$this->setQuery('ROLLBACK TO ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth--;
}
}
}
/**
* Method to initialize a transaction.
*
* @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
*
* @return void
*
* @since 12.3
* @throws RuntimeException
*/
public function transactionStart($asSavepoint = false)
{
$this->connect();
if (!$asSavepoint || !$this->transactionDepth)
{
parent::transactionStart($asSavepoint);
}
$savepoint = 'SP_' . $this->transactionDepth;
$this->setQuery('SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute())
{
$this->transactionDepth++;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Platform Database Exporter Class
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
abstract class JDatabaseExporter
{
}

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,62 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQL export driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseExporterMysql extends JDatabaseExporterMysqli
{
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseExporterMySQL Method supports chaining.
*
* @since 11.1
*
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverMysql))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Sets the database connector to use for exporting structure and/or data from MySQL.
*
* @param JDatabaseDriverMysql $db The database connector.
*
* @return JDatabaseExporterMysql Method supports chaining.
*
* @since 11.1
*/
public function setDbo(JDatabaseDriverMysql $db)
{
$this->db = $db;
return $this;
}
}

View File

@ -0,0 +1,287 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQLi export driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseExporterMysqli extends JDatabaseExporter
{
/**
* An array of cached data.
*
* @var array
* @since 11.1
*/
protected $cache = array();
/**
* The database connector to use for exporting structure and/or data.
*
* @var JDatabaseDriverMysql
* @since 11.1
*/
protected $db = null;
/**
* An array input sources (table names).
*
* @var array
* @since 11.1
*/
protected $from = array();
/**
* The type of output format (xml).
*
* @var string
* @since 11.1
*/
protected $asFormat = 'xml';
/**
* An array of options for the exporter.
*
* @var object
* @since 11.1
*/
protected $options = null;
/**
* Constructor.
*
* Sets up the default options for the exporter.
*
* @since 11.1
*/
public function __construct()
{
$this->options = new stdClass;
$this->cache = array('columns' => array(), 'keys' => array());
// Set up the class defaults:
// Export with only structure
$this->withStructure();
// Export as xml.
$this->asXml();
// Default destination is a string using $output = (string) $exporter;
}
/**
* Magic function to exports the data to a string.
*
* @return string
*
* @since 11.1
* @throws Exception if an error is encountered.
*/
public function __toString()
{
// Check everything is ok to run first.
$this->check();
return $this->buildXml();
}
/**
* Set the output option for the exporter to XML format.
*
* @return JDatabaseExporterMySQL Method supports chaining.
*
* @since 11.1
*/
public function asXml()
{
$this->asFormat = 'xml';
return $this;
}
/**
* Builds the XML data for the tables to export.
*
* @return string An XML string
*
* @since 11.1
* @throws Exception if an error occurs.
*/
protected function buildXml()
{
$buffer = array();
$buffer[] = '<?xml version="1.0"?>';
$buffer[] = '<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
$buffer[] = ' <database name="">';
$buffer = array_merge($buffer, $this->buildXmlStructure());
$buffer[] = ' </database>';
$buffer[] = '</mysqldump>';
return implode("\n", $buffer);
}
/**
* Builds the XML structure to export.
*
* @return array An array of XML lines (strings).
*
* @since 11.1
* @throws Exception if an error occurs.
*/
protected function buildXmlStructure()
{
$buffer = array();
foreach ($this->from as $table)
{
// Replace the magic prefix if found.
$table = $this->getGenericTableName($table);
// Get the details columns information.
$fields = $this->db->getTableColumns($table, false);
$keys = $this->db->getTableKeys($table);
$buffer[] = ' <table_structure name="' . $table . '">';
foreach ($fields as $field)
{
$buffer[] = ' <field Field="' . $field->Field . '"' . ' Type="' . $field->Type . '"' . ' Null="' . $field->Null . '"' . ' Key="' .
$field->Key . '"' . (isset($field->Default) ? ' Default="' . $field->Default . '"' : '') . ' Extra="' . $field->Extra . '"' .
' />';
}
foreach ($keys as $key)
{
$buffer[] = ' <key Table="' . $table . '"' . ' Non_unique="' . $key->Non_unique . '"' . ' Key_name="' . $key->Key_name . '"' .
' Seq_in_index="' . $key->Seq_in_index . '"' . ' Column_name="' . $key->Column_name . '"' . ' Collation="' . $key->Collation . '"' .
' Null="' . $key->Null . '"' . ' Index_type="' . $key->Index_type . '"' . ' Comment="' . htmlspecialchars($key->Comment) . '"' .
' />';
}
$buffer[] = ' </table_structure>';
}
return $buffer;
}
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseExporterMysqli Method supports chaining.
*
* @since 11.1
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverMysqli))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Get the generic name of the table, converting the database prefix to the wildcard string.
*
* @param string $table The name of the table.
*
* @return string The name of the table with the database prefix replaced with #__.
*
* @since 11.1
*/
protected function getGenericTableName($table)
{
// TODO Incorporate into parent class and use $this.
$prefix = $this->db->getPrefix();
// Replace the magic prefix if found.
$table = preg_replace("|^$prefix|", '#__', $table);
return $table;
}
/**
* Specifies a list of table names to export.
*
* @param mixed $from The name of a single table, or an array of the table names to export.
*
* @return JDatabaseExporterMysql Method supports chaining.
*
* @since 11.1
* @throws Exception if input is not a string or array.
*/
public function from($from)
{
if (is_string($from))
{
$this->from = array($from);
}
elseif (is_array($from))
{
$this->from = $from;
}
else
{
throw new Exception('JPLATFORM_ERROR_INPUT_REQUIRES_STRING_OR_ARRAY');
}
return $this;
}
/**
* Sets the database connector to use for exporting structure and/or data from MySQL.
*
* @param JDatabaseDriverMysqli $db The database connector.
*
* @return JDatabaseExporterMysqli Method supports chaining.
*
* @since 11.1
*/
public function setDbo(JDatabaseDriverMysqli $db)
{
$this->db = $db;
return $this;
}
/**
* Sets an internal option to export the structure of the input table(s).
*
* @param boolean $setting True to export the structure, false to not.
*
* @return JDatabaseExporterMysql Method supports chaining.
*
* @since 11.1
*/
public function withStructure($setting = true)
{
$this->options->withStructure = (boolean) $setting;
return $this;
}
}

View File

@ -0,0 +1,302 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* PostgreSQL export driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseExporterPostgresql extends JDatabaseExporter
{
/**
* An array of cached data.
*
* @var array
* @since 12.1
*/
protected $cache = array();
/**
* The database connector to use for exporting structure and/or data.
*
* @var JDatabaseDriverPostgresql
* @since 12.1
*/
protected $db = null;
/**
* An array input sources (table names).
*
* @var array
* @since 12.1
*/
protected $from = array();
/**
* The type of output format (xml).
*
* @var string
* @since 12.1
*/
protected $asFormat = 'xml';
/**
* An array of options for the exporter.
*
* @var object
* @since 12.1
*/
protected $options = null;
/**
* Constructor.
*
* Sets up the default options for the exporter.
*
* @since 12.1
*/
public function __construct()
{
$this->options = new stdClass;
$this->cache = array('columns' => array(), 'keys' => array());
// Set up the class defaults:
// Export with only structure
$this->withStructure();
// Export as xml.
$this->asXml();
// Default destination is a string using $output = (string) $exporter;
}
/**
* Magic function to exports the data to a string.
*
* @return string
*
* @since 12.1
* @throws Exception if an error is encountered.
*/
public function __toString()
{
// Check everything is ok to run first.
$this->check();
return $this->buildXml();
}
/**
* Set the output option for the exporter to XML format.
*
* @return JDatabaseExporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function asXml()
{
$this->asFormat = 'xml';
return $this;
}
/**
* Builds the XML data for the tables to export.
*
* @return string An XML string
*
* @since 12.1
* @throws Exception if an error occurs.
*/
protected function buildXml()
{
$buffer = array();
$buffer[] = '<?xml version="1.0"?>';
$buffer[] = '<postgresqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
$buffer[] = ' <database name="">';
$buffer = array_merge($buffer, $this->buildXmlStructure());
$buffer[] = ' </database>';
$buffer[] = '</postgresqldump>';
return implode("\n", $buffer);
}
/**
* Builds the XML structure to export.
*
* @return array An array of XML lines (strings).
*
* @since 12.1
* @throws Exception if an error occurs.
*/
protected function buildXmlStructure()
{
$buffer = array();
foreach ($this->from as $table)
{
// Replace the magic prefix if found.
$table = $this->getGenericTableName($table);
// Get the details columns information.
$fields = $this->db->getTableColumns($table, false);
$keys = $this->db->getTableKeys($table);
$sequences = $this->db->getTableSequences($table);
$buffer[] = ' <table_structure name="' . $table . '">';
foreach ($sequences as $sequence)
{
if (version_compare($this->db->getVersion(), '9.1.0') < 0)
{
$sequence->start_value = null;
}
$buffer[] = ' <sequence Name="' . $sequence->sequence . '"' . ' Schema="' . $sequence->schema . '"' .
' Table="' . $sequence->table . '"' . ' Column="' . $sequence->column . '"' . ' Type="' . $sequence->data_type . '"' .
' Start_Value="' . $sequence->start_value . '"' . ' Min_Value="' . $sequence->minimum_value . '"' .
' Max_Value="' . $sequence->maximum_value . '"' . ' Increment="' . $sequence->increment . '"' .
' Cycle_option="' . $sequence->cycle_option . '"' .
' />';
}
foreach ($fields as $field)
{
$buffer[] = ' <field Field="' . $field->column_name . '"' . ' Type="' . $field->type . '"' . ' Null="' . $field->null . '"' .
(isset($field->default) ? ' Default="' . $field->default . '"' : '') . ' Comments="' . $field->comments . '"' .
' />';
}
foreach ($keys as $key)
{
$buffer[] = ' <key Index="' . $key->idxName . '"' . ' is_primary="' . $key->isPrimary . '"' . ' is_unique="' . $key->isUnique . '"' .
' Query="' . $key->Query . '" />';
}
$buffer[] = ' </table_structure>';
}
return $buffer;
}
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseExporterPostgresql Method supports chaining.
*
* @since 12.1
*
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverPostgresql))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Get the generic name of the table, converting the database prefix to the wildcard string.
*
* @param string $table The name of the table.
*
* @return string The name of the table with the database prefix replaced with #__.
*
* @since 12.1
*/
protected function getGenericTableName($table)
{
// TODO Incorporate into parent class and use $this.
$prefix = $this->db->getPrefix();
// Replace the magic prefix if found.
$table = preg_replace("|^$prefix|", '#__', $table);
return $table;
}
/**
* Specifies a list of table names to export.
*
* @param mixed $from The name of a single table, or an array of the table names to export.
*
* @return JDatabaseExporterPostgresql Method supports chaining.
*
* @since 12.1
* @throws Exception if input is not a string or array.
*/
public function from($from)
{
if (is_string($from))
{
$this->from = array($from);
}
elseif (is_array($from))
{
$this->from = $from;
}
else
{
throw new Exception('JPLATFORM_ERROR_INPUT_REQUIRES_STRING_OR_ARRAY');
}
return $this;
}
/**
* Sets the database connector to use for exporting structure and/or data from PostgreSQL.
*
* @param JDatabaseDriverPostgresql $db The database connector.
*
* @return JDatabaseExporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function setDbo(JDatabaseDriverPostgresql $db)
{
$this->db = $db;
return $this;
}
/**
* Sets an internal option to export the structure of the input table(s).
*
* @param boolean $setting True to export the structure, false to not.
*
* @return JDatabaseExporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function withStructure($setting = true)
{
$this->options->withStructure = (boolean) $setting;
return $this;
}
}

View File

@ -0,0 +1,192 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Platform Database Factory class
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseFactory
{
/**
* Contains the current JDatabaseFactory instance
*
* @var JDatabaseFactory
* @since 12.1
*/
private static $_instance = null;
/**
* Method to return a JDatabaseDriver instance based on the given options. There are three global options and then
* the rest are specific to the database driver. The 'database' option determines which database is to
* be used for the connection. The 'select' option determines whether the connector should automatically select
* the chosen database.
*
* Instances are unique to the given options and new objects are only created when a unique options array is
* passed into the method. This ensures that we don't end up with unnecessary database connection resources.
*
* @param string $name Name of the database driver you'd like to instantiate
* @param array $options Parameters to be passed to the database driver.
*
* @return JDatabaseDriver A database driver object.
*
* @since 12.1
* @throws RuntimeException
*/
public function getDriver($name = 'mysqli', $options = array())
{
// Sanitize the database connector options.
$options['driver'] = preg_replace('/[^A-Z0-9_\.-]/i', '', $name);
$options['database'] = (isset($options['database'])) ? $options['database'] : null;
$options['select'] = (isset($options['select'])) ? $options['select'] : true;
// Derive the class name from the driver.
$class = 'JDatabaseDriver' . ucfirst(strtolower($options['driver']));
// If the class still doesn't exist we have nothing left to do but throw an exception. We did our best.
if (!class_exists($class))
{
throw new RuntimeException(sprintf('Unable to load Database Driver: %s', $options['driver']));
}
// Create our new JDatabaseDriver connector based on the options given.
try
{
$instance = new $class($options);
}
catch (RuntimeException $e)
{
throw new RuntimeException(sprintf('Unable to connect to the Database: %s', $e->getMessage()));
}
return $instance;
}
/**
* Gets an exporter class object.
*
* @param string $name Name of the driver you want an exporter for.
* @param JDatabaseDriver $db Optional JDatabaseDriver instance
*
* @return JDatabaseExporter An exporter object.
*
* @since 12.1
* @throws RuntimeException
*/
public function getExporter($name, JDatabaseDriver $db = null)
{
// Derive the class name from the driver.
$class = 'JDatabaseExporter' . ucfirst(strtolower($name));
// Make sure we have an exporter class for this driver.
if (!class_exists($class))
{
// If it doesn't exist we are at an impasse so throw an exception.
throw new RuntimeException('Database Exporter not found.');
}
$o = new $class;
if ($db instanceof JDatabaseDriver)
{
$o->setDbo($db);
}
return $o;
}
/**
* Gets an importer class object.
*
* @param string $name Name of the driver you want an importer for.
* @param JDatabaseDriver $db Optional JDatabaseDriver instance
*
* @return JDatabaseImporter An importer object.
*
* @since 12.1
* @throws RuntimeException
*/
public function getImporter($name, JDatabaseDriver $db = null)
{
// Derive the class name from the driver.
$class = 'JDatabaseImporter' . ucfirst(strtolower($name));
// Make sure we have an importer class for this driver.
if (!class_exists($class))
{
// If it doesn't exist we are at an impasse so throw an exception.
throw new RuntimeException('Database importer not found.');
}
$o = new $class;
if ($db instanceof JDatabaseDriver)
{
$o->setDbo($db);
}
return $o;
}
/**
* Gets an instance of the factory object.
*
* @return JDatabaseFactory
*
* @since 12.1
*/
public static function getInstance()
{
return self::$_instance ? self::$_instance : new JDatabaseFactory;
}
/**
* Get the current query object or a new JDatabaseQuery object.
*
* @param string $name Name of the driver you want an query object for.
* @param JDatabaseDriver $db Optional JDatabaseDriver instance
*
* @return JDatabaseQuery The current query object or a new object extending the JDatabaseQuery class.
*
* @since 12.1
* @throws RuntimeException
*/
public function getQuery($name, JDatabaseDriver $db = null)
{
// Derive the class name from the driver.
$class = 'JDatabaseQuery' . ucfirst(strtolower($name));
// Make sure we have a query class for this driver.
if (!class_exists($class))
{
// If it doesn't exist we are at an impasse so throw an exception.
throw new RuntimeException('Database Query class not found');
}
return new $class($db);
}
/**
* Gets an instance of a factory object to return on subsequent calls of getInstance.
*
* @param JDatabaseFactory $instance A JDatabaseFactory object.
*
* @return void
*
* @since 12.1
*/
public static function setInstance(JDatabaseFactory $instance = null)
{
self::$_instance = $instance;
}
}

View File

@ -0,0 +1,22 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Platform Database Importer Class
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
abstract class JDatabaseImporter
{
}

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,61 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQL import driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseImporterMysql extends JDatabaseImporterMysqli
{
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseImporterMysql Method supports chaining.
*
* @since 11.1
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverMysql))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Sets the database connector to use for exporting structure and/or data from MySQL.
*
* @param JDatabaseDriverMysql $db The database connector.
*
* @return JDatabaseImporterMysql Method supports chaining.
*
* @since 11.1
*/
public function setDbo(JDatabaseDriverMysql $db)
{
$this->db = $db;
return $this;
}
}

View File

@ -0,0 +1,646 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQLi import driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseImporterMysqli extends JDatabaseImporter
{
/**
* @var array An array of cached data.
* @since 11.1
*/
protected $cache = array();
/**
* The database connector to use for exporting structure and/or data.
*
* @var JDatabaseDriverMysql
* @since 11.1
*/
protected $db = null;
/**
* The input source.
*
* @var mixed
* @since 11.1
*/
protected $from = array();
/**
* The type of input format (XML).
*
* @var string
* @since 11.1
*/
protected $asFormat = 'xml';
/**
* An array of options for the exporter.
*
* @var object
* @since 11.1
*/
protected $options = null;
/**
* Constructor.
*
* Sets up the default options for the exporter.
*
* @since 11.1
*/
public function __construct()
{
$this->options = new stdClass;
$this->cache = array('columns' => array(), 'keys' => array());
// Set up the class defaults:
// Import with only structure
$this->withStructure();
// Export as XML.
$this->asXml();
// Default destination is a string using $output = (string) $exporter;
}
/**
* Set the output option for the exporter to XML format.
*
* @return JDatabaseImporterMysql Method supports chaining.
*
* @since 11.1
*/
public function asXml()
{
$this->asFormat = 'xml';
return $this;
}
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseImporterMysqli Method supports chaining.
*
* @since 11.1
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverMysqli))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Specifies the data source to import.
*
* @param mixed $from The data source to import.
*
* @return JDatabaseImporterMysql Method supports chaining.
*
* @since 11.1
*/
public function from($from)
{
$this->from = $from;
return $this;
}
/**
* Get the SQL syntax to add a column.
*
* @param string $table The table name.
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 11.1
*/
protected function getAddColumnSQL($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD COLUMN ' . $this->getColumnSQL($field);
}
/**
* Get the SQL syntax to add a key.
*
* @param string $table The table name.
* @param array $keys An array of the fields pertaining to this key.
*
* @return string
*
* @since 11.1
*/
protected function getAddKeySQL($table, $keys)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD ' . $this->getKeySQL($keys);
}
/**
* Get alters for table if there is a difference.
*
* @param SimpleXMLElement $structure The XML structure pf the table.
*
* @return array
*
* @since 11.1
*/
protected function getAlterTableSQL(SimpleXMLElement $structure)
{
$table = $this->getRealTableName($structure['name']);
$oldFields = $this->db->getTableColumns($table);
$oldKeys = $this->db->getTableKeys($table);
$alters = array();
// Get the fields and keys from the XML that we are aiming for.
$newFields = $structure->xpath('field');
$newKeys = $structure->xpath('key');
// Loop through each field in the new structure.
foreach ($newFields as $field)
{
$fName = (string) $field['Field'];
if (isset($oldFields[$fName]))
{
// The field exists, check it's the same.
$column = $oldFields[$fName];
// Test whether there is a change.
$change = ((string) $field['Type'] != $column->Type) || ((string) $field['Null'] != $column->Null)
|| ((string) $field['Default'] != $column->Default) || ((string) $field['Extra'] != $column->Extra);
if ($change)
{
$alters[] = $this->getChangeColumnSQL($table, $field);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldFields[$fName]);
}
else
{
// The field is new.
$alters[] = $this->getAddColumnSQL($table, $field);
}
}
// Any columns left are orphans
foreach ($oldFields as $name => $column)
{
// Delete the column.
$alters[] = $this->getDropColumnSQL($table, $name);
}
// Get the lookups for the old and new keys.
$oldLookup = $this->getKeyLookup($oldKeys);
$newLookup = $this->getKeyLookup($newKeys);
// Loop through each key in the new structure.
foreach ($newLookup as $name => $keys)
{
// Check if there are keys on this field in the existing table.
if (isset($oldLookup[$name]))
{
$same = true;
$newCount = count($newLookup[$name]);
$oldCount = count($oldLookup[$name]);
// There is a key on this field in the old and new tables. Are they the same?
if ($newCount == $oldCount)
{
// Need to loop through each key and do a fine grained check.
for ($i = 0; $i < $newCount; $i++)
{
$same = (((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique)
&& ((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name)
&& ((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index)
&& ((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation)
&& ((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type));
/*
Debug.
echo '<pre>';
echo '<br />Non_unique: '.
((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Non_unique'].' vs '.$oldLookup[$name][$i]->Non_unique;
echo '<br />Column_name: '.
((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Column_name'].' vs '.$oldLookup[$name][$i]->Column_name;
echo '<br />Seq_in_index: '.
((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Seq_in_index'].' vs '.$oldLookup[$name][$i]->Seq_in_index;
echo '<br />Collation: '.
((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Collation'].' vs '.$oldLookup[$name][$i]->Collation;
echo '<br />Index_type: '.
((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Index_type'].' vs '.$oldLookup[$name][$i]->Index_type;
echo '<br />Same = '.($same ? 'true' : 'false');
echo '</pre>';
*/
if (!$same)
{
// Break out of the loop. No need to check further.
break;
}
}
}
else
{
// Count is different, just drop and add.
$same = false;
}
if (!$same)
{
$alters[] = $this->getDropKeySQL($table, $name);
$alters[] = $this->getAddKeySQL($table, $keys);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldLookup[$name]);
}
else
{
// This is a new key.
$alters[] = $this->getAddKeySQL($table, $keys);
}
}
// Any keys left are orphans.
foreach ($oldLookup as $name => $keys)
{
if (strtoupper($name) == 'PRIMARY')
{
$alters[] = $this->getDropPrimaryKeySQL($table);
}
else
{
$alters[] = $this->getDropKeySQL($table, $name);
}
}
return $alters;
}
/**
* Get the syntax to alter a column.
*
* @param string $table The name of the database table to alter.
* @param SimpleXMLElement $field The XML definition for the field.
*
* @return string
*
* @since 11.1
*/
protected function getChangeColumnSQL($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' CHANGE COLUMN ' . $this->db->quoteName((string) $field['Field']) . ' '
. $this->getColumnSQL($field);
}
/**
* Get the SQL syntax for a single column that would be included in a table create or alter statement.
*
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 11.1
*/
protected function getColumnSQL(SimpleXMLElement $field)
{
// TODO Incorporate into parent class and use $this.
$blobs = array('text', 'smalltext', 'mediumtext', 'largetext');
$fName = (string) $field['Field'];
$fType = (string) $field['Type'];
$fNull = (string) $field['Null'];
$fDefault = isset($field['Default']) ? (string) $field['Default'] : null;
$fExtra = (string) $field['Extra'];
$query = $this->db->quoteName($fName) . ' ' . $fType;
if ($fNull == 'NO')
{
if (in_array($fType, $blobs) || $fDefault === null)
{
$query .= ' NOT NULL';
}
else
{
// TODO Don't quote numeric values.
$query .= ' NOT NULL DEFAULT ' . $this->db->quote($fDefault);
}
}
else
{
if ($fDefault === null)
{
$query .= ' DEFAULT NULL';
}
else
{
// TODO Don't quote numeric values.
$query .= ' DEFAULT ' . $this->db->quote($fDefault);
}
}
if ($fExtra)
{
$query .= ' ' . strtoupper($fExtra);
}
return $query;
}
/**
* Get the SQL syntax to drop a column.
*
* @param string $table The table name.
* @param string $name The name of the field to drop.
*
* @return string
*
* @since 11.1
*/
protected function getDropColumnSQL($table, $name)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP COLUMN ' . $this->db->quoteName($name);
}
/**
* Get the SQL syntax to drop a key.
*
* @param string $table The table name.
* @param string $name The name of the key to drop.
*
* @return string
*
* @since 11.1
*/
protected function getDropKeySQL($table, $name)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP KEY ' . $this->db->quoteName($name);
}
/**
* Get the SQL syntax to drop a key.
*
* @param string $table The table name.
*
* @return string
*
* @since 11.1
*/
protected function getDropPrimaryKeySQL($table)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP PRIMARY KEY';
}
/**
* Get the details list of keys for a table.
*
* @param array $keys An array of objects that comprise the keys for the table.
*
* @return array The lookup array. array({key name} => array(object, ...))
*
* @since 11.1
* @throws Exception
*/
protected function getKeyLookup($keys)
{
// First pass, create a lookup of the keys.
$lookup = array();
foreach ($keys as $key)
{
if ($key instanceof SimpleXMLElement)
{
$kName = (string) $key['Key_name'];
}
else
{
$kName = $key->Key_name;
}
if (empty($lookup[$kName]))
{
$lookup[$kName] = array();
}
$lookup[$kName][] = $key;
}
return $lookup;
}
/**
* Get the SQL syntax for a key.
*
* @param array $columns An array of SimpleXMLElement objects comprising the key.
*
* @return string
*
* @since 11.1
*/
protected function getKeySQL($columns)
{
// TODO Error checking on array and element types.
$kNonUnique = (string) $columns[0]['Non_unique'];
$kName = (string) $columns[0]['Key_name'];
$kColumn = (string) $columns[0]['Column_name'];
$prefix = '';
if ($kName == 'PRIMARY')
{
$prefix = 'PRIMARY ';
}
elseif ($kNonUnique == 0)
{
$prefix = 'UNIQUE ';
}
$nColumns = count($columns);
$kColumns = array();
if ($nColumns == 1)
{
$kColumns[] = $this->db->quoteName($kColumn);
}
else
{
foreach ($columns as $column)
{
$kColumns[] = (string) $column['Column_name'];
}
}
$query = $prefix . 'KEY ' . ($kName != 'PRIMARY' ? $this->db->quoteName($kName) : '') . ' (' . implode(',', $kColumns) . ')';
return $query;
}
/**
* Get the real name of the table, converting the prefix wildcard string if present.
*
* @param string $table The name of the table.
*
* @return string The real name of the table.
*
* @since 11.1
*/
protected function getRealTableName($table)
{
// TODO Incorporate into parent class and use $this.
$prefix = $this->db->getPrefix();
// Replace the magic prefix if found.
$table = preg_replace('|^#__|', $prefix, $table);
return $table;
}
/**
* Merges the incoming structure definition with the existing structure.
*
* @return void
*
* @note Currently only supports XML format.
* @since 11.1
* @throws Exception on error.
* @todo If it's not XML convert to XML first.
*/
protected function mergeStructure()
{
$prefix = $this->db->getPrefix();
$tables = $this->db->getTableList();
if ($this->from instanceof SimpleXMLElement)
{
$xml = $this->from;
}
else
{
$xml = new SimpleXMLElement($this->from);
}
// Get all the table definitions.
$xmlTables = $xml->xpath('database/table_structure');
foreach ($xmlTables as $table)
{
// Convert the magic prefix into the real table name.
$tableName = (string) $table['name'];
$tableName = preg_replace('|^#__|', $prefix, $tableName);
if (in_array($tableName, $tables))
{
// The table already exists. Now check if there is any difference.
if ($queries = $this->getAlterTableSQL($xml->database->table_structure))
{
// Run the queries to upgrade the data structure.
foreach ($queries as $query)
{
$this->db->setQuery($query);
try
{
$this->db->execute();
}
catch (RuntimeException $e)
{
$this->addLog('Fail: ' . $this->db->getQuery());
throw $e;
}
$this->addLog('Pass: ' . $this->db->getQuery());
}
}
}
else
{
// This is a new table.
$query = $this->xmlToCreate($table);
$this->db->setQuery($query);
try
{
$this->db->execute();
}
catch (RuntimeException $e)
{
$this->addLog('Fail: ' . $this->db->getQuery());
throw $e;
}
$this->addLog('Pass: ' . $this->db->getQuery());
}
}
}
/**
* Sets the database connector to use for exporting structure and/or data from MySQL.
*
* @param JDatabaseDriverMysqli $db The database connector.
*
* @return JDatabaseImporterMysqli Method supports chaining.
*
* @since 11.1
*/
public function setDbo(JDatabaseDriverMysqli $db)
{
$this->db = $db;
return $this;
}
/**
* Sets an internal option to merge the structure based on the input data.
*
* @param boolean $setting True to export the structure, false to not.
*
* @return JDatabaseImporterMysql Method supports chaining.
*
* @since 11.1
*/
public function withStructure($setting = true)
{
$this->options->withStructure = (boolean) $setting;
return $this;
}
}

View File

@ -0,0 +1,780 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* PostgreSQL import driver.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseImporterPostgresql extends JDatabaseImporter
{
/**
* @var array An array of cached data.
* @since 12.1
*/
protected $cache = array();
/**
* The database connector to use for exporting structure and/or data.
*
* @var JDatabaseDriverPostgresql
* @since 12.1
*/
protected $db = null;
/**
* The input source.
*
* @var mixed
* @since 12.1
*/
protected $from = array();
/**
* The type of input format (XML).
*
* @var string
* @since 12.1
*/
protected $asFormat = 'xml';
/**
* An array of options for the exporter.
*
* @var object
* @since 12.1
*/
protected $options = null;
/**
* Constructor.
*
* Sets up the default options for the exporter.
*
* @since 12.1
*/
public function __construct()
{
$this->options = new stdClass;
$this->cache = array('columns' => array(), 'keys' => array());
// Set up the class defaults:
// Import with only structure
$this->withStructure();
// Export as XML.
$this->asXml();
// Default destination is a string using $output = (string) $exporter;
}
/**
* Set the output option for the exporter to XML format.
*
* @return JDatabaseImporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function asXml()
{
$this->asFormat = 'xml';
return $this;
}
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseImporterPostgresql Method supports chaining.
*
* @since 12.1
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverPostgresql))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Specifies the data source to import.
*
* @param mixed $from The data source to import.
*
* @return JDatabaseImporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function from($from)
{
$this->from = $from;
return $this;
}
/**
* Get the SQL syntax to add a column.
*
* @param string $table The table name.
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 12.1
*/
protected function getAddColumnSQL($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD COLUMN ' . $this->getColumnSQL($field);
}
/**
* Get the SQL syntax to add an index.
*
* @param SimpleXMLElement $field The XML index definition.
*
* @return string
*
* @since 12.1
*/
protected function getAddIndexSQL(SimpleXMLElement $field)
{
return (string) $field['Query'];
}
/**
* Get alters for table if there is a difference.
*
* @param SimpleXMLElement $structure The XML structure of the table.
*
* @return array
*
* @since 12.1
*/
protected function getAlterTableSQL(SimpleXMLElement $structure)
{
$table = $this->getRealTableName($structure['name']);
$oldFields = $this->db->getTableColumns($table);
$oldKeys = $this->db->getTableKeys($table);
$oldSequence = $this->db->getTableSequences($table);
$alters = array();
// Get the fields and keys from the XML that we are aiming for.
$newFields = $structure->xpath('field');
$newKeys = $structure->xpath('key');
$newSequence = $structure->xpath('sequence');
/* Sequence section */
$oldSeq = $this->getSeqLookup($oldSequence);
$newSequenceLook = $this->getSeqLookup($newSequence);
foreach ($newSequenceLook as $kSeqName => $vSeq)
{
if (isset($oldSeq[$kSeqName]))
{
// The field exists, check it's the same.
$column = $oldSeq[$kSeqName][0];
/* For older database version that doesn't support these fields use default values */
if (version_compare($this->db->getVersion(), '9.1.0') < 0)
{
$column->Min_Value = '1';
$column->Max_Value = '9223372036854775807';
$column->Increment = '1';
$column->Cycle_option = 'NO';
$column->Start_Value = '1';
}
// Test whether there is a change.
$change = ((string) $vSeq[0]['Type'] != $column->Type) || ((string) $vSeq[0]['Start_Value'] != $column->Start_Value)
|| ((string) $vSeq[0]['Min_Value'] != $column->Min_Value) || ((string) $vSeq[0]['Max_Value'] != $column->Max_Value)
|| ((string) $vSeq[0]['Increment'] != $column->Increment) || ((string) $vSeq[0]['Cycle_option'] != $column->Cycle_option)
|| ((string) $vSeq[0]['Table'] != $column->Table) || ((string) $vSeq[0]['Column'] != $column->Column)
|| ((string) $vSeq[0]['Schema'] != $column->Schema) || ((string) $vSeq[0]['Name'] != $column->Name);
if ($change)
{
$alters[] = $this->getChangeSequenceSQL($kSeqName, $vSeq);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldSeq[$kSeqName]);
}
else
{
// The sequence is new
$alters[] = $this->getAddSequenceSQL($newSequenceLook[$kSeqName][0]);
}
}
// Any sequences left are orphans
foreach ($oldSeq as $name => $column)
{
// Delete the sequence.
$alters[] = $this->getDropSequenceSQL($name);
}
/* Field section */
// Loop through each field in the new structure.
foreach ($newFields as $field)
{
$fName = (string) $field['Field'];
if (isset($oldFields[$fName]))
{
// The field exists, check it's the same.
$column = $oldFields[$fName];
// Test whether there is a change.
$change = ((string) $field['Type'] != $column->Type) || ((string) $field['Null'] != $column->Null)
|| ((string) $field['Default'] != $column->Default);
if ($change)
{
$alters[] = $this->getChangeColumnSQL($table, $field);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldFields[$fName]);
}
else
{
// The field is new.
$alters[] = $this->getAddColumnSQL($table, $field);
}
}
// Any columns left are orphans
foreach ($oldFields as $name => $column)
{
// Delete the column.
$alters[] = $this->getDropColumnSQL($table, $name);
}
/* Index section */
// Get the lookups for the old and new keys
$oldLookup = $this->getIdxLookup($oldKeys);
$newLookup = $this->getIdxLookup($newKeys);
// Loop through each key in the new structure.
foreach ($newLookup as $name => $keys)
{
// Check if there are keys on this field in the existing table.
if (isset($oldLookup[$name]))
{
$same = true;
$newCount = count($newLookup[$name]);
$oldCount = count($oldLookup[$name]);
// There is a key on this field in the old and new tables. Are they the same?
if ($newCount == $oldCount)
{
for ($i = 0; $i < $newCount; $i++)
{
// Check only query field -> different query means different index
$same = ((string) $newLookup[$name][$i]['Query'] == $oldLookup[$name][$i]->Query);
if (!$same)
{
// Break out of the loop. No need to check further.
break;
}
}
}
else
{
// Count is different, just drop and add.
$same = false;
}
if (!$same)
{
$alters[] = $this->getDropIndexSQL($name);
$alters[] = (string) $newLookup[$name][0]['Query'];
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldLookup[$name]);
}
else
{
// This is a new key.
$alters[] = (string) $newLookup[$name][0]['Query'];
}
}
// Any keys left are orphans.
foreach ($oldLookup as $name => $keys)
{
if ($oldLookup[$name][0]->is_primary == 'TRUE')
{
$alters[] = $this->getDropPrimaryKeySQL($table, $oldLookup[$name][0]->Index);
}
else
{
$alters[] = $this->getDropIndexSQL($name);
}
}
return $alters;
}
/**
* Get the SQL syntax to drop a sequence.
*
* @param string $name The name of the sequence to drop.
*
* @return string
*
* @since 12.1
*/
protected function getDropSequenceSQL($name)
{
return 'DROP SEQUENCE ' . $this->db->quoteName($name);
}
/**
* Get the syntax to add a sequence.
*
* @param SimpleXMLElement $field The XML definition for the sequence.
*
* @return string
*
* @since 12.1
*/
protected function getAddSequenceSQL($field)
{
/* For older database version that doesn't support these fields use default values */
if (version_compare($this->db->getVersion(), '9.1.0') < 0)
{
$field['Min_Value'] = '1';
$field['Max_Value'] = '9223372036854775807';
$field['Increment'] = '1';
$field['Cycle_option'] = 'NO';
$field['Start_Value'] = '1';
}
return 'CREATE SEQUENCE ' . (string) $field['Name'] .
' INCREMENT BY ' . (string) $field['Increment'] . ' MINVALUE ' . $field['Min_Value'] .
' MAXVALUE ' . (string) $field['Max_Value'] . ' START ' . (string) $field['Start_Value'] .
(((string) $field['Cycle_option'] == 'NO') ? ' NO' : '') . ' CYCLE' .
' OWNED BY ' . $this->db->quoteName((string) $field['Schema'] . '.' . (string) $field['Table'] . '.' . (string) $field['Column']);
}
/**
* Get the syntax to alter a sequence.
*
* @param SimpleXMLElement $field The XML definition for the sequence.
*
* @return string
*
* @since 12.1
*/
protected function getChangeSequenceSQL($field)
{
/* For older database version that doesn't support these fields use default values */
if (version_compare($this->db->getVersion(), '9.1.0') < 0)
{
$field['Min_Value'] = '1';
$field['Max_Value'] = '9223372036854775807';
$field['Increment'] = '1';
$field['Cycle_option'] = 'NO';
$field['Start_Value'] = '1';
}
return 'ALTER SEQUENCE ' . (string) $field['Name'] .
' INCREMENT BY ' . (string) $field['Increment'] . ' MINVALUE ' . (string) $field['Min_Value'] .
' MAXVALUE ' . (string) $field['Max_Value'] . ' START ' . (string) $field['Start_Value'] .
' OWNED BY ' . $this->db->quoteName((string) $field['Schema'] . '.' . (string) $field['Table'] . '.' . (string) $field['Column']);
}
/**
* Get the syntax to alter a column.
*
* @param string $table The name of the database table to alter.
* @param SimpleXMLElement $field The XML definition for the field.
*
* @return string
*
* @since 12.1
*/
protected function getChangeColumnSQL($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ALTER COLUMN ' . $this->db->quoteName((string) $field['Field']) . ' '
. $this->getAlterColumnSQL($table, $field);
}
/**
* Get the SQL syntax for a single column that would be included in a table create statement.
*
* @param string $table The name of the database table to alter.
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 12.1
*/
protected function getAlterColumnSQL($table, $field)
{
// TODO Incorporate into parent class and use $this.
$blobs = array('text', 'smalltext', 'mediumtext', 'largetext');
$fName = (string) $field['Field'];
$fType = (string) $field['Type'];
$fNull = (string) $field['Null'];
$fDefault = (isset($field['Default']) && $field['Default'] != 'NULL' ) ?
preg_match('/^[0-9]$/', $field['Default']) ? $field['Default'] : $this->db->quote((string) $field['Default'])
: null;
$query = ' TYPE ' . $fType;
if ($fNull == 'NO')
{
if (in_array($fType, $blobs) || $fDefault === null)
{
$query .= ",\nALTER COLUMN " . $this->db->quoteName($fName) . ' SET NOT NULL' .
",\nALTER COLUMN " . $this->db->quoteName($fName) . ' DROP DEFAULT';
}
else
{
$query .= ",\nALTER COLUMN " . $this->db->quoteName($fName) . ' SET NOT NULL' .
",\nALTER COLUMN " . $this->db->quoteName($fName) . ' SET DEFAULT ' . $fDefault;
}
}
else
{
if ($fDefault !== null)
{
$query .= ",\nALTER COLUMN " . $this->db->quoteName($fName) . ' DROP NOT NULL' .
",\nALTER COLUMN " . $this->db->quoteName($fName) . ' SET DEFAULT ' . $fDefault;
}
}
/* sequence was created in other function, here is associated a default value but not yet owner */
if (strpos($fDefault, 'nextval') !== false)
{
$query .= ";\nALTER SEQUENCE " . $this->db->quoteName($table . '_' . $fName . '_seq') . ' OWNED BY ' . $this->db->quoteName($table . '.' . $fName);
}
return $query;
}
/**
* Get the SQL syntax for a single column that would be included in a table create statement.
*
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 12.1
*/
protected function getColumnSQL(SimpleXMLElement $field)
{
// TODO Incorporate into parent class and use $this.
$blobs = array('text', 'smalltext', 'mediumtext', 'largetext');
$fName = (string) $field['Field'];
$fType = (string) $field['Type'];
$fNull = (string) $field['Null'];
$fDefault = (isset($field['Default']) && $field['Default'] != 'NULL' ) ?
preg_match('/^[0-9]$/', $field['Default']) ? $field['Default'] : $this->db->quote((string) $field['Default'])
: null;
/* nextval() as default value means that type field is serial */
if (strpos($fDefault, 'nextval') !== false)
{
$query = $this->db->quoteName($fName) . ' SERIAL';
}
else
{
$query = $this->db->quoteName($fName) . ' ' . $fType;
if ($fNull == 'NO')
{
if (in_array($fType, $blobs) || $fDefault === null)
{
$query .= ' NOT NULL';
}
else
{
$query .= ' NOT NULL DEFAULT ' . $fDefault;
}
}
else
{
if ($fDefault !== null)
{
$query .= ' DEFAULT ' . $fDefault;
}
}
}
return $query;
}
/**
* Get the SQL syntax to drop a column.
*
* @param string $table The table name.
* @param string $name The name of the field to drop.
*
* @return string
*
* @since 12.1
*/
protected function getDropColumnSQL($table, $name)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP COLUMN ' . $this->db->quoteName($name);
}
/**
* Get the SQL syntax to drop an index.
*
* @param string $name The name of the key to drop.
*
* @return string
*
* @since 12.1
*/
protected function getDropIndexSQL($name)
{
return 'DROP INDEX ' . $this->db->quoteName($name);
}
/**
* Get the SQL syntax to drop a key.
*
* @param string $table The table name.
* @param string $name The constraint name.
*
* @return string
*
* @since 12.1
*/
protected function getDropPrimaryKeySQL($table, $name)
{
return 'ALTER TABLE ONLY ' . $this->db->quoteName($table) . ' DROP CONSTRAINT ' . $this->db->quoteName($name);
}
/**
* Get the details list of keys for a table.
*
* @param array $keys An array of objects that comprise the keys for the table.
*
* @return array The lookup array. array({key name} => array(object, ...))
*
* @since 12.1
* @throws Exception
*/
protected function getIdxLookup($keys)
{
// First pass, create a lookup of the keys.
$lookup = array();
foreach ($keys as $key)
{
if ($key instanceof SimpleXMLElement)
{
$kName = (string) $key['Index'];
}
else
{
$kName = $key->Index;
}
if (empty($lookup[$kName]))
{
$lookup[$kName] = array();
}
$lookup[$kName][] = $key;
}
return $lookup;
}
/**
* Get the details list of sequences for a table.
*
* @param array $sequences An array of objects that comprise the sequences for the table.
*
* @return array The lookup array. array({key name} => array(object, ...))
*
* @since 12.1
* @throws Exception
*/
protected function getSeqLookup($sequences)
{
// First pass, create a lookup of the keys.
$lookup = array();
foreach ($sequences as $seq)
{
if ($seq instanceof SimpleXMLElement)
{
$sName = (string) $seq['Name'];
}
else
{
$sName = $seq->Name;
}
if (empty($lookup[$sName]))
{
$lookup[$sName] = array();
}
$lookup[$sName][] = $seq;
}
return $lookup;
}
/**
* Get the real name of the table, converting the prefix wildcard string if present.
*
* @param string $table The name of the table.
*
* @return string The real name of the table.
*
* @since 12.1
*/
protected function getRealTableName($table)
{
// TODO Incorporate into parent class and use $this.
$prefix = $this->db->getPrefix();
// Replace the magic prefix if found.
$table = preg_replace('|^#__|', $prefix, $table);
return $table;
}
/**
* Merges the incoming structure definition with the existing structure.
*
* @return void
*
* @note Currently only supports XML format.
* @since 12.1
* @throws Exception on error.
* @todo If it's not XML convert to XML first.
*/
protected function mergeStructure()
{
$prefix = $this->db->getPrefix();
$tables = $this->db->getTableList();
if ($this->from instanceof SimpleXMLElement)
{
$xml = $this->from;
}
else
{
$xml = new SimpleXMLElement($this->from);
}
// Get all the table definitions.
$xmlTables = $xml->xpath('database/table_structure');
foreach ($xmlTables as $table)
{
// Convert the magic prefix into the real table name.
$tableName = (string) $table['name'];
$tableName = preg_replace('|^#__|', $prefix, $tableName);
if (in_array($tableName, $tables))
{
// The table already exists. Now check if there is any difference.
if ($queries = $this->getAlterTableSQL($xml->database->table_structure))
{
// Run the queries to upgrade the data structure.
foreach ($queries as $query)
{
$this->db->setQuery($query);
try
{
$this->db->execute();
}
catch (RuntimeException $e)
{
$this->addLog('Fail: ' . $this->db->getQuery());
throw $e;
}
$this->addLog('Pass: ' . $this->db->getQuery());
}
}
}
else
{
// This is a new table.
$query = $this->xmlToCreate($table);
$this->db->setQuery($query);
try
{
$this->db->execute();
}
catch (RuntimeException $e)
{
$this->addLog('Fail: ' . $this->db->getQuery());
throw $e;
}
$this->addLog('Pass: ' . $this->db->getQuery());
}
}
}
/**
* Sets the database connector to use for exporting structure and/or data from PostgreSQL.
*
* @param JDatabaseDriverPostgresql $db The database connector.
*
* @return JDatabaseImporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function setDbo(JDatabaseDriverPostgresql $db)
{
$this->db = $db;
return $this;
}
/**
* Sets an internal option to merge the structure based on the input data.
*
* @param boolean $setting True to export the structure, false to not.
*
* @return JDatabaseImporterPostgresql Method supports chaining.
*
* @since 12.1
*/
public function withStructure($setting = true)
{
$this->options->withStructure = (boolean) $setting;
return $this;
}
}

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,205 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Platform Database Driver Class
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
abstract class JDatabaseIterator implements Countable, Iterator
{
/**
* The database cursor.
*
* @var mixed
* @since 12.1
*/
protected $cursor;
/**
* The class of object to create.
*
* @var string
* @since 12.1
*/
protected $class;
/**
* The name of the column to use for the key of the database record.
*
* @var mixed
* @since 12.1
*/
private $_column;
/**
* The current database record.
*
* @var mixed
* @since 12.1
*/
private $_current;
/**
* A numeric or string key for the current database record.
*
* @var scalar
* @since 12.1
*/
private $_key;
/**
* The number of fetched records.
*
* @var integer
* @since 12.1
*/
private $_fetched = 0;
/**
* Database iterator constructor.
*
* @param mixed $cursor The database cursor.
* @param string $column An option column to use as the iterator key.
* @param string $class The class of object that is returned.
*
* @throws InvalidArgumentException
*/
public function __construct($cursor, $column = null, $class = 'stdClass')
{
if (!class_exists($class))
{
throw new InvalidArgumentException(sprintf('new %s(*%s*, cursor)', get_class($this), gettype($class)));
}
$this->cursor = $cursor;
$this->class = $class;
$this->_column = $column;
$this->_fetched = 0;
$this->next();
}
/**
* Database iterator destructor.
*
* @since 12.1
*/
public function __destruct()
{
if ($this->cursor)
{
$this->freeResult($this->cursor);
}
}
/**
* The current element in the iterator.
*
* @return object
*
* @see Iterator::current()
* @since 12.1
*/
public function current()
{
return $this->_current;
}
/**
* The key of the current element in the iterator.
*
* @return scalar
*
* @see Iterator::key()
* @since 12.1
*/
public function key()
{
return $this->_key;
}
/**
* Moves forward to the next result from the SQL query.
*
* @return void
*
* @see Iterator::next()
* @since 12.1
*/
public function next()
{
// Set the default key as being the number of fetched object
$this->_key = $this->_fetched;
// Try to get an object
$this->_current = $this->fetchObject();
// If an object has been found
if ($this->_current)
{
// Set the key as being the indexed column (if it exists)
if (isset($this->_current->{$this->_column}))
{
$this->_key = $this->_current->{$this->_column};
}
// Update the number of fetched object
$this->_fetched++;
}
}
/**
* Rewinds the iterator.
*
* This iterator cannot be rewound.
*
* @return void
*
* @see Iterator::rewind()
* @since 12.1
*/
public function rewind()
{
}
/**
* Checks if the current position of the iterator is valid.
*
* @return boolean
*
* @see Iterator::valid()
* @since 12.1
*/
public function valid()
{
return (boolean) $this->_current;
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
abstract protected function fetchObject();
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 12.1
*/
abstract protected function freeResult();
}

View File

@ -0,0 +1,21 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQL azure database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorAzure extends JDatabaseIteratorSqlsrv
{
}

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,58 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQL database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @see http://dev.mysql.com/doc/
* @since 12.1
*/
class JDatabaseIteratorMysql extends JDatabaseIterator
{
/**
* Get the number of rows in the result set for the executed SQL given by the cursor.
*
* @return integer The number of rows in the result set.
*
* @since 12.1
* @see Countable::count()
*/
public function count()
{
return mysql_num_rows($this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject()
{
return mysql_fetch_object($this->cursor, $this->class);
}
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 12.1
*/
protected function freeResult()
{
mysql_free_result($this->cursor);
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQLi database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorMysqli extends JDatabaseIterator
{
/**
* Get the number of rows in the result set for the executed SQL given by the cursor.
*
* @return integer The number of rows in the result set.
*
* @since 12.1
* @see Countable::count()
*/
public function count()
{
return mysqli_num_rows($this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject()
{
return mysqli_fetch_object($this->cursor, $this->class);
}
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 12.1
*/
protected function freeResult()
{
mysqli_free_result($this->cursor);
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Oracle database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorOracle extends JDatabaseIteratorPdo
{
}

View File

@ -0,0 +1,74 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* PDO database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorPdo extends JDatabaseIterator
{
/**
* Get the number of rows in the result set for the executed SQL given by the cursor.
*
* @return integer The number of rows in the result set.
*
* @since 12.1
* @see Countable::count()
*/
public function count()
{
if (!empty($this->cursor) && $this->cursor instanceof PDOStatement)
{
return $this->cursor->rowCount();
}
else
{
return 0;
}
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject()
{
if (!empty($this->cursor) && $this->cursor instanceof PDOStatement)
{
return $this->cursor->fetchObject($this->class);
}
else
{
return false;
}
}
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 12.1
*/
protected function freeResult()
{
if (!empty($this->cursor) && $this->cursor instanceof PDOStatement)
{
$this->cursor->closeCursor();
}
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQLite database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorSqlite extends JDatabaseIteratorPdo
{
}

View File

@ -0,0 +1,57 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQL server database iterator.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseIteratorSqlsrv extends JDatabaseIterator
{
/**
* Get the number of rows in the result set for the executed SQL given by the cursor.
*
* @return integer The number of rows in the result set.
*
* @since 12.1
* @see Countable::count()
*/
public function count()
{
return sqlsrv_num_rows($this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 12.1
*/
protected function fetchObject()
{
return sqlsrv_fetch_object($this->cursor, $this->class);
}
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 12.1
*/
protected function freeResult()
{
sqlsrv_free_stmt($this->cursor);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,56 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Database Query Limitable Interface.
* Adds bind/unbind methods as well as a getBounded() method
* to retrieve the stored bounded variables on demand prior to
* query execution.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
interface JDatabaseQueryLimitable
{
/**
* Method to modify a query already in string format with the needed
* additions to make the query limited to a particular number of
* results, or start at a particular offset. This method is used
* automatically by the __toString() method if it detects that the
* query implements the JDatabaseQueryLimitable interface.
*
* @param string $query The query in string format
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return string
*
* @since 12.1
*/
public function processLimit($query, $limit, $offset = 0);
/**
* Sets the offset and limit for the result set, if the database driver supports it.
*
* Usage:
* $query->setLimit(100, 0); (retrieve 100 rows, starting at first record)
* $query->setLimit(50, 50); (retrieve 50 rows, starting at 50th record)
*
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function setLimit($limit = 0, $offset = 0);
}

View File

@ -0,0 +1,21 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseQueryMysql extends JDatabaseQueryMysqli
{
}

View File

@ -0,0 +1,106 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseQueryMysqli extends JDatabaseQuery implements JDatabaseQueryLimitable
{
/**
* @var interger The offset for the result set.
* @since 12.1
*/
protected $offset;
/**
* @var integer The limit for the result set.
* @since 12.1
*/
protected $limit;
/**
* Method to modify a query already in string format with the needed
* additions to make the query limited to a particular number of
* results, or start at a particular offset.
*
* @param string $query The query in string format
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return string
*
* @since 12.1
*/
public function processLimit($query, $limit, $offset = 0)
{
if ($limit > 0 || $offset > 0)
{
$query .= ' LIMIT ' . $offset . ', ' . $limit;
}
return $query;
}
/**
* Concatenates an array of column names or values.
*
* @param array $values An array of values to concatenate.
* @param string $separator As separator to place between each value.
*
* @return string The concatenated values.
*
* @since 11.1
*/
public function concatenate($values, $separator = null)
{
if ($separator)
{
$concat_string = 'CONCAT_WS(' . $this->quote($separator);
foreach ($values as $value)
{
$concat_string .= ', ' . $value;
}
return $concat_string . ')';
}
else
{
return 'CONCAT(' . implode(',', $values) . ')';
}
}
/**
* Sets the offset and limit for the result set, if the database driver supports it.
*
* Usage:
* $query->setLimit(100, 0); (retrieve 100 rows, starting at first record)
* $query->setLimit(50, 50); (retrieve 50 rows, starting at 50th record)
*
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function setLimit($limit = 0, $offset = 0)
{
$this->limit = (int) $limit;
$this->offset = (int) $offset;
return $this;
}
}

View File

@ -0,0 +1,204 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Oracle Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseQueryOracle extends JDatabaseQueryPdo implements JDatabaseQueryPreparable, JDatabaseQueryLimitable
{
/**
* @var integer
* @since 12.1
*/
protected $limit;
/**
* @var integer
* @since 12.1
*/
protected $offset;
/**
* @var mixed
* @since 12.1
*/
protected $bounded = array();
/**
* Method to add a variable to an internal array that will be bound to a prepared SQL statement before query execution. Also
* removes a variable that has been bounded from the internal bounded array when the passed in value is null.
*
* @param string|integer $key The key that will be used in your SQL query to reference the value. Usually of
* the form ':key', but can also be an integer.
* @param mixed &$value The value that will be bound. The value is passed by reference to support output
* parameters such as those possible with stored procedures.
* @param integer $dataType Constant corresponding to a SQL datatype.
* @param integer $length The length of the variable. Usually required for OUTPUT parameters.
* @param array $driverOptions Optional driver options to be used.
*
* @return JDatabaseQuery
*
* @since 12.1
*/
public function bind($key = null, &$value = null, $dataType = PDO::PARAM_STR, $length = 0, $driverOptions = array())
{
// Case 1: Empty Key (reset $bounded array)
if (empty($key))
{
$this->bounded = array();
return $this;
}
// Case 2: Key Provided, null value (unset key from $bounded array)
if (is_null($value))
{
if (isset($this->bounded[$key]))
{
unset($this->bounded[$key]);
}
return $this;
}
$obj = new stdClass;
$obj->value = &$value;
$obj->dataType = $dataType;
$obj->length = $length;
$obj->driverOptions = $driverOptions;
// Case 3: Simply add the Key/Value into the bounded array
$this->bounded[$key] = $obj;
return $this;
}
/**
* Retrieves the bound parameters array when key is null and returns it by reference. If a key is provided then that item is
* returned.
*
* @param mixed $key The bounded variable key to retrieve.
*
* @return mixed
*
* @since 12.1
*/
public function &getBounded($key = null)
{
if (empty($key))
{
return $this->bounded;
}
else
{
if (isset($this->bounded[$key]))
{
return $this->bounded[$key];
}
}
}
/**
* Clear data from the query or a specific clause of the query.
*
* @param string $clause Optionally, the name of the clause to clear, or nothing to clear the whole query.
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function clear($clause = null)
{
switch ($clause)
{
case null:
$this->bounded = array();
break;
}
parent::clear($clause);
return $this;
}
/**
* Method to modify a query already in string format with the needed
* additions to make the query limited to a particular number of
* results, or start at a particular offset. This method is used
* automatically by the __toString() method if it detects that the
* query implements the JDatabaseQueryLimitable interface.
*
* @param string $query The query in string format
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return string
*
* @since 12.1
*/
public function processLimit($query, $limit, $offset = 0)
{
// Check if we need to mangle the query.
if ($limit || $offset)
{
$query = "SELECT joomla2.*
FROM (
SELECT joomla1.*, ROWNUM AS joomla_db_rownum
FROM (
" . $query . "
) joomla1
) joomla2";
// Check if the limit value is greater than zero.
if ($limit > 0)
{
$query .= ' WHERE joomla2.joomla_db_rownum BETWEEN ' . ($offset + 1) . ' AND ' . ($offset + $limit);
}
else
{
// Check if there is an offset and then use this.
if ($offset)
{
$query .= ' WHERE joomla2.joomla_db_rownum > ' . ($offset + 1);
}
}
}
return $query;
}
/**
* Sets the offset and limit for the result set, if the database driver supports it.
*
* Usage:
* $query->setLimit(100, 0); (retrieve 100 rows, starting at first record)
* $query->setLimit(50, 50); (retrieve 50 rows, starting at 50th record)
*
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function setLimit($limit = 0, $offset = 0)
{
$this->limit = (int) $limit;
$this->offset = (int) $offset;
return $this;
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* PDO Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseQueryPdo extends JDatabaseQuery
{
}

View File

@ -0,0 +1,630 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.3
*/
class JDatabaseQueryPostgresql extends JDatabaseQuery implements JDatabaseQueryLimitable
{
/**
* @var object The FOR UPDATE element used in "FOR UPDATE" lock
* @since 11.3
*/
protected $forUpdate = null;
/**
* @var object The FOR SHARE element used in "FOR SHARE" lock
* @since 11.3
*/
protected $forShare = null;
/**
* @var object The NOWAIT element used in "FOR SHARE" and "FOR UPDATE" lock
* @since 11.3
*/
protected $noWait = null;
/**
* @var object The LIMIT element
* @since 11.3
*/
protected $limit = null;
/**
* @var object The OFFSET element
* @since 11.3
*/
protected $offset = null;
/**
* @var object The RETURNING element of INSERT INTO
* @since 11.3
*/
protected $returning = null;
/**
* Magic function to convert the query to a string, only for postgresql specific query
*
* @return string The completed query.
*
* @since 11.3
*/
public function __toString()
{
$query = '';
switch ($this->type)
{
case 'select':
$query .= (string) $this->select;
$query .= (string) $this->from;
if ($this->join)
{
// Special case for joins
foreach ($this->join as $join)
{
$query .= (string) $join;
}
}
if ($this->where)
{
$query .= (string) $this->where;
}
if ($this->group)
{
$query .= (string) $this->group;
}
if ($this->having)
{
$query .= (string) $this->having;
}
if ($this->order)
{
$query .= (string) $this->order;
}
if ($this->limit)
{
$query .= (string) $this->limit;
}
if ($this->offset)
{
$query .= (string) $this->offset;
}
if ($this->forUpdate)
{
$query .= (string) $this->forUpdate;
}
else
{
if ($this->forShare)
{
$query .= (string) $this->forShare;
}
}
if ($this->noWait)
{
$query .= (string) $this->noWait;
}
break;
case 'update':
$query .= (string) $this->update;
$query .= (string) $this->set;
if ($this->join)
{
$onWord = ' ON ';
// Workaround for special case of JOIN with UPDATE
foreach ($this->join as $join)
{
$joinElem = $join->getElements();
$joinArray = explode($onWord, $joinElem[0]);
$this->from($joinArray[0]);
$this->where($joinArray[1]);
}
$query .= (string) $this->from;
}
if ($this->where)
{
$query .= (string) $this->where;
}
break;
case 'insert':
$query .= (string) $this->insert;
if ($this->values)
{
if ($this->columns)
{
$query .= (string) $this->columns;
}
$elements = $this->values->getElements();
if (!($elements[0] instanceof $this))
{
$query .= ' VALUES ';
}
$query .= (string) $this->values;
if ($this->returning)
{
$query .= (string) $this->returning;
}
}
break;
default:
$query = parent::__toString();
break;
}
return $query;
}
/**
* Clear data from the query or a specific clause of the query.
*
* @param string $clause Optionally, the name of the clause to clear, or nothing to clear the whole query.
*
* @return void
*
* @since 11.3
*/
public function clear($clause = null)
{
switch ($clause)
{
case 'limit':
$this->limit = null;
break;
case 'offset':
$this->offset = null;
break;
case 'forUpdate':
$this->forUpdate = null;
break;
case 'forShare':
$this->forShare = null;
break;
case 'noWait':
$this->noWait = null;
break;
case 'returning':
$this->returning = null;
break;
case 'select':
case 'update':
case 'delete':
case 'insert':
case 'from':
case 'join':
case 'set':
case 'where':
case 'group':
case 'having':
case 'order':
case 'columns':
case 'values':
parent::clear($clause);
break;
default:
$this->type = null;
$this->limit = null;
$this->offset = null;
$this->forUpdate = null;
$this->forShare = null;
$this->noWait = null;
$this->returning = null;
parent::clear($clause);
break;
}
return $this;
}
/**
* Casts a value to a char.
*
* Ensure that the value is properly quoted before passing to the method.
*
* Usage:
* $query->select($query->castAsChar('a'));
*
* @param string $value The value to cast as a char.
*
* @return string Returns the cast value.
*
* @since 11.1
*/
public function castAsChar($value)
{
return $value . '::text';
}
/**
* Concatenates an array of column names or values.
*
* Usage:
* $query->select($query->concatenate(array('a', 'b')));
*
* @param array $values An array of values to concatenate.
* @param string $separator As separator to place between each value.
*
* @return string The concatenated values.
*
* @since 11.3
*/
public function concatenate($values, $separator = null)
{
if ($separator)
{
return implode(' || ' . $this->quote($separator) . ' || ', $values);
}
else
{
return implode(' || ', $values);
}
}
/**
* Gets the current date and time.
*
* @return string Return string used in query to obtain
*
* @since 11.3
*/
public function currentTimestamp()
{
return 'NOW()';
}
/**
* Sets the FOR UPDATE lock on select's output row
*
* @param string $table_name The table to lock
* @param boolean $glue The glue by which to join the conditions. Defaults to ',' .
*
* @return JDatabaseQuery FOR UPDATE query element
*
* @since 11.3
*/
public function forUpdate ($table_name, $glue = ',')
{
$this->type = 'forUpdate';
if ( is_null($this->forUpdate) )
{
$glue = strtoupper($glue);
$this->forUpdate = new JDatabaseQueryElement('FOR UPDATE', 'OF ' . $table_name, "$glue ");
}
else
{
$this->forUpdate->append($table_name);
}
return $this;
}
/**
* Sets the FOR SHARE lock on select's output row
*
* @param string $table_name The table to lock
* @param boolean $glue The glue by which to join the conditions. Defaults to ',' .
*
* @return JDatabaseQuery FOR SHARE query element
*
* @since 11.3
*/
public function forShare ($table_name, $glue = ',')
{
$this->type = 'forShare';
if ( is_null($this->forShare) )
{
$glue = strtoupper($glue);
$this->forShare = new JDatabaseQueryElement('FOR SHARE', 'OF ' . $table_name, "$glue ");
}
else
{
$this->forShare->append($table_name);
}
return $this;
}
/**
* Used to get a string to extract year from date column.
*
* Usage:
* $query->select($query->year($query->quoteName('dateColumn')));
*
* @param string $date Date column containing year to be extracted.
*
* @return string Returns string to extract year from a date.
*
* @since 12.1
*/
public function year($date)
{
return 'EXTRACT (YEAR FROM ' . $date . ')';
}
/**
* Used to get a string to extract month from date column.
*
* Usage:
* $query->select($query->month($query->quoteName('dateColumn')));
*
* @param string $date Date column containing month to be extracted.
*
* @return string Returns string to extract month from a date.
*
* @since 12.1
*/
public function month($date)
{
return 'EXTRACT (MONTH FROM ' . $date . ')';
}
/**
* Used to get a string to extract day from date column.
*
* Usage:
* $query->select($query->day($query->quoteName('dateColumn')));
*
* @param string $date Date column containing day to be extracted.
*
* @return string Returns string to extract day from a date.
*
* @since 12.1
*/
public function day($date)
{
return 'EXTRACT (DAY FROM ' . $date . ')';
}
/**
* Used to get a string to extract hour from date column.
*
* Usage:
* $query->select($query->hour($query->quoteName('dateColumn')));
*
* @param string $date Date column containing hour to be extracted.
*
* @return string Returns string to extract hour from a date.
*
* @since 12.1
*/
public function hour($date)
{
return 'EXTRACT (HOUR FROM ' . $date . ')';
}
/**
* Used to get a string to extract minute from date column.
*
* Usage:
* $query->select($query->minute($query->quoteName('dateColumn')));
*
* @param string $date Date column containing minute to be extracted.
*
* @return string Returns string to extract minute from a date.
*
* @since 12.1
*/
public function minute($date)
{
return 'EXTRACT (MINUTE FROM ' . $date . ')';
}
/**
* Used to get a string to extract seconds from date column.
*
* Usage:
* $query->select($query->second($query->quoteName('dateColumn')));
*
* @param string $date Date column containing second to be extracted.
*
* @return string Returns string to extract second from a date.
*
* @since 12.1
*/
public function second($date)
{
return 'EXTRACT (SECOND FROM ' . $date . ')';
}
/**
* Sets the NOWAIT lock on select's output row
*
* @return JDatabaseQuery NO WAIT query element
*
* @since 11.3
*/
public function noWait ()
{
$this->type = 'noWait';
if ( is_null($this->noWait) )
{
$this->noWait = new JDatabaseQueryElement('NOWAIT', null);
}
return $this;
}
/**
* Set the LIMIT clause to the query
*
* @param int $limit An int of how many row will be returned
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 11.3
*/
public function limit( $limit = 0 )
{
if (is_null($this->limit))
{
$this->limit = new JDatabaseQueryElement('LIMIT', (int) $limit);
}
return $this;
}
/**
* Set the OFFSET clause to the query
*
* @param int $offset An int for skipping row
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 11.3
*/
public function offset( $offset = 0 )
{
if (is_null($this->offset))
{
$this->offset = new JDatabaseQueryElement('OFFSET', (int) $offset);
}
return $this;
}
/**
* Add the RETURNING element to INSERT INTO statement.
*
* @param mixed $pkCol The name of the primary key column.
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 11.3
*/
public function returning( $pkCol )
{
if (is_null($this->returning))
{
$this->returning = new JDatabaseQueryElement('RETURNING', $pkCol);
}
return $this;
}
/**
* Sets the offset and limit for the result set, if the database driver supports it.
*
* Usage:
* $query->setLimit(100, 0); (retrieve 100 rows, starting at first record)
* $query->setLimit(50, 50); (retrieve 50 rows, starting at 50th record)
*
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function setLimit($limit = 0, $offset = 0)
{
$this->limit = (int) $limit;
$this->offset = (int) $offset;
return $this;
}
/**
* Method to modify a query already in string format with the needed
* additions to make the query limited to a particular number of
* results, or start at a particular offset.
*
* @param string $query The query in string format
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return string
*
* @since 12.1
*/
public function processLimit($query, $limit, $offset = 0)
{
if ($limit > 0)
{
$query .= ' LIMIT ' . $limit;
}
if ($offset > 0)
{
$query .= ' OFFSET ' . $offset;
}
return $query;
}
/**
* Add to the current date and time in Postgresql.
* Usage:
* $query->select($query->dateAdd());
* Prefixing the interval with a - (negative sign) will cause subtraction to be used.
*
* @param datetime $date The date to add to
* @param string $interval The string representation of the appropriate number of units
* @param string $datePart The part of the date to perform the addition on
*
* @return string The string with the appropriate sql for addition of dates
*
* @since 13.1
* @note Not all drivers support all units. Check appropriate references
* @link http://www.postgresql.org/docs/9.0/static/functions-datetime.html.
*/
public function dateAdd($date, $interval, $datePart)
{
if (substr($interval, 0, 1) != '-')
{
return "timestamp '" . $date . "' + interval '" . $interval . " " . $datePart . "'";
}
else
{
return "timestamp '" . $date . "' - interval '" . ltrim($interval, '-') . " " . $datePart . "'";
}
}
}

View File

@ -0,0 +1,53 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Joomla Database Query Preparable Interface.
* Adds bind/unbind methods as well as a getBounded() method
* to retrieve the stored bounded variables on demand prior to
* query execution.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
interface JDatabaseQueryPreparable
{
/**
* Method to add a variable to an internal array that will be bound to a prepared SQL statement before query execution. Also
* removes a variable that has been bounded from the internal bounded array when the passed in value is null.
*
* @param string|integer $key The key that will be used in your SQL query to reference the value. Usually of
* the form ':key', but can also be an integer.
* @param mixed &$value The value that will be bound. The value is passed by reference to support output
* parameters such as those possible with stored procedures.
* @param integer $dataType Constant corresponding to a SQL datatype.
* @param integer $length The length of the variable. Usually required for OUTPUT parameters.
* @param array $driverOptions Optional driver options to be used.
*
* @return JDatabaseQuery
*
* @since 12.1
*/
public function bind($key = null, &$value = null, $dataType = PDO::PARAM_STR, $length = 0, $driverOptions = array());
/**
* Retrieves the bound parameters array when key is null and returns it by reference. If a key is provided then that item is
* returned.
*
* @param mixed $key The bounded variable key to retrieve.
*
* @return mixed
*
* @since 12.1
*/
public function &getBounded($key = null);
}

View File

@ -0,0 +1,32 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseQuerySqlazure extends JDatabaseQuerySqlsrv
{
/**
* The character(s) used to quote SQL statement names such as table names or field names,
* etc. The child classes should define this as necessary. If a single character string the
* same character is used for both sides of the quoted name, else the first character will be
* used for the opening quote and the second for the closing quote.
*
* @var string
*
* @since 11.1
*/
protected $name_quotes = '';
}

View File

@ -0,0 +1,217 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* SQLite Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 12.1
*/
class JDatabaseQuerySqlite extends JDatabaseQueryPdo implements JDatabaseQueryPreparable, JDatabaseQueryLimitable
{
/**
* @var integer
* @since 12.1
*/
protected $limit;
/**
* @var integer
* @since 12.1
*/
protected $offset;
/**
* @var mixed
* @since 12.1
*/
protected $bounded = array();
/**
* Method to add a variable to an internal array that will be bound to a prepared SQL statement before query execution. Also
* removes a variable that has been bounded from the internal bounded array when the passed in value is null.
*
* @param string|integer $key The key that will be used in your SQL query to reference the value. Usually of
* the form ':key', but can also be an integer.
* @param mixed &$value The value that will be bound. The value is passed by reference to support output
* parameters such as those possible with stored procedures.
* @param integer $dataType Constant corresponding to a SQL datatype.
* @param integer $length The length of the variable. Usually required for OUTPUT parameters.
* @param array $driverOptions Optional driver options to be used.
*
* @return JDatabaseQuery
*
* @since 12.1
*/
public function bind($key = null, &$value = null, $dataType = PDO::PARAM_STR, $length = 0, $driverOptions = array())
{
// Case 1: Empty Key (reset $bounded array)
if (empty($key))
{
$this->bounded = array();
return $this;
}
// Case 2: Key Provided, null value (unset key from $bounded array)
if (is_null($value))
{
if (isset($this->bounded[$key]))
{
unset($this->bounded[$key]);
}
return $this;
}
$obj = new stdClass;
$obj->value = &$value;
$obj->dataType = $dataType;
$obj->length = $length;
$obj->driverOptions = $driverOptions;
// Case 3: Simply add the Key/Value into the bounded array
$this->bounded[$key] = $obj;
return $this;
}
/**
* Retrieves the bound parameters array when key is null and returns it by reference. If a key is provided then that item is
* returned.
*
* @param mixed $key The bounded variable key to retrieve.
*
* @return mixed
*
* @since 12.1
*/
public function &getBounded($key = null)
{
if (empty($key))
{
return $this->bounded;
}
else
{
if (isset($this->bounded[$key]))
{
return $this->bounded[$key];
}
}
}
/**
* Clear data from the query or a specific clause of the query.
*
* @param string $clause Optionally, the name of the clause to clear, or nothing to clear the whole query.
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function clear($clause = null)
{
switch ($clause)
{
case null:
$this->bounded = array();
break;
}
parent::clear($clause);
return $this;
}
/**
* Method to modify a query already in string format with the needed
* additions to make the query limited to a particular number of
* results, or start at a particular offset. This method is used
* automatically by the __toString() method if it detects that the
* query implements the JDatabaseQueryLimitable interface.
*
* @param string $query The query in string format
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return string
*
* @since 12.1
*/
public function processLimit($query, $limit, $offset = 0)
{
if ($limit > 0 || $offset > 0)
{
$query .= ' LIMIT ' . $offset . ', ' . $limit;
}
return $query;
}
/**
* Sets the offset and limit for the result set, if the database driver supports it.
*
* Usage:
* $query->setLimit(100, 0); (retrieve 100 rows, starting at first record)
* $query->setLimit(50, 50); (retrieve 50 rows, starting at 50th record)
*
* @param integer $limit The limit for the result set
* @param integer $offset The offset for the result set
*
* @return JDatabaseQuery Returns this object to allow chaining.
*
* @since 12.1
*/
public function setLimit($limit = 0, $offset = 0)
{
$this->limit = (int) $limit;
$this->offset = (int) $offset;
return $this;
}
/**
* Add to the current date and time.
* Usage:
* $query->select($query->dateAdd());
* Prefixing the interval with a - (negative sign) will cause subtraction to be used.
*
* @param datetime $date The date or datetime to add to
* @param string $interval The string representation of the appropriate number of units
* @param string $datePart The part of the date to perform the addition on
*
* @return string The string with the appropriate sql for addition of dates
*
* @since 13.1
* @link http://www.sqlite.org/lang_datefunc.html
*/
public function dateAdd($date, $interval, $datePart)
{
// SQLite does not support microseconds as a separate unit. Convert the interval to seconds
if (strcasecmp($datePart, 'microseconds') == 0)
{
$interval = .001 * $interval;
$datePart = 'seconds';
}
if (substr($interval, 0, 1) != '-')
{
return "datetime('" . $date . "', '+" . $interval . " " . $datePart . "')";
}
else
{
return "datetime('" . $date . "', '" . $interval . " " . $datePart . "')";
}
}
}

View File

@ -0,0 +1,199 @@
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 11.1
*/
class JDatabaseQuerySqlsrv extends JDatabaseQuery
{
/**
* The character(s) used to quote SQL statement names such as table names or field names,
* etc. The child classes should define this as necessary. If a single character string the
* same character is used for both sides of the quoted name, else the first character will be
* used for the opening quote and the second for the closing quote.
*
* @var string
*
* @since 11.1
*/
protected $name_quotes = '`';
/**
* The null or zero representation of a timestamp for the database driver. This should be
* defined in child classes to hold the appropriate value for the engine.
*
* @var string
*
* @since 11.1
*/
protected $null_date = '1900-01-01 00:00:00';
/**
* Magic function to convert the query to a string.
*
* @return string The completed query.
*
* @since 11.1
*/
public function __toString()
{
$query = '';
switch ($this->type)
{
case 'insert':
$query .= (string) $this->insert;
// Set method
if ($this->set)
{
$query .= (string) $this->set;
}
// Columns-Values method
elseif ($this->values)
{
if ($this->columns)
{
$query .= (string) $this->columns;
}
$elements = $this->insert->getElements();
$tableName = array_shift($elements);
$query .= 'VALUES ';
$query .= (string) $this->values;
if ($this->autoIncrementField)
{
$query = 'SET IDENTITY_INSERT ' . $tableName . ' ON;' . $query . 'SET IDENTITY_INSERT ' . $tableName . ' OFF;';
}
if ($this->where)
{
$query .= (string) $this->where;
}
}
break;
default:
$query = parent::__toString();
break;
}
return $query;
}
/**
* Casts a value to a char.
*
* Ensure that the value is properly quoted before passing to the method.
*
* @param string $value The value to cast as a char.
*
* @return string Returns the cast value.
*
* @since 11.1
*/
public function castAsChar($value)
{
return 'CAST(' . $value . ' as NVARCHAR(10))';
}
/**
* Gets the function to determine the length of a character string.
*
* @param string $field A value.
* @param string $operator Comparison operator between charLength integer value and $condition
* @param string $condition Integer value to compare charLength with.
*
* @return string The required char length call.
*
* @since 11.1
*/
public function charLength($field, $operator = null, $condition = null)
{
return 'DATALENGTH(' . $field . ')' . (isset($operator) && isset($condition) ? ' ' . $operator . ' ' . $condition : '');
}
/**
* Concatenates an array of column names or values.
*
* @param array $values An array of values to concatenate.
* @param string $separator As separator to place between each value.
*
* @return string The concatenated values.
*
* @since 11.1
*/
public function concatenate($values, $separator = null)
{
if ($separator)
{
return '(' . implode('+' . $this->quote($separator) . '+', $values) . ')';
}
else
{
return '(' . implode('+', $values) . ')';
}
}
/**
* Gets the current date and time.
*
* @return string
*
* @since 11.1
*/
public function currentTimestamp()
{
return 'GETDATE()';
}
/**
* Get the length of a string in bytes.
*
* @param string $value The string to measure.
*
* @return integer
*
* @since 11.1
*/
public function length($value)
{
return 'LEN(' . $value . ')';
}
/**
* Add to the current date and time.
* Usage:
* $query->select($query->dateAdd());
* Prefixing the interval with a - (negative sign) will cause subtraction to be used.
*
* @param datetime $date The date to add to; type may be time or datetime.
* @param string $interval The string representation of the appropriate number of units
* @param string $datePart The part of the date to perform the addition on
*
* @return string The string with the appropriate sql for addition of dates
*
* @since 13.1
* @note Not all drivers support all units.
* @link http://msdn.microsoft.com/en-us/library/ms186819.aspx for more information
*/
public function dateAdd($date, $interval, $datePart)
{
return "DATEADD('" . $datePart . "', '" . $interval . "', '" . $date . "'" . ')';
}
}