summaryrefslogtreecommitdiffstats
path: root/system/database
diff options
context:
space:
mode:
Diffstat (limited to 'system/database')
-rwxr-xr-xsystem/database/DB.php50
-rw-r--r--system/database/DB_cache.php12
-rw-r--r--system/database/DB_driver.php428
-rw-r--r--system/database/DB_forge.php79
-rw-r--r--system/database/DB_query_builder.php (renamed from system/database/DB_active_rec.php)734
-rw-r--r--system/database/DB_result.php57
-rw-r--r--system/database/DB_utility.php128
-rw-r--r--system/database/drivers/cubrid/cubrid_driver.php328
-rw-r--r--system/database/drivers/cubrid/cubrid_forge.php158
-rw-r--r--system/database/drivers/cubrid/cubrid_result.php64
-rw-r--r--system/database/drivers/cubrid/cubrid_utility.php56
-rw-r--r--system/database/drivers/interbase/interbase_driver.php148
-rw-r--r--system/database/drivers/interbase/interbase_forge.php141
-rw-r--r--system/database/drivers/interbase/interbase_result.php17
-rw-r--r--system/database/drivers/interbase/interbase_utility.php67
-rw-r--r--system/database/drivers/mssql/mssql_driver.php280
-rw-r--r--system/database/drivers/mssql/mssql_forge.php148
-rw-r--r--system/database/drivers/mssql/mssql_result.php12
-rw-r--r--system/database/drivers/mssql/mssql_utility.php47
-rw-r--r--system/database/drivers/mysql/mysql_driver.php243
-rw-r--r--system/database/drivers/mysql/mysql_forge.php103
-rw-r--r--system/database/drivers/mysql/mysql_result.php2
-rw-r--r--system/database/drivers/mysql/mysql_utility.php57
-rw-r--r--system/database/drivers/mysqli/mysqli_driver.php246
-rw-r--r--system/database/drivers/mysqli/mysqli_forge.php105
-rw-r--r--system/database/drivers/mysqli/mysqli_result.php4
-rw-r--r--system/database/drivers/mysqli/mysqli_utility.php46
-rw-r--r--system/database/drivers/oci8/oci8_driver.php265
-rw-r--r--system/database/drivers/oci8/oci8_forge.php131
-rw-r--r--system/database/drivers/oci8/oci8_result.php522
-rw-r--r--system/database/drivers/oci8/oci8_utility.php44
-rw-r--r--system/database/drivers/odbc/odbc_driver.php227
-rw-r--r--system/database/drivers/odbc/odbc_forge.php159
-rw-r--r--system/database/drivers/odbc/odbc_result.php75
-rw-r--r--system/database/drivers/odbc/odbc_utility.php59
-rw-r--r--system/database/drivers/pdo/pdo_driver.php391
-rw-r--r--system/database/drivers/pdo/pdo_forge.php162
-rw-r--r--system/database/drivers/pdo/pdo_result.php36
-rw-r--r--system/database/drivers/pdo/pdo_utility.php59
-rw-r--r--system/database/drivers/postgre/postgre_driver.php368
-rw-r--r--system/database/drivers/postgre/postgre_forge.php153
-rw-r--r--system/database/drivers/postgre/postgre_result.php20
-rw-r--r--system/database/drivers/postgre/postgre_utility.php41
-rw-r--r--system/database/drivers/sqlite/sqlite_driver.php242
-rw-r--r--system/database/drivers/sqlite/sqlite_forge.php144
-rw-r--r--system/database/drivers/sqlite/sqlite_result.php48
-rw-r--r--system/database/drivers/sqlite/sqlite_utility.php47
-rw-r--r--system/database/drivers/sqlite3/index.html10
-rw-r--r--system/database/drivers/sqlite3/sqlite3_driver.php385
-rw-r--r--system/database/drivers/sqlite3/sqlite3_forge.php203
-rw-r--r--system/database/drivers/sqlite3/sqlite3_result.php615
-rw-r--r--system/database/drivers/sqlite3/sqlite3_utility.php54
-rw-r--r--system/database/drivers/sqlsrv/sqlsrv_driver.php198
-rw-r--r--system/database/drivers/sqlsrv/sqlsrv_forge.php149
-rw-r--r--system/database/drivers/sqlsrv/sqlsrv_result.php24
-rw-r--r--system/database/drivers/sqlsrv/sqlsrv_utility.php49
56 files changed, 3724 insertions, 4916 deletions
diff --git a/system/database/DB.php b/system/database/DB.php
index 96e495515..00d14b43e 100755
--- a/system/database/DB.php
+++ b/system/database/DB.php
@@ -32,9 +32,9 @@
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
* @param string
- * @param bool Determines if active record should be used or not
+ * @param bool Determines if query builder should be used or not
*/
-function &DB($params = '', $active_record_override = NULL)
+function &DB($params = '', $query_builder_override = NULL)
{
// Load the DB config file if a DSN string wasn't passed
if (is_string($params) && strpos($params, '://') === FALSE)
@@ -53,7 +53,7 @@ function &DB($params = '', $active_record_override = NULL)
show_error('No database connection settings were found in the database config file.');
}
- if ($params != '')
+ if ($params !== '')
{
$active_group = $params;
}
@@ -92,16 +92,12 @@ function &DB($params = '', $active_record_override = NULL)
if (isset($dsn['query']))
{
parse_str($dsn['query'], $extra);
+
foreach ($extra as $key => $val)
{
- // booleans please
- if (strtoupper($val) === 'TRUE')
- {
- $val = TRUE;
- }
- elseif (strtoupper($val) === 'FALSE')
+ if (is_string($val) && in_array(strtoupper($val), array('TRUE', 'FALSE', 'NULL')))
{
- $val = FALSE;
+ $val = var_export($val);
}
$params[$key] = $val;
@@ -110,27 +106,34 @@ function &DB($params = '', $active_record_override = NULL)
}
// No DB specified yet? Beat them senseless...
- if ( ! isset($params['dbdriver']) OR $params['dbdriver'] == '')
+ if (empty($params['dbdriver']))
{
show_error('You have not selected a database type to connect to.');
}
- // Load the DB classes. Note: Since the active record class is optional
+ // Load the DB classes. Note: Since the query builder class is optional
// we need to dynamically create a class that extends proper parent class
- // based on whether we're using the active record class or not.
- if ($active_record_override !== NULL)
+ // based on whether we're using the query builder class or not.
+ if ($query_builder_override !== NULL)
{
- $active_record = $active_record_override;
+ $query_builder = $query_builder_override;
+ }
+ // Backwards compatibility work-around for keeping the
+ // $active_record config variable working. Should be
+ // removed in v3.1
+ elseif ( ! isset($query_builder) && isset($active_record))
+ {
+ $query_builder = $active_record;
}
require_once(BASEPATH.'database/DB_driver.php');
- if ( ! isset($active_record) OR $active_record == TRUE)
+ if ( ! isset($query_builder) OR $query_builder === TRUE)
{
- require_once(BASEPATH.'database/DB_active_rec.php');
+ require_once(BASEPATH.'database/DB_query_builder.php');
if ( ! class_exists('CI_DB'))
{
- class CI_DB extends CI_DB_active_record { }
+ class CI_DB extends CI_DB_query_builder { }
}
}
elseif ( ! class_exists('CI_DB'))
@@ -138,18 +141,23 @@ function &DB($params = '', $active_record_override = NULL)
class CI_DB extends CI_DB_driver { }
}
- require_once(BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php');
+ // Load the DB driver
+ $driver_file = BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php';
+
+ if ( ! file_exists($driver_file)) show_error('Invalid DB driver');
+
+ require_once($driver_file);
// Instantiate the DB adapter
$driver = 'CI_DB_'.$params['dbdriver'].'_driver';
$DB = new $driver($params);
- if ($DB->autoinit == TRUE)
+ if ($DB->autoinit === TRUE)
{
$DB->initialize();
}
- if (isset($params['stricton']) && $params['stricton'] == TRUE)
+ if ( ! empty($params['stricton']))
{
$DB->query('SET SESSION sql_mode="STRICT_ALL_TABLES"');
}
diff --git a/system/database/DB_cache.php b/system/database/DB_cache.php
index 58e6968c0..ba9110382 100644
--- a/system/database/DB_cache.php
+++ b/system/database/DB_cache.php
@@ -55,9 +55,9 @@ class CI_DB_Cache {
*/
public function check_path($path = '')
{
- if ($path == '')
+ if ($path === '')
{
- if ($this->db->cachedir == '')
+ if ($this->db->cachedir === '')
{
return $this->db->cache_off();
}
@@ -99,7 +99,7 @@ class CI_DB_Cache {
$segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2);
$filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql);
- if (FALSE === ($cachedata = read_file($filepath)))
+ if (FALSE === ($cachedata = file_get_contents($filepath)))
{
return FALSE;
}
@@ -154,12 +154,12 @@ class CI_DB_Cache {
*/
public function delete($segment_one = '', $segment_two = '')
{
- if ($segment_one == '')
+ if ($segment_one === '')
{
$segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1);
}
- if ($segment_two == '')
+ if ($segment_two === '')
{
$segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2);
}
@@ -177,7 +177,7 @@ class CI_DB_Cache {
*/
public function delete_all()
{
- delete_files($this->db->cachedir, TRUE);
+ delete_files($this->db->cachedir, TRUE, 0, TRUE);
}
}
diff --git a/system/database/DB_driver.php b/system/database/DB_driver.php
index 9f1a0b895..65f1f18d0 100644
--- a/system/database/DB_driver.php
+++ b/system/database/DB_driver.php
@@ -99,9 +99,13 @@ abstract class CI_DB_driver {
*/
public function initialize()
{
- // If an existing connection resource is available
- // there is no need to connect and select the database
- if (is_resource($this->conn_id) OR is_object($this->conn_id))
+ /* If an established connection is available, then there's
+ * no need to connect and select the database.
+ *
+ * Depending on the database driver, conn_id can be either
+ * boolean TRUE, a resource or an object.
+ */
+ if ($this->conn_id)
{
return TRUE;
}
@@ -109,7 +113,7 @@ abstract class CI_DB_driver {
// ----------------------------------------------------------------
// Connect to the database and set the connection ID
- $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
+ $this->conn_id = ($this->pconnect === FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource? Check if there is a failover else throw an error
if ( ! $this->conn_id)
@@ -127,7 +131,7 @@ abstract class CI_DB_driver {
}
// Try to connect
- $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
+ $this->conn_id = ($this->pconnect === FALSE) ? $this->db_connect() : $this->db_pconnect();
// If a connection is made break the foreach loop
if ($this->conn_id)
@@ -188,10 +192,24 @@ abstract class CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Select database
+ *
+ * This is just a dummy method to allow drivers without such
+ * functionality to not declare it, while others will override it.
+ *
+ * @return bool
+ */
+ public function db_select()
+ {
+ return TRUE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Set client character set
*
* @param string
- * @param string
* @return bool
*/
public function db_set_charset($charset)
@@ -279,21 +297,17 @@ abstract class CI_DB_driver {
*/
public function query($sql, $binds = FALSE, $return_object = TRUE)
{
- if ($sql == '')
+ if ($sql === '')
{
log_message('error', 'Invalid query: '.$sql);
- if ($this->db_debug)
- {
- return $this->display_error('db_invalid_query');
- }
- return FALSE;
+ return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
}
// Verify table prefix and replace if necessary
- if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
+ if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
{
- $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
+ $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
}
// Compile binds if needed
@@ -305,31 +319,28 @@ abstract class CI_DB_driver {
// Is query caching enabled? If the query is a "read type"
// we will load the caching class and return the previously
// cached query if it exists
- if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
+ if ($this->cache_on === TRUE && stripos($sql, 'SELECT') !== FALSE && $this->_cache_init())
{
- if ($this->_cache_init())
+ $this->load_rdriver();
+ if (FALSE !== ($cache = $this->CACHE->read($sql)))
{
- $this->load_rdriver();
- if (FALSE !== ($cache = $this->CACHE->read($sql)))
- {
- return $cache;
- }
+ return $cache;
}
}
// Save the query for debugging
- if ($this->save_queries == TRUE)
+ if ($this->save_queries === TRUE)
{
$this->queries[] = $sql;
}
// Start the Query Timer
- $time_start = list($sm, $ss) = explode(' ', microtime());
+ $time_start = microtime(TRUE);
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
- if ($this->save_queries == TRUE)
+ if ($this->save_queries === TRUE)
{
$this->query_times[] = 0;
}
@@ -352,25 +363,19 @@ abstract class CI_DB_driver {
$this->trans_complete();
// Display errors
- return $this->display_error(
- array(
- 'Error Number: '.$error['code'],
- $error['message'],
- $sql
- )
- );
+ return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
}
return FALSE;
}
// Stop and aggregate the query time results
- $time_end = list($em, $es) = explode(' ', microtime());
- $this->benchmark += ($em + $es) - ($sm + $ss);
+ $time_end = microtime(TRUE);
+ $this->benchmark += $time_end - $time_start;
- if ($this->save_queries == TRUE)
+ if ($this->save_queries === TRUE)
{
- $this->query_times[] = ($em + $es) - ($sm + $ss);
+ $this->query_times[] = $time_end - $time_start;
}
// Increment the query counter
@@ -382,7 +387,7 @@ abstract class CI_DB_driver {
{
// If caching is enabled we'll auto-cleanup any
// existing files related to this particular URI
- if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
+ if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
{
$this->CACHE->delete();
}
@@ -402,11 +407,9 @@ abstract class CI_DB_driver {
$driver = $this->load_rdriver();
$RES = new $driver($this);
- $RES->num_rows = $RES->num_rows();
-
- // Is query caching enabled? If so, we'll serialize the
+ // Is query caching enabled? If so, we'll serialize the
// result object and save it to a cache file.
- if ($this->cache_on == TRUE AND $this->_cache_init())
+ if ($this->cache_on === TRUE && $this->_cache_init())
{
// We'll create a new instance of the result object
// only without the platform specific driver since
@@ -415,9 +418,9 @@ abstract class CI_DB_driver {
// result object, so we'll have to compile the data
// and save it)
$CR = new CI_DB_result();
- $CR->num_rows = $RES->num_rows();
$CR->result_object = $RES->result_object();
$CR->result_array = $RES->result_array();
+ $CR->num_rows = $RES->num_rows();
// Reset these since cached objects can not utilize resource IDs.
$CR->conn_id = NULL;
@@ -608,7 +611,8 @@ abstract class CI_DB_driver {
// The count of bind should be 1 less then the count of segments
// If there are more bind arguments trim it down
- if (count($binds) >= count($segments)) {
+ if (count($binds) >= count($segments))
+ {
$binds = array_slice($binds, 0, count($segments)-1);
}
@@ -617,8 +621,7 @@ abstract class CI_DB_driver {
$i = 0;
foreach ($binds as $bind)
{
- $result .= $this->escape($bind);
- $result .= $segments[++$i];
+ $result .= $this->escape($bind).$segments[++$i];
}
return $result;
@@ -634,7 +637,7 @@ abstract class CI_DB_driver {
*/
public function is_write_type($sql)
{
- return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|OPTIMIZE|REINDEX)\s+/i', $sql);
+ return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql);
}
// --------------------------------------------------------------------
@@ -689,15 +692,15 @@ abstract class CI_DB_driver {
{
if (is_string($str) OR method_exists($str, '__toString'))
{
- $str = "'".$this->escape_str($str)."'";
+ return "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
- $str = ($str === FALSE) ? 0 : 1;
+ return ($str === FALSE) ? 0 : 1;
}
elseif (is_null($str))
{
- $str = 'NULL';
+ return 'NULL';
}
return $str;
@@ -733,13 +736,36 @@ abstract class CI_DB_driver {
public function primary($table = '')
{
$fields = $this->list_fields($table);
+ return is_array($fields) ? current($fields) : FALSE;
+ }
- if ( ! is_array($fields))
+ // --------------------------------------------------------------------
+
+ /**
+ * "Count All" query
+ *
+ * Generates a platform-specific query string that counts all records in
+ * the specified database
+ *
+ * @param string
+ * @return int
+ */
+ public function count_all($table = '')
+ {
+ if ($table === '')
{
- return FALSE;
+ return 0;
+ }
+
+ $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
+ if ($query->num_rows() === 0)
+ {
+ return 0;
}
- return current($fields);
+ $query = $query->row();
+ $this->_reset_select();
+ return (int) $query->numrows;
}
// --------------------------------------------------------------------
@@ -759,35 +785,40 @@ abstract class CI_DB_driver {
if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
{
- if ($this->db_debug)
- {
- return $this->display_error('db_unsupported_function');
- }
- return FALSE;
+ return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
- $retval = array();
+ $this->data_cache['table_names'] = array();
$query = $this->query($sql);
- if ($query->num_rows() > 0)
+ foreach ($query->result_array() as $row)
{
- $table = FALSE;
- $rows = $query->result_array();
- $key = (($row = current($rows)) && in_array('table_name', array_map('strtolower', array_keys($row))));
-
- if ($key)
+ // Do we know from which column to get the table name?
+ if ( ! isset($key))
{
- $table = array_key_exists('TABLE_NAME', $row) ? 'TABLE_NAME' : 'table_name';
+ if (isset($row['table_name']))
+ {
+ $key = 'table_name';
+ }
+ elseif (isset($row['TABLE_NAME']))
+ {
+ $key = 'TABLE_NAME';
+ }
+ else
+ {
+ /* We have no other choice but to just get the first element's key.
+ * Due to array_shift() accepting it's argument by reference, if
+ * E_STRICT is on, this would trigger a warning. So we'll have to
+ * assign it first.
+ */
+ $key = array_keys($row);
+ $key = array_shift($key);
+ }
}
- foreach ($rows as $row)
- {
- $retval[] = ( ! $table) ? current($row) : $row[$table];
- }
+ $this->data_cache['table_names'][] = $row[$key];
}
- $this->data_cache['table_names'] = $retval;
-
return $this->data_cache['table_names'];
}
@@ -819,40 +850,47 @@ abstract class CI_DB_driver {
return $this->data_cache['field_names'][$table];
}
- if ($table == '')
+ if ($table === '')
{
- if ($this->db_debug)
- {
- return $this->display_error('db_field_param_missing');
- }
- return FALSE;
+ return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
}
if (FALSE === ($sql = $this->_list_columns($table)))
{
- if ($this->db_debug)
- {
- return $this->display_error('db_unsupported_function');
- }
- return FALSE;
+ return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
$query = $this->query($sql);
+ $this->data_cache['field_names'][$table] = array();
- $retval = array();
foreach ($query->result_array() as $row)
{
- if (isset($row['COLUMN_NAME']))
- {
- $retval[] = $row['COLUMN_NAME'];
- }
- else
+ // Do we know from where to get the column's name?
+ if ( ! isset($key))
{
- $retval[] = current($row);
+ if (isset($row['column_name']))
+ {
+ $key = 'column_name';
+ }
+ elseif (isset($row['COLUMN_NAME']))
+ {
+ $key = 'COLUMN_NAME';
+ }
+ else
+ {
+ /* We have no other choice but to just get the first element's key.
+ * Due to array_shift() accepting it's argument by reference, if
+ * E_STRICT is on, this would trigger a warning. So we'll have to
+ * assign it first.
+ */
+ $key = array_keys($row);
+ $key = array_shift($key);
+ }
}
+
+ $this->data_cache['field_names'][$table][] = $row[$key];
}
- $this->data_cache['field_names'][$table] = $retval;
return $this->data_cache['field_names'][$table];
}
@@ -867,7 +905,7 @@ abstract class CI_DB_driver {
*/
public function field_exists($field_name, $table_name)
{
- return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
+ return in_array($field_name, $this->list_fields($table_name));
}
// --------------------------------------------------------------------
@@ -880,18 +918,64 @@ abstract class CI_DB_driver {
*/
public function field_data($table = '')
{
- if ($table == '')
+ if ($table === '')
{
- if ($this->db_debug)
+ return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
+ }
+
+ $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
+ return $query->field_data();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Escape the SQL Identifiers
+ *
+ * This function escapes column and table names
+ *
+ * @param mixed
+ * @return mixed
+ */
+ public function escape_identifiers($item)
+ {
+ if ($this->_escape_char === '')
+ {
+ return $item;
+ }
+ elseif (is_array($item))
+ {
+ foreach ($item as $key => $value)
{
- return $this->display_error('db_field_param_missing');
+ $item[$key] = $this->escape_identifiers($value);
}
- return FALSE;
+
+ return $item;
}
- $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
+ static $preg_ec = array();
- return $query->field_data();
+ if (empty($preg_ec))
+ {
+ if (is_array($this->_escape_char))
+ {
+ $preg_ec = array(preg_quote($this->_escape_char[0]), preg_quote($this->_escape_char[1]));
+ }
+ else
+ {
+ $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char);
+ }
+ }
+
+ foreach ($this->_reserved_identifiers as $id)
+ {
+ if (strpos($item, '.'.$id) !== FALSE)
+ {
+ return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[0].'$1'.$preg_ec[1].'.', $item);
+ }
+ }
+
+ return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[0].'$1'.$preg_ec[1].'$2', $item);
}
// --------------------------------------------------------------------
@@ -905,12 +989,11 @@ abstract class CI_DB_driver {
*/
public function insert_string($table, $data)
{
- $fields = array();
- $values = array();
+ $fields = $values = array();
foreach ($data as $key => $val)
{
- $fields[] = $this->_escape_identifiers($key);
+ $fields[] = $this->escape_identifiers($key);
$values[] = $this->escape($val);
}
@@ -929,7 +1012,7 @@ abstract class CI_DB_driver {
*/
public function update_string($table, $data, $where)
{
- if ($where == '')
+ if ($where === '')
{
return FALSE;
}
@@ -949,7 +1032,7 @@ abstract class CI_DB_driver {
$dest = array();
foreach ($where as $key => $val)
{
- $prefix = (count($dest) == 0) ? '' : ' AND ';
+ $prefix = (count($dest) === 0) ? '' : ' AND ';
$key = $this->protect_identifiers($key);
if ($val !== '')
@@ -979,13 +1062,7 @@ abstract class CI_DB_driver {
*/
protected function _has_operator($str)
{
- $str = trim($str);
- if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
- {
- return FALSE;
- }
-
- return TRUE;
+ return (bool) preg_match('/(\s|<|>|!|=|IS NULL|IS NOT NULL)/i', trim($str));
}
// --------------------------------------------------------------------
@@ -999,7 +1076,7 @@ abstract class CI_DB_driver {
*/
public function call_function($function)
{
- $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
+ $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
if (FALSE === strpos($driver, $function))
{
@@ -1008,25 +1085,12 @@ abstract class CI_DB_driver {
if ( ! function_exists($function))
{
- if ($this->db_debug)
- {
- return $this->display_error('db_unsupported_function');
- }
- return FALSE;
+ return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
- else
- {
- $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
- if (is_null($args))
- {
- return call_user_func($function);
- }
- else
- {
- return call_user_func_array($function, $args);
- }
- }
+ return (func_num_args() > 1)
+ ? call_user_func_array($function, array_splice(func_get_args(), 1))
+ : call_user_func($function);
}
// --------------------------------------------------------------------
@@ -1051,8 +1115,7 @@ abstract class CI_DB_driver {
*/
public function cache_on()
{
- $this->cache_on = TRUE;
- return TRUE;
+ return $this->cache_on = TRUE;
}
// --------------------------------------------------------------------
@@ -1064,8 +1127,7 @@ abstract class CI_DB_driver {
*/
public function cache_off()
{
- $this->cache_on = FALSE;
- return FALSE;
+ return $this->cache_on = FALSE;
}
@@ -1078,11 +1140,9 @@ abstract class CI_DB_driver {
*/
public function cache_delete($segment_one = '', $segment_two = '')
{
- if ( ! $this->_cache_init())
- {
- return FALSE;
- }
- return $this->CACHE->delete($segment_one, $segment_two);
+ return ($this->_cache_init())
+ ? $this->CACHE->delete($segment_one, $segment_two)
+ : FALSE;
}
// --------------------------------------------------------------------
@@ -1094,12 +1154,9 @@ abstract class CI_DB_driver {
*/
public function cache_delete_all()
{
- if ( ! $this->_cache_init())
- {
- return FALSE;
- }
-
- return $this->CACHE->delete_all();
+ return ($this->_cache_init())
+ ? $this->CACHE->delete_all()
+ : FALSE;
}
// --------------------------------------------------------------------
@@ -1111,18 +1168,17 @@ abstract class CI_DB_driver {
*/
protected function _cache_init()
{
- if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
- {
- return TRUE;
- }
-
- if ( ! class_exists('CI_DB_Cache'))
+ if (class_exists('CI_DB_Cache'))
{
- if ( ! @include(BASEPATH.'database/DB_cache.php'))
+ if (is_object($this->CACHE))
{
- return $this->cache_off();
+ return TRUE;
}
}
+ elseif ( ! @include_once(BASEPATH.'database/DB_cache.php'))
+ {
+ return $this->cache_off();
+ }
$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
return TRUE;
@@ -1137,10 +1193,24 @@ abstract class CI_DB_driver {
*/
public function close()
{
- if (is_resource($this->conn_id) OR is_object($this->conn_id))
+ if ($this->conn_id)
{
- $this->_close($this->conn_id);
+ $this->_close();
+ $this->conn_id = FALSE;
}
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Close DB Connection
+ *
+ * This method would be overriden by most of the drivers.
+ *
+ * @return void
+ */
+ protected function _close()
+ {
$this->conn_id = FALSE;
}
@@ -1161,7 +1231,7 @@ abstract class CI_DB_driver {
$heading = $LANG->line('db_error_heading');
- if ($native == TRUE)
+ if ($native === TRUE)
{
$message = (array) $error;
}
@@ -1173,9 +1243,7 @@ abstract class CI_DB_driver {
// Find the most likely culprit of the error by going through
// the backtrace until the source file is no longer in the
// database folder.
-
$trace = debug_backtrace();
-
foreach ($trace as $call)
{
if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
@@ -1183,7 +1251,6 @@ abstract class CI_DB_driver {
// Found it - use a relative path for safety
$message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
$message[] = 'Line Number: '.$call['line'];
-
break;
}
}
@@ -1198,10 +1265,10 @@ abstract class CI_DB_driver {
/**
* Protect Identifiers
*
- * This function is used extensively by the Active Record class, and by
+ * This function is used extensively by the Query Builder class, and by
* a couple functions in this class.
* It takes a column or table name (optionally with an alias) and inserts
- * the table prefix onto it. Some logic is necessary in order to deal with
+ * the table prefix onto it. Some logic is necessary in order to deal with
* column names that include the path. Consider a query like this:
*
* SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
@@ -1244,12 +1311,15 @@ abstract class CI_DB_driver {
// If the item has an alias declaration we remove it and set it aside.
// Basically we remove everything to the right of the first space
- $alias = '';
if (strpos($item, ' ') !== FALSE)
{
- $alias = strstr($item, " ");
+ $alias = strstr($item, ' ');
$item = substr($item, 0, - strlen($alias));
}
+ else
+ {
+ $alias = '';
+ }
// This is basically a bug fix for queries that use MAX, MIN, etc.
// If a parenthesis is found we know that we do not need to
@@ -1270,7 +1340,7 @@ abstract class CI_DB_driver {
// Does the first segment of the exploded item match
// one of the aliases previously identified? If so,
// we have nothing more to do other than escape the item
- if (in_array($parts[0], $this->ar_aliased_tables))
+ if (in_array($parts[0], $this->qb_aliased_tables))
{
if ($protect_identifiers === TRUE)
{
@@ -1278,17 +1348,18 @@ abstract class CI_DB_driver {
{
if ( ! in_array($val, $this->_reserved_identifiers))
{
- $parts[$key] = $this->_escape_identifiers($val);
+ $parts[$key] = $this->escape_identifiers($val);
}
}
$item = implode('.', $parts);
}
+
return $item.$alias;
}
// Is there a table prefix defined in the config file? If not, no need to do anything
- if ($this->dbprefix != '')
+ if ($this->dbprefix !== '')
{
// We now add the table prefix based on some logic.
// Do we have 4 segments (hostname.database.table.column)?
@@ -1312,19 +1383,18 @@ abstract class CI_DB_driver {
// This flag is set when the supplied $item does not contain a field name.
// This can happen when this function is being called from a JOIN.
- if ($field_exists == FALSE)
+ if ($field_exists === FALSE)
{
$i++;
}
// Verify table prefix and replace if necessary
- if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
+ if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
{
- $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
+ $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
}
-
// We only add the table prefix if it does not already exist
- if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
+ elseif (strpos($parts[$i], $this->dbprefix) !== 0)
{
$parts[$i] = $this->dbprefix.$parts[$i];
}
@@ -1335,31 +1405,30 @@ abstract class CI_DB_driver {
if ($protect_identifiers === TRUE)
{
- $item = $this->_escape_identifiers($item);
+ $item = $this->escape_identifiers($item);
}
return $item.$alias;
}
// Is there a table prefix? If not, no need to insert it
- if ($this->dbprefix != '')
+ if ($this->dbprefix !== '')
{
// Verify table prefix and replace if necessary
- if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
+ if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
{
- $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
+ $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
}
-
// Do we prefix an item with no segments?
- if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
+ elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
{
$item = $this->dbprefix.$item;
}
}
- if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
+ if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
{
- $item = $this->_escape_identifiers($item);
+ $item = $this->escape_identifiers($item);
}
return $item.$alias;
@@ -1368,13 +1437,14 @@ abstract class CI_DB_driver {
// --------------------------------------------------------------------
/**
- * Dummy method that allows Active Record class to be disabled
- *
- * This function is used extensively by every db driver.
+ * Dummy method that allows Query Builder class to be disabled
+ * and keep count_all() working.
*
* @return void
*/
- abstract protected function _reset_select();
+ protected function _reset_select()
+ {
+ }
}
diff --git a/system/database/DB_forge.php b/system/database/DB_forge.php
index 34c502a99..ff5eb3fe6 100644
--- a/system/database/DB_forge.php
+++ b/system/database/DB_forge.php
@@ -25,10 +25,8 @@
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
- * Database Utility Class
+ * Database Forge Class
*
* @category Database
* @author EllisLab Dev Team
@@ -41,6 +39,12 @@ abstract class CI_DB_forge {
public $primary_keys = array();
public $db_char_set = '';
+ // Platform specific SQL strings
+ protected $_create_database = 'CREATE DATABASE %s';
+ protected $_drop_database = 'DROP DATABASE %s';
+ protected $_drop_table = 'DROP TABLE IF EXISTS %s';
+ protected $_rename_table = 'ALTER TABLE %s RENAME TO %s';
+
public function __construct()
{
// Assign the main database object to $this->db
@@ -59,8 +63,16 @@ abstract class CI_DB_forge {
*/
public function create_database($db_name)
{
- $sql = $this->_create_database($db_name);
- return is_bool($sql) ? $sql : $this->db->query($sql);
+ if ($this->_create_database === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
+ }
+ elseif ( ! $this->db->query(sprintf($this->_create_database, $db_name, $this->db->char_set, $this->db->dbcollat)))
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
+ }
+
+ return TRUE;
}
// --------------------------------------------------------------------
@@ -73,8 +85,21 @@ abstract class CI_DB_forge {
*/
public function drop_database($db_name)
{
- $sql = $this->_drop_database($db_name);
- return is_bool($sql) ? $sql : $this->db->query($sql);
+ if ($db_name === '')
+ {
+ show_error('A table name is required for that operation.');
+ return FALSE;
+ }
+ elseif ($this->_drop_database === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
+ }
+ elseif ( ! $this->db->query(sprintf($this->_drop_database, $db_name)))
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
+ }
+
+ return TRUE;
}
// --------------------------------------------------------------------
@@ -98,7 +123,7 @@ abstract class CI_DB_forge {
return;
}
- if ($key == '')
+ if ($key === '')
{
show_error('Key information is required for that operation.');
}
@@ -125,7 +150,7 @@ abstract class CI_DB_forge {
*/
public function add_field($field = '')
{
- if ($field == '')
+ if ($field === '')
{
show_error('Field information is required.');
}
@@ -172,7 +197,7 @@ abstract class CI_DB_forge {
*/
public function create_table($table = '', $if_not_exists = FALSE)
{
- if ($table == '')
+ if ($table === '')
{
show_error('A table name is required for that operation.');
}
@@ -197,8 +222,16 @@ abstract class CI_DB_forge {
*/
public function drop_table($table_name)
{
- $sql = $this->_drop_table($this->db->dbprefix.$table_name);
- return is_bool($sql) ? $sql : $this->db->query($sql);
+ if ($table_name === '')
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_table_name_required') : FALSE;
+ }
+ elseif ($this->_drop_table === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
+ }
+
+ return $this->db->query(sprintf($this->_drop_table, $this->db->escape_identifiers($this->db->dbprefix.$table_name)));
}
// --------------------------------------------------------------------
@@ -212,12 +245,20 @@ abstract class CI_DB_forge {
*/
public function rename_table($table_name, $new_table_name)
{
- if ($table_name == '' OR $new_table_name == '')
+ if ($table_name === '' OR $new_table_name === '')
{
show_error('A table name is required for that operation.');
+ return FALSE;
+ }
+ elseif ($this->_rename_table === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
}
- return $this->db->query($this->_rename_table($this->db->dbprefix.$table_name, $this->db->dbprefix.$new_table_name));
+ return $this->db->query(sprintf($this->_rename_table,
+ $this->db->escape_identifiers($this->db->dbprefix.$table_name),
+ $this->db->escape_identifiers($this->db->dbprefix.$new_table_name))
+ );
}
// --------------------------------------------------------------------
@@ -232,7 +273,7 @@ abstract class CI_DB_forge {
*/
public function add_column($table = '', $field = array(), $after_field = '')
{
- if ($table == '')
+ if ($table === '')
{
show_error('A table name is required for that operation.');
}
@@ -243,7 +284,7 @@ abstract class CI_DB_forge {
{
$this->add_field(array($k => $field[$k]));
- if (count($this->fields) == 0)
+ if (count($this->fields) === 0)
{
show_error('Field information is required.');
}
@@ -271,12 +312,12 @@ abstract class CI_DB_forge {
*/
public function drop_column($table = '', $column_name = '')
{
- if ($table == '')
+ if ($table === '')
{
show_error('A table name is required for that operation.');
}
- if ($column_name == '')
+ if ($column_name === '')
{
show_error('A column name is required for that operation.');
}
@@ -296,7 +337,7 @@ abstract class CI_DB_forge {
*/
public function modify_column($table = '', $field = array())
{
- if ($table == '')
+ if ($table === '')
{
show_error('A table name is required for that operation.');
}
diff --git a/system/database/DB_active_rec.php b/system/database/DB_query_builder.php
index b324226ab..3ed556212 100644
--- a/system/database/DB_active_rec.php
+++ b/system/database/DB_query_builder.php
@@ -26,9 +26,9 @@
*/
/**
- * Active Record Class
+ * Query Builder Class
*
- * This is the platform-independent base Active Record implementation class.
+ * This is the platform-independent base Query Builder implementation class.
*
* @package CodeIgniter
* @subpackage Drivers
@@ -36,46 +36,47 @@
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
-abstract class CI_DB_active_record extends CI_DB_driver {
+
+abstract class CI_DB_query_builder extends CI_DB_driver {
protected $return_delete_sql = FALSE;
protected $reset_delete_data = FALSE;
- protected $ar_select = array();
- protected $ar_distinct = FALSE;
- protected $ar_from = array();
- protected $ar_join = array();
- protected $ar_where = array();
- protected $ar_like = array();
- protected $ar_groupby = array();
- protected $ar_having = array();
- protected $ar_keys = array();
- protected $ar_limit = FALSE;
- protected $ar_offset = FALSE;
- protected $ar_order = FALSE;
- protected $ar_orderby = array();
- protected $ar_set = array();
- protected $ar_wherein = array();
- protected $ar_aliased_tables = array();
- protected $ar_store_array = array();
- protected $ar_where_group_started = FALSE;
- protected $ar_where_group_count = 0;
-
- // Active Record Caching variables
- protected $ar_caching = FALSE;
- protected $ar_cache_exists = array();
- protected $ar_cache_select = array();
- protected $ar_cache_from = array();
- protected $ar_cache_join = array();
- protected $ar_cache_where = array();
- protected $ar_cache_like = array();
- protected $ar_cache_groupby = array();
- protected $ar_cache_having = array();
- protected $ar_cache_orderby = array();
- protected $ar_cache_set = array();
-
- protected $ar_no_escape = array();
- protected $ar_cache_no_escape = array();
+ protected $qb_select = array();
+ protected $qb_distinct = FALSE;
+ protected $qb_from = array();
+ protected $qb_join = array();
+ protected $qb_where = array();
+ protected $qb_like = array();
+ protected $qb_groupby = array();
+ protected $qb_having = array();
+ protected $qb_keys = array();
+ protected $qb_limit = FALSE;
+ protected $qb_offset = FALSE;
+ protected $qb_order = FALSE;
+ protected $qb_orderby = array();
+ protected $qb_set = array();
+ protected $qb_wherein = array();
+ protected $qb_aliased_tables = array();
+ protected $qb_store_array = array();
+ protected $qb_where_group_started = FALSE;
+ protected $qb_where_group_count = 0;
+
+ // Query Builder Caching variables
+ protected $qb_caching = FALSE;
+ protected $qb_cache_exists = array();
+ protected $qb_cache_select = array();
+ protected $qb_cache_from = array();
+ protected $qb_cache_join = array();
+ protected $qb_cache_where = array();
+ protected $qb_cache_like = array();
+ protected $qb_cache_groupby = array();
+ protected $qb_cache_having = array();
+ protected $qb_cache_orderby = array();
+ protected $qb_cache_set = array();
+
+ protected $qb_no_escape = array();
+ protected $qb_cache_no_escape = array();
/**
* Select
@@ -96,16 +97,16 @@ abstract class CI_DB_active_record extends CI_DB_driver {
{
$val = trim($val);
- if ($val != '')
+ if ($val !== '')
{
- $this->ar_select[] = $val;
- $this->ar_no_escape[] = $escape;
+ $this->qb_select[] = $val;
+ $this->qb_no_escape[] = $escape;
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_select[] = $val;
- $this->ar_cache_exists[] = 'select';
- $this->ar_cache_no_escape[] = $escape;
+ $this->qb_cache_select[] = $val;
+ $this->qb_cache_exists[] = 'select';
+ $this->qb_cache_no_escape[] = $escape;
}
}
}
@@ -193,7 +194,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX')
{
- if ( ! is_string($select) OR $select == '')
+ if ( ! is_string($select) OR $select === '')
{
$this->display_error('db_invalid_query');
}
@@ -205,19 +206,20 @@ abstract class CI_DB_active_record extends CI_DB_driver {
show_error('Invalid function type: '.$type);
}
- if ($alias == '')
+ if ($alias === '')
{
$alias = $this->_create_alias_from_table(trim($select));
}
- $sql = $this->protect_identifiers($type.'('.trim($select).')').' AS '.$this->protect_identifiers(trim($alias));
- $this->ar_select[] = $sql;
- $this->ar_no_escape[] = NULL;
+ $sql = $this->protect_identifiers($type.'('.trim($select).')').' AS '.$this->escape_identifiers(trim($alias));
+
+ $this->qb_select[] = $sql;
+ $this->qb_no_escape[] = NULL;
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_select[] = $sql;
- $this->ar_cache_exists[] = 'select';
+ $this->qb_cache_select[] = $sql;
+ $this->qb_cache_exists[] = 'select';
}
return $this;
@@ -254,7 +256,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function distinct($val = TRUE)
{
- $this->ar_distinct = (is_bool($val)) ? $val : TRUE;
+ $this->qb_distinct = is_bool($val) ? $val : TRUE;
return $this;
}
@@ -270,7 +272,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function from($from)
{
- foreach ((array)$from as $val)
+ foreach ((array) $from as $val)
{
if (strpos($val, ',') !== FALSE)
{
@@ -278,12 +280,13 @@ abstract class CI_DB_active_record extends CI_DB_driver {
{
$v = trim($v);
$this->_track_aliases($v);
- $v = $this->ar_from[] = $this->protect_identifiers($v, TRUE, NULL, FALSE);
- if ($this->ar_caching === TRUE)
+ $this->qb_from[] = $v = $this->protect_identifiers($v, TRUE, NULL, FALSE);
+
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_from[] = $v;
- $this->ar_cache_exists[] = 'from';
+ $this->qb_cache_from[] = $v;
+ $this->qb_cache_exists[] = 'from';
}
}
}
@@ -292,14 +295,15 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$val = trim($val);
// Extract any aliases that might exist. We use this information
- // in the _protect_identifiers to know whether to add a table prefix
+ // in the protect_identifiers to know whether to add a table prefix
$this->_track_aliases($val);
- $this->ar_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE);
- if ($this->ar_caching === TRUE)
+ $this->qb_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE);
+
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_from[] = $val;
- $this->ar_cache_exists[] = 'from';
+ $this->qb_cache_from[] = $val;
+ $this->qb_cache_exists[] = 'from';
}
}
}
@@ -321,7 +325,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function join($table, $cond, $type = '')
{
- if ($type != '')
+ if ($type !== '')
{
$type = strtoupper(trim($type));
@@ -336,7 +340,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
// Extract any aliases that might exist. We use this information
- // in the _protect_identifiers to know whether to add a table prefix
+ // in the protect_identifiers to know whether to add a table prefix
$this->_track_aliases($table);
// Strip apart the condition and protect the identifiers
@@ -346,12 +350,12 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
// Assemble the JOIN statement
- $this->ar_join[] = $join = $type.'JOIN '.$this->protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;
+ $this->qb_join[] = $join = $type.'JOIN '.$this->protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_join[] = $join;
- $this->ar_cache_exists[] = 'join';
+ $this->qb_cache_join[] = $join;
+ $this->qb_cache_exists[] = 'join';
}
return $this;
@@ -420,7 +424,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach ($key as $k => $v)
{
- $prefix = (count($this->ar_where) === 0 && count($this->ar_cache_where) === 0) ? '' : $type;
+ $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
if (is_null($v) && ! $this->_has_operator($k))
{
@@ -446,11 +450,11 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$k = $this->protect_identifiers($k, FALSE, $escape);
}
- $this->ar_where[] = $prefix.$k.$v;
- if ($this->ar_caching === TRUE)
+ $this->qb_where[] = $prefix.$k.$v;
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_where[] = $prefix.$k.$v;
- $this->ar_cache_exists[] = 'where';
+ $this->qb_cache_where[] = $prefix.$k.$v;
+ $this->qb_cache_exists[] = 'where';
}
}
@@ -557,20 +561,20 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach ($values as $value)
{
- $this->ar_wherein[] = $this->escape($value);
+ $this->qb_wherein[] = $this->escape($value);
}
- $prefix = (count($this->ar_where) === 0) ? '' : $type;
- $this->ar_where[] = $where_in = $prefix.$this->protect_identifiers($key).$not.' IN ('.implode(', ', $this->ar_wherein).') ';
+ $prefix = (count($this->qb_where) === 0) ? '' : $type;
+ $this->qb_where[] = $where_in = $prefix.$this->protect_identifiers($key).$not.' IN ('.implode(', ', $this->qb_wherein).') ';
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_where[] = $where_in;
- $this->ar_cache_exists[] = 'where';
+ $this->qb_cache_where[] = $where_in;
+ $this->qb_cache_exists[] = 'where';
}
// reset the array for multiple calls
- $this->ar_wherein = array();
+ $this->qb_wherein = array();
return $this;
}
@@ -666,37 +670,37 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach ($field as $k => $v)
{
$k = $this->protect_identifiers($k);
- $prefix = (count($this->ar_like) === 0) ? '' : $type;
+ $prefix = (count($this->qb_like) === 0) ? '' : $type;
$v = $this->escape_like_str($v);
if ($side === 'none')
{
- $like_statement = $prefix." $k $not LIKE '{$v}'";
+ $like_statement = "{$prefix} $k $not LIKE '{$v}'";
}
elseif ($side === 'before')
{
- $like_statement = $prefix." $k $not LIKE '%{$v}'";
+ $like_statement = "{$prefix} $k $not LIKE '%{$v}'";
}
elseif ($side === 'after')
{
- $like_statement = $prefix." $k $not LIKE '{$v}%'";
+ $like_statement = "{$prefix} $k $not LIKE '{$v}%'";
}
else
{
- $like_statement = $prefix." $k $not LIKE '%{$v}%'";
+ $like_statement = "{$prefix} $k $not LIKE '%{$v}%'";
}
// some platforms require an escape sequence definition for LIKE wildcards
- if ($this->_like_escape_str != '')
+ if ($this->_like_escape_str !== '')
{
$like_statement = $like_statement.sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
- $this->ar_like[] = $like_statement;
- if ($this->ar_caching === TRUE)
+ $this->qb_like[] = $like_statement;
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_like[] = $like_statement;
- $this->ar_cache_exists[] = 'like';
+ $this->qb_cache_like[] = $like_statement;
+ $this->qb_cache_exists[] = 'like';
}
}
@@ -716,13 +720,14 @@ abstract class CI_DB_active_record extends CI_DB_driver {
public function group_start($not = '', $type = 'AND ')
{
$type = $this->_group_get_type($type);
- $this->ar_where_group_started = TRUE;
- $prefix = (count($this->ar_where) === 0 && count($this->ar_cache_where) === 0) ? '' : $type;
- $this->ar_where[] = $value = $prefix.$not.str_repeat(' ', ++$this->ar_where_group_count).' (';
- if ($this->ar_caching)
+ $this->qb_where_group_started = TRUE;
+ $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
+ $this->qb_where[] = $value = $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (';
+
+ if ($this->qb_caching)
{
- $this->ar_cache_where[] = $value;
+ $this->qb_cache_where[] = $value;
}
return $this;
@@ -773,12 +778,12 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function group_end()
{
- $this->ar_where_group_started = FALSE;
- $this->ar_where[] = $value = str_repeat(' ', $this->ar_where_group_count--) . ')';
+ $this->qb_where_group_started = FALSE;
+ $this->qb_where[] = $value = str_repeat(' ', $this->qb_where_group_count--) . ')';
- if ($this->ar_caching)
+ if ($this->qb_caching)
{
- $this->ar_cache_where[] = $value;
+ $this->qb_cache_where[] = $value;
}
return $this;
@@ -796,10 +801,10 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
protected function _group_get_type($type)
{
- if ($this->ar_where_group_started)
+ if ($this->qb_where_group_started)
{
$type = '';
- $this->ar_where_group_started = FALSE;
+ $this->qb_where_group_started = FALSE;
}
return $type;
@@ -824,14 +829,14 @@ abstract class CI_DB_active_record extends CI_DB_driver {
{
$val = trim($val);
- if ($val != '')
+ if ($val !== '')
{
- $this->ar_groupby[] = $val = $this->protect_identifiers($val);
+ $this->qb_groupby[] = $val = $this->protect_identifiers($val);
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_groupby[] = $val;
- $this->ar_cache_exists[] = 'groupby';
+ $this->qb_cache_groupby[] = $val;
+ $this->qb_cache_exists[] = 'groupby';
}
}
}
@@ -891,7 +896,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach ($key as $k => $v)
{
- $prefix = (count($this->ar_having) === 0) ? '' : $type;
+ $prefix = (count($this->qb_having) === 0) ? '' : $type;
if ($escape === TRUE)
{
@@ -903,16 +908,16 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$k .= ' = ';
}
- if ($v != '')
+ if ($v !== '')
{
$v = ' '.$this->escape($v);
}
- $this->ar_having[] = $prefix.$k.$v;
- if ($this->ar_caching === TRUE)
+ $this->qb_having[] = $prefix.$k.$v;
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_having[] = $prefix.$k.$v;
- $this->ar_cache_exists[] = 'having';
+ $this->qb_cache_having[] = $prefix.$k.$v;
+ $this->qb_cache_exists[] = 'having';
}
}
@@ -936,7 +941,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$orderby = ''; // Random results want or don't need a field name
$direction = $this->_random_keyword;
}
- elseif (trim($direction) != '')
+ elseif (trim($direction) !== '')
{
$direction = (in_array(strtoupper(trim($direction)), array('ASC', 'DESC'), TRUE)) ? ' '.$direction : ' ASC';
}
@@ -948,7 +953,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach (explode(',', $orderby) as $part)
{
$part = trim($part);
- if ( ! in_array($part, $this->ar_aliased_tables))
+ if ( ! in_array($part, $this->qb_aliased_tables))
{
$part = $this->protect_identifiers(trim($part));
}
@@ -958,7 +963,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$orderby = implode(', ', $temp);
}
- elseif ($direction != $this->_random_keyword)
+ elseif ($direction !== $this->_random_keyword)
{
if ($escape === TRUE)
{
@@ -966,12 +971,12 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
}
- $this->ar_orderby[] = $orderby_statement = $orderby.$direction;
+ $this->qb_orderby[] = $orderby_statement = $orderby.$direction;
- if ($this->ar_caching === TRUE)
+ if ($this->qb_caching === TRUE)
{
- $this->ar_cache_orderby[] = $orderby_statement;
- $this->ar_cache_exists[] = 'orderby';
+ $this->qb_cache_orderby[] = $orderby_statement;
+ $this->qb_cache_exists[] = 'orderby';
}
return $this;
@@ -988,11 +993,11 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function limit($value, $offset = NULL)
{
- $this->ar_limit = (int) $value;
+ $this->qb_limit = (int) $value;
if ( ! is_null($offset))
{
- $this->ar_offset = (int) $offset;
+ $this->qb_offset = (int) $offset;
}
return $this;
@@ -1008,7 +1013,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function offset($offset)
{
- $this->ar_offset = (int) $offset;
+ $this->qb_offset = (int) $offset;
return $this;
}
@@ -1035,11 +1040,11 @@ abstract class CI_DB_active_record extends CI_DB_driver {
{
if ($escape === FALSE)
{
- $this->ar_set[$this->protect_identifiers($k)] = $v;
+ $this->qb_set[$this->protect_identifiers($k)] = $v;
}
else
{
- $this->ar_set[$this->protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
+ $this->qb_set[$this->protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
@@ -1054,12 +1059,12 @@ abstract class CI_DB_active_record extends CI_DB_driver {
* Compiles a SELECT query string and returns the sql.
*
* @param string the table name to select from (optional)
- * @param bool TRUE: resets AR values; FALSE: leave AR vaules alone
+ * @param bool TRUE: resets QB values; FALSE: leave QB vaules alone
* @return string
*/
public function get_compiled_select($table = '', $reset = TRUE)
{
- if ($table != '')
+ if ($table !== '')
{
$this->_track_aliases($table);
$this->from($table);
@@ -1090,7 +1095,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function get($table = '', $limit = null, $offset = null)
{
- if ($table != '')
+ if ($table !== '')
{
$this->_track_aliases($table);
$this->from($table);
@@ -1106,18 +1111,20 @@ abstract class CI_DB_active_record extends CI_DB_driver {
return $result;
}
+ // --------------------------------------------------------------------
+
/**
* "Count All Results" query
*
* Generates a platform-specific query string that counts all records
- * returned by an Active Record query.
+ * returned by an Query Builder query.
*
* @param string
* @return string
*/
public function count_all_results($table = '')
{
- if ($table != '')
+ if ($table !== '')
{
$this->_track_aliases($table);
$this->from($table);
@@ -1134,6 +1141,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$row = $result->row();
return (int) $row->numrows;
}
+
// --------------------------------------------------------------------
/**
@@ -1148,7 +1156,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function get_where($table = '', $where = null, $limit = null, $offset = null)
{
- if ($table != '')
+ if ($table !== '')
{
$this->from($table);
}
@@ -1186,7 +1194,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$this->set_insert_batch($set);
}
- if (count($this->ar_set) === 0)
+ if (count($this->qb_set) === 0)
{
if ($this->db_debug)
{
@@ -1196,20 +1204,20 @@ abstract class CI_DB_active_record extends CI_DB_driver {
return FALSE;
}
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
// Batch this baby
- for ($i = 0, $total = count($this->ar_set); $i < $total; $i += 100)
+ for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100)
{
- $this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100)));
+ $this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, 100)));
}
$this->_reset_write();
@@ -1219,6 +1227,23 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Insert_batch statement
+ *
+ * Generates a platform-specific insert string from the supplied data.
+ *
+ * @param string the table name
+ * @param array the insert keys
+ * @param array the insert values
+ * @return string
+ */
+ protected function _insert_batch($table, $keys, $values)
+ {
+ return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
*
* @param mixed
@@ -1235,15 +1260,16 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$key = array($key => $value);
}
- $keys = array_keys(current($key));
+ $keys = array_keys($this->_object_to_array(current($key)));
sort($keys);
foreach ($key as $row)
{
+ $row = $this->_object_to_array($row);
if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
{
// batch function above returns an error on an empty array
- $this->ar_set[] = array();
+ $this->qb_set[] = array();
return;
}
@@ -1251,7 +1277,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
if ($escape === FALSE)
{
- $this->ar_set[] = '('.implode(',', $row).')';
+ $this->qb_set[] = '('.implode(',', $row).')';
}
else
{
@@ -1261,13 +1287,13 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$clean[] = $this->escape($value);
}
- $this->ar_set[] = '('.implode(',', $clean).')';
+ $this->qb_set[] = '('.implode(',', $clean).')';
}
}
foreach ($keys as $k)
{
- $this->ar_keys[] = $this->protect_identifiers($k);
+ $this->qb_keys[] = $this->protect_identifiers($k);
}
return $this;
@@ -1281,7 +1307,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
* Compiles an insert query and returns the sql
*
* @param string the table to insert into
- * @param bool TRUE: reset AR values; FALSE: leave AR values alone
+ * @param bool TRUE: reset QB values; FALSE: leave QB values alone
* @return string
*/
public function get_compiled_insert($table = '', $reset = TRUE)
@@ -1292,9 +1318,11 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
$sql = $this->_insert(
- $this->protect_identifiers($this->ar_from[0], TRUE, NULL, FALSE),
- array_keys($this->ar_set),
- array_values($this->ar_set)
+ $this->protect_identifiers(
+ $this->qb_from[0], TRUE, NULL, FALSE
+ ),
+ array_keys($this->qb_set),
+ array_values($this->qb_set)
);
if ($reset === TRUE)
@@ -1329,9 +1357,11 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
$sql = $this->_insert(
- $this->protect_identifiers($this->ar_from[0], TRUE, NULL, FALSE),
- array_keys($this->ar_set),
- array_values($this->ar_set)
+ $this->protect_identifiers(
+ $this->qb_from[0], TRUE, NULL, FALSE
+ ),
+ array_keys($this->qb_set),
+ array_values($this->qb_set)
);
$this->_reset_write();
@@ -1341,6 +1371,23 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Insert statement
+ *
+ * Generates a platform-specific insert string from the supplied data
+ *
+ * @param string the table name
+ * @param array the insert keys
+ * @param array the insert values
+ * @return string
+ */
+ protected function _insert($table, $keys, $values)
+ {
+ return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Validate Insert
*
* This method is used by both insert() and get_compiled_insert() to
@@ -1352,21 +1399,18 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
protected function _validate_insert($table = '')
{
- if (count($this->ar_set) === 0)
+ if (count($this->qb_set) === 0)
{
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
- if ($table == '')
+ if ($table !== '')
{
- if ( ! isset($this->ar_from[0]))
- {
- return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
- }
+ $this->qb_from[0] = $table;
}
- else
+ elseif ( ! isset($this->qb_from[0]))
{
- $this->ar_from[0] = $table;
+ return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
return TRUE;
@@ -1390,22 +1434,23 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$this->set($set);
}
- if (count($this->ar_set) === 0)
+ if (count($this->qb_set) === 0)
{
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
- $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
+ $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set));
+
$this->_reset_write();
return $this->query($sql);
}
@@ -1413,12 +1458,47 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Replace statement
+ *
+ * Generates a platform-specific replace string from the supplied data
+ *
+ * @param string the table name
+ * @param array the insert keys
+ * @param array the insert values
+ * @return string
+ */
+ protected function _replace($table, $keys, $values)
+ {
+ return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * From Tables
+ *
+ * This public function implicitly groups FROM tables so there is no confusion
+ * about operator precedence in harmony with SQL standards
+ *
+ * @param array
+ * @return string
+ */
+ protected function _from_tables($tables)
+ {
+ is_array($tables) OR $tables = array($tables);
+
+ return (count($tables) === 1) ? $tables[0] : '('.implode(', ', $tables).')';
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Get UPDATE query string
*
* Compiles an update query and returns the sql
*
* @param string the table to update
- * @param bool TRUE: reset AR values; FALSE: leave AR values alone
+ * @param bool TRUE: reset QB values; FALSE: leave QB values alone
* @return string
*/
public function get_compiled_update($table = '', $reset = TRUE)
@@ -1431,7 +1511,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
return FALSE;
}
- $sql = $this->_update($this->protect_identifiers($this->ar_from[0], TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);
+ $sql = $this->_update($this->protect_identifiers($this->qb_from[0], TRUE, NULL, FALSE), $this->qb_set, $this->qb_where, $this->qb_orderby, $this->qb_limit);
if ($reset === TRUE)
{
@@ -1468,7 +1548,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
return FALSE;
}
- if ($where != NULL)
+ if ($where !== NULL)
{
$this->where($where);
}
@@ -1478,7 +1558,8 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$this->limit($limit);
}
- $sql = $this->_update($this->protect_identifiers($this->ar_from[0], TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit, $this->ar_like);
+ $sql = $this->_update($this->protect_identifiers($this->qb_from[0], TRUE, NULL, FALSE), $this->qb_set, $this->qb_where, $this->qb_orderby, $this->qb_limit, $this->qb_like);
+
$this->_reset_write();
return $this->query($sql);
}
@@ -1486,6 +1567,41 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Update statement
+ *
+ * Generates a platform-specific update string from the supplied data
+ *
+ * @param string the table name
+ * @param array the update data
+ * @param array the where clause
+ * @param array the orderby clause
+ * @param array the limit clause
+ * @param array the like clause
+ * @return string
+ */
+ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
+ {
+ foreach ($values as $key => $val)
+ {
+ $valstr[] = $key.' = '.$val;
+ }
+
+ $where = empty($where) ? '' : ' WHERE '.implode(' ', $where);
+
+ if ( ! empty($like))
+ {
+ $where .= ($where === '' ? ' WHERE ' : ' AND ').implode(' ', $like);
+ }
+
+ return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
+ .$where
+ .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '')
+ .($limit ? ' LIMIT '.$limit : '');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Validate Update
*
* This method is used by both update() and get_compiled_update() to
@@ -1497,21 +1613,18 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
protected function _validate_update($table = '')
{
- if (count($this->ar_set) == 0)
+ if (count($this->qb_set) === 0)
{
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
- if ($table == '')
+ if ($table !== '')
{
- if ( ! isset($this->ar_from[0]))
- {
- return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
- }
+ $this->qb_from[0] = $table;
}
- else
+ elseif ( ! isset($this->qb_from[0]))
{
- $this->ar_from[0] = $table;
+ return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
return TRUE;
@@ -1544,25 +1657,25 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$this->set_update_batch($set, $index);
}
- if (count($this->ar_set) === 0)
+ if (count($this->qb_set) === 0)
{
return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE;
}
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
// Batch this baby
- for ($i = 0, $total = count($this->ar_set); $i < $total; $i += 100)
+ for ($i = 0, $total = count($this->qb_set); $i < $total; $i += 100)
{
- $this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->ar_set, $i, 100), $this->protect_identifiers($index), $this->ar_where));
+ $this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set, $i, 100), $this->protect_identifiers($index), $this->qb_where));
}
$this->_reset_write();
@@ -1594,24 +1707,20 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$clean = array();
foreach ($v as $k2 => $v2)
{
- if ($k2 == $index)
+ if ($k2 === $index)
{
$index_set = TRUE;
}
- else
- {
- $not[] = $k.'-'.$v;
- }
$clean[$this->protect_identifiers($k2)] = ($escape === FALSE) ? $v2 : $this->escape($v2);
}
- if ($index_set == FALSE)
+ if ($index_set === FALSE)
{
return $this->display_error('db_batch_missing_index');
}
- $this->ar_set[] = $clean;
+ $this->qb_set[] = $clean;
}
return $this;
@@ -1629,14 +1738,14 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function empty_table($table = '')
{
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
else
{
@@ -1662,14 +1771,14 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function truncate($table = '')
{
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
else
{
@@ -1684,12 +1793,30 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Truncate statement
+ *
+ * Generates a platform-specific truncate string from the supplied data
+ *
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
+ *
+ * @param string the table name
+ * @return string
+ */
+ protected function _truncate($table)
+ {
+ return 'TRUNCATE '.$table;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Get DELETE query string
*
* Compiles a delete query string and returns the sql
*
* @param string the table to delete from
- * @param bool TRUE: reset AR values; FALSE: leave AR values alone
+ * @param bool TRUE: reset QB values; FALSE: leave QB values alone
* @return string
*/
public function get_compiled_delete($table = '', $reset = TRUE)
@@ -1718,14 +1845,14 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// Combine any cached components with the current statements
$this->_merge_cache();
- if ($table == '')
+ if ($table === '')
{
- if ( ! isset($this->ar_from[0]))
+ if ( ! isset($this->qb_from[0]))
{
return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE;
}
- $table = $this->ar_from[0];
+ $table = $this->qb_from[0];
}
elseif (is_array($table))
{
@@ -1742,7 +1869,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$table = $this->protect_identifiers($table, TRUE, NULL, FALSE);
}
- if ($where != '')
+ if ($where !== '')
{
$this->where($where);
}
@@ -1752,12 +1879,12 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$this->limit($limit);
}
- if (count($this->ar_where) === 0 && count($this->ar_wherein) === 0 && count($this->ar_like) === 0)
+ if (count($this->qb_where) === 0 && count($this->qb_wherein) === 0 && count($this->qb_like) === 0)
{
return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE;
}
- $sql = $this->_delete($table, $this->ar_where, $this->ar_like, $this->ar_limit);
+ $sql = $this->_delete($table, $this->qb_where, $this->qb_like, $this->qb_limit);
if ($reset_data)
{
$this->_reset_write();
@@ -1769,6 +1896,31 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
+ * Delete statement
+ *
+ * Generates a platform-specific delete string from the supplied data
+ *
+ * @param string the table name
+ * @param array the where clause
+ * @param array the like clause
+ * @param string the limit clause
+ * @return string
+ */
+ protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
+ {
+ $conditions = array();
+
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
+
+ return 'DELETE FROM '.$table
+ .(count($conditions) > 0 ? ' WHERE '.implode(' AND ', $conditions) : '')
+ .($limit ? ' LIMIT '.$limit : '');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* DB Prefix
*
* Prepends a database prefix if one exists in configuration
@@ -1778,7 +1930,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
*/
public function dbprefix($table = '')
{
- if ($table == '')
+ if ($table === '')
{
$this->display_error('db_table_name_required');
}
@@ -1839,9 +1991,9 @@ abstract class CI_DB_active_record extends CI_DB_driver {
$table = trim(strrchr($table, ' '));
// Store the alias, if it doesn't already exist
- if ( ! in_array($table, $this->ar_aliased_tables))
+ if ( ! in_array($table, $this->qb_aliased_tables))
{
- $this->ar_aliased_tables[] = $table;
+ $this->qb_aliased_tables[] = $table;
}
}
}
@@ -1868,9 +2020,9 @@ abstract class CI_DB_active_record extends CI_DB_driver {
}
else
{
- $sql = ( ! $this->ar_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
+ $sql = ( ! $this->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
- if (count($this->ar_select) === 0)
+ if (count($this->qb_select) === 0)
{
$sql .= '*';
}
@@ -1879,73 +2031,73 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// Cycle through the "select" portion of the query and prep each column name.
// The reason we protect identifiers here rather then in the select() function
// is because until the user calls the from() function we don't know if there are aliases
- foreach ($this->ar_select as $key => $val)
+ foreach ($this->qb_select as $key => $val)
{
- $no_escape = isset($this->ar_no_escape[$key]) ? $this->ar_no_escape[$key] : NULL;
- $this->ar_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape);
+ $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL;
+ $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape);
}
- $sql .= implode(', ', $this->ar_select);
+ $sql .= implode(', ', $this->qb_select);
}
}
// Write the "FROM" portion of the query
- if (count($this->ar_from) > 0)
+ if (count($this->qb_from) > 0)
{
- $sql .= "\nFROM ".$this->_from_tables($this->ar_from);
+ $sql .= "\nFROM ".$this->_from_tables($this->qb_from);
}
// Write the "JOIN" portion of the query
- if (count($this->ar_join) > 0)
+ if (count($this->qb_join) > 0)
{
- $sql .= "\n".implode("\n", $this->ar_join);
+ $sql .= "\n".implode("\n", $this->qb_join);
}
// Write the "WHERE" portion of the query
- if (count($this->ar_where) > 0 OR count($this->ar_like) > 0)
+ if (count($this->qb_where) > 0 OR count($this->qb_like) > 0)
{
$sql .= "\nWHERE ";
}
- $sql .= implode("\n", $this->ar_where);
+ $sql .= implode("\n", $this->qb_where);
// Write the "LIKE" portion of the query
- if (count($this->ar_like) > 0)
+ if (count($this->qb_like) > 0)
{
- if (count($this->ar_where) > 0)
+ if (count($this->qb_where) > 0)
{
$sql .= "\nAND ";
}
- $sql .= implode("\n", $this->ar_like);
+ $sql .= implode("\n", $this->qb_like);
}
// Write the "GROUP BY" portion of the query
- if (count($this->ar_groupby) > 0)
+ if (count($this->qb_groupby) > 0)
{
- $sql .= "\nGROUP BY ".implode(', ', $this->ar_groupby);
+ $sql .= "\nGROUP BY ".implode(', ', $this->qb_groupby);
}
// Write the "HAVING" portion of the query
- if (count($this->ar_having) > 0)
+ if (count($this->qb_having) > 0)
{
- $sql .= "\nHAVING ".implode("\n", $this->ar_having);
+ $sql .= "\nHAVING ".implode("\n", $this->qb_having);
}
// Write the "ORDER BY" portion of the query
- if (count($this->ar_orderby) > 0)
+ if (count($this->qb_orderby) > 0)
{
- $sql .= "\nORDER BY ".implode(', ', $this->ar_orderby);
- if ($this->ar_order !== FALSE)
+ $sql .= "\nORDER BY ".implode(', ', $this->qb_orderby);
+ if ($this->qb_order !== FALSE)
{
- $sql .= ($this->ar_order == 'desc') ? ' DESC' : ' ASC';
+ $sql .= ($this->qb_order === 'desc') ? ' DESC' : ' ASC';
}
}
// Write the "LIMIT" portion of the query
- if (is_numeric($this->ar_limit))
+ if (is_numeric($this->qb_limit))
{
- return $this->_limit($sql."\n", $this->ar_limit, $this->ar_offset);
+ return $this->_limit($sql."\n", $this->qb_limit, $this->qb_offset);
}
return $sql;
@@ -1961,7 +2113,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
* @param object
* @return array
*/
- public function _object_to_array($object)
+ protected function _object_to_array($object)
{
if ( ! is_object($object))
{
@@ -1972,7 +2124,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
foreach (get_object_vars($object) as $key => $val)
{
// There are some built in keys we need to ignore for this conversion
- if ( ! is_object($val) && ! is_array($val) && $key != '_parent_name')
+ if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name')
{
$array[$key] = $val;
}
@@ -1991,7 +2143,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
* @param object
* @return array
*/
- public function _object_to_array_batch($object)
+ protected function _object_to_array_batch($object)
{
if ( ! is_object($object))
{
@@ -2023,13 +2175,13 @@ abstract class CI_DB_active_record extends CI_DB_driver {
/**
* Start Cache
*
- * Starts AR caching
+ * Starts QB caching
*
* @return void
*/
public function start_cache()
{
- $this->ar_caching = TRUE;
+ $this->qb_caching = TRUE;
}
// --------------------------------------------------------------------
@@ -2037,13 +2189,13 @@ abstract class CI_DB_active_record extends CI_DB_driver {
/**
* Stop Cache
*
- * Stops AR caching
+ * Stops QB caching
*
* @return void
*/
public function stop_cache()
{
- $this->ar_caching = FALSE;
+ $this->qb_caching = FALSE;
}
// --------------------------------------------------------------------
@@ -2051,24 +2203,24 @@ abstract class CI_DB_active_record extends CI_DB_driver {
/**
* Flush Cache
*
- * Empties the AR cache
+ * Empties the QB cache
*
* @return void
*/
public function flush_cache()
{
$this->_reset_run(array(
- 'ar_cache_select' => array(),
- 'ar_cache_from' => array(),
- 'ar_cache_join' => array(),
- 'ar_cache_where' => array(),
- 'ar_cache_like' => array(),
- 'ar_cache_groupby' => array(),
- 'ar_cache_having' => array(),
- 'ar_cache_orderby' => array(),
- 'ar_cache_set' => array(),
- 'ar_cache_exists' => array(),
- 'ar_cache_no_escape' => array()
+ 'qb_cache_select' => array(),
+ 'qb_cache_from' => array(),
+ 'qb_cache_join' => array(),
+ 'qb_cache_where' => array(),
+ 'qb_cache_like' => array(),
+ 'qb_cache_groupby' => array(),
+ 'qb_cache_having' => array(),
+ 'qb_cache_orderby' => array(),
+ 'qb_cache_set' => array(),
+ 'qb_cache_exists' => array(),
+ 'qb_cache_no_escape' => array()
));
}
@@ -2077,47 +2229,47 @@ abstract class CI_DB_active_record extends CI_DB_driver {
/**
* Merge Cache
*
- * When called, this function merges any cached AR arrays with
+ * When called, this function merges any cached QB arrays with
* locally called ones.
*
* @return void
*/
protected function _merge_cache()
{
- if (count($this->ar_cache_exists) === 0)
+ if (count($this->qb_cache_exists) === 0)
{
return;
}
- foreach ($this->ar_cache_exists as $val)
+ foreach ($this->qb_cache_exists as $val)
{
- $ar_variable = 'ar_'.$val;
- $ar_cache_var = 'ar_cache_'.$val;
+ $qb_variable = 'qb_'.$val;
+ $qb_cache_var = 'qb_cache_'.$val;
- if (count($this->$ar_cache_var) === 0)
+ if (count($this->$qb_cache_var) === 0)
{
continue;
}
- $this->$ar_variable = array_unique(array_merge($this->$ar_cache_var, $this->$ar_variable));
+ $this->$qb_variable = array_unique(array_merge($this->$qb_cache_var, $this->$qb_variable));
}
// If we are "protecting identifiers" we need to examine the "from"
// portion of the query to determine if there are any aliases
- if ($this->_protect_identifiers === TRUE && count($this->ar_cache_from) > 0)
+ if ($this->_protect_identifiers === TRUE && count($this->qb_cache_from) > 0)
{
- $this->_track_aliases($this->ar_from);
+ $this->_track_aliases($this->qb_from);
}
- $this->ar_no_escape = $this->ar_cache_no_escape;
+ $this->qb_no_escape = $this->qb_cache_no_escape;
}
// --------------------------------------------------------------------
/**
- * Reset Active Record values.
+ * Reset Query Builder values.
*
- * Publicly-visible method to reset the AR values.
+ * Publicly-visible method to reset the QB values.
*
* @return void
*/
@@ -2130,16 +2282,16 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
- * Resets the active record values. Called by the get() function
+ * Resets the query builder values. Called by the get() function
*
* @param array An array of fields to reset
* @return void
*/
- protected function _reset_run($ar_reset_items)
+ protected function _reset_run($qb_reset_items)
{
- foreach ($ar_reset_items as $item => $default_value)
+ foreach ($qb_reset_items as $item => $default_value)
{
- if ( ! in_array($item, $this->ar_store_array))
+ if ( ! in_array($item, $this->qb_store_array))
{
$this->$item = $default_value;
}
@@ -2149,28 +2301,28 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
- * Resets the active record values. Called by the get() function
+ * Resets the query builder values. Called by the get() function
*
* @return void
*/
protected function _reset_select()
{
$this->_reset_run(array(
- 'ar_select' => array(),
- 'ar_from' => array(),
- 'ar_join' => array(),
- 'ar_where' => array(),
- 'ar_like' => array(),
- 'ar_groupby' => array(),
- 'ar_having' => array(),
- 'ar_orderby' => array(),
- 'ar_wherein' => array(),
- 'ar_aliased_tables' => array(),
- 'ar_no_escape' => array(),
- 'ar_distinct' => FALSE,
- 'ar_limit' => FALSE,
- 'ar_offset' => FALSE,
- 'ar_order' => FALSE
+ 'qb_select' => array(),
+ 'qb_from' => array(),
+ 'qb_join' => array(),
+ 'qb_where' => array(),
+ 'qb_like' => array(),
+ 'qb_groupby' => array(),
+ 'qb_having' => array(),
+ 'qb_orderby' => array(),
+ 'qb_wherein' => array(),
+ 'qb_aliased_tables' => array(),
+ 'qb_no_escape' => array(),
+ 'qb_distinct' => FALSE,
+ 'qb_limit' => FALSE,
+ 'qb_offset' => FALSE,
+ 'qb_order' => FALSE
)
);
}
@@ -2178,7 +2330,7 @@ abstract class CI_DB_active_record extends CI_DB_driver {
// --------------------------------------------------------------------
/**
- * Resets the active record "write" values.
+ * Resets the query builder "write" values.
*
* Called by the insert() update() insert_batch() update_batch() and delete() functions
*
@@ -2187,19 +2339,19 @@ abstract class CI_DB_active_record extends CI_DB_driver {
protected function _reset_write()
{
$this->_reset_run(array(
- 'ar_set' => array(),
- 'ar_from' => array(),
- 'ar_where' => array(),
- 'ar_like' => array(),
- 'ar_orderby' => array(),
- 'ar_keys' => array(),
- 'ar_limit' => FALSE,
- 'ar_order' => FALSE
+ 'qb_set' => array(),
+ 'qb_from' => array(),
+ 'qb_where' => array(),
+ 'qb_like' => array(),
+ 'qb_orderby' => array(),
+ 'qb_keys' => array(),
+ 'qb_limit' => FALSE,
+ 'qb_order' => FALSE
)
);
}
}
-/* End of file DB_active_rec.php */
-/* Location: ./system/database/DB_active_rec.php */ \ No newline at end of file
+/* End of file DB_query_builder.php */
+/* Location: ./system/database/DB_query_builder.php */ \ No newline at end of file
diff --git a/system/database/DB_result.php b/system/database/DB_result.php
index 04f964fb1..991f6ba94 100644
--- a/system/database/DB_result.php
+++ b/system/database/DB_result.php
@@ -57,7 +57,7 @@ class CI_DB_result {
* Query result. Acts as a wrapper function for the following functions.
*
* @param string can be "object" or "array"
- * @return mixed either a result object or array
+ * @return object
*/
public function result($type = 'object')
{
@@ -81,7 +81,7 @@ class CI_DB_result {
return $this->custom_result_object[$class_name];
}
- if ($this->result_id === FALSE OR $this->num_rows() == 0)
+ if ($this->result_id === FALSE OR $this->num_rows() === 0)
{
return array();
}
@@ -108,9 +108,9 @@ class CI_DB_result {
// --------------------------------------------------------------------
/**
- * Query result. "object" version.
+ * Query result. "object" version.
*
- * @return object
+ * @return array
*/
public function result_object()
{
@@ -122,7 +122,7 @@ class CI_DB_result {
// In the event that query caching is on the result_id variable
// will return FALSE since there isn't a valid SQL resource so
// we'll simply return an empty array.
- if ($this->result_id === FALSE OR $this->num_rows() == 0)
+ if ($this->result_id === FALSE OR $this->num_rows() === 0)
{
return array();
}
@@ -153,7 +153,7 @@ class CI_DB_result {
// In the event that query caching is on the result_id variable
// will return FALSE since there isn't a valid SQL resource so
// we'll simply return an empty array.
- if ($this->result_id === FALSE OR $this->num_rows() == 0)
+ if ($this->result_id === FALSE OR $this->num_rows() === 0)
{
return array();
}
@@ -224,7 +224,7 @@ class CI_DB_result {
return;
}
- if ($key != '' AND ! is_null($value))
+ if ($key !== '' && ! is_null($value))
{
$this->row_data[$key] = $value;
}
@@ -242,10 +242,10 @@ class CI_DB_result {
$result = $this->custom_result_object($type);
if (count($result) === 0)
{
- return $result;
+ return NULL;
}
- if ($n != $this->current_row AND isset($result[$n]))
+ if ($n !== $this->current_row && isset($result[$n]))
{
$this->current_row = $n;
}
@@ -253,6 +253,8 @@ class CI_DB_result {
return $result[$this->current_row];
}
+ // --------------------------------------------------------------------
+
/**
* Returns a single result row - object version
*
@@ -263,10 +265,10 @@ class CI_DB_result {
$result = $this->result_object();
if (count($result) === 0)
{
- return $result;
+ return NULL;
}
- if ($n != $this->current_row AND isset($result[$n]))
+ if ($n !== $this->current_row && isset($result[$n]))
{
$this->current_row = $n;
}
@@ -286,10 +288,10 @@ class CI_DB_result {
$result = $this->result_array();
if (count($result) === 0)
{
- return $result;
+ return NULL;
}
- if ($n != $this->current_row AND isset($result[$n]))
+ if ($n !== $this->current_row && isset($result[$n]))
{
$this->current_row = $n;
}
@@ -297,7 +299,6 @@ class CI_DB_result {
return $result[$this->current_row];
}
-
// --------------------------------------------------------------------
/**
@@ -308,7 +309,7 @@ class CI_DB_result {
public function first_row($type = 'object')
{
$result = $this->result($type);
- return (count($result) === 0) ? $result : $result[0];
+ return (count($result) === 0) ? NULL : $result[0];
}
// --------------------------------------------------------------------
@@ -321,7 +322,7 @@ class CI_DB_result {
public function last_row($type = 'object')
{
$result = $this->result($type);
- return (count($result) === 0) ? $result : $result[count($result) - 1];
+ return (count($result) === 0) ? NULL : $result[count($result) - 1];
}
// --------------------------------------------------------------------
@@ -336,7 +337,7 @@ class CI_DB_result {
$result = $this->result($type);
if (count($result) === 0)
{
- return $result;
+ return NULL;
}
if (isset($result[$this->current_row + 1]))
@@ -359,7 +360,7 @@ class CI_DB_result {
$result = $this->result($type);
if (count($result) === 0)
{
- return $result;
+ return NULL;
}
if (isset($result[$this->current_row - 1]))
@@ -372,11 +373,23 @@ class CI_DB_result {
// --------------------------------------------------------------------
/**
+ * Returns an unbuffered row and move pointer to next row
+ *
+ * @return mixed either a result object or array
+ */
+ public function unbuffered_row($type = 'object')
+ {
+ return ($type !== 'array') ? $this->_fetch_object() : $this->_fetch_assoc();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* The following functions are normally overloaded by the identically named
* methods in the platform-specific driver -- except when query caching
- * is used. When caching is enabled we do not load the other driver.
+ * is used. When caching is enabled we do not load the other driver.
* These functions are primarily here to prevent undefined function errors
- * when a cached result object is in use. They are not otherwise fully
+ * when a cached result object is in use. They are not otherwise fully
* operational due to the unavailability of the database resource IDs with
* cached results.
*/
@@ -384,8 +397,8 @@ class CI_DB_result {
public function num_fields() { return 0; }
public function list_fields() { return array(); }
public function field_data() { return array(); }
- public function free_result() { return TRUE; }
- protected function _data_seek() { return TRUE; }
+ public function free_result() { $this->result_id = FALSE; }
+ protected function _data_seek() { return FALSE; }
protected function _fetch_assoc() { return array(); }
protected function _fetch_object() { return array(); }
diff --git a/system/database/DB_utility.php b/system/database/DB_utility.php
index 642a004bd..02c921834 100644
--- a/system/database/DB_utility.php
+++ b/system/database/DB_utility.php
@@ -37,6 +37,11 @@ abstract class CI_DB_utility extends CI_DB_forge {
public $db;
public $data_cache = array();
+ // Platform specific SQL strings
+ // Just setting those defaults to FALSE as they are mostly MySQL-specific
+ protected $_optimize_table = FALSE;
+ protected $_repair_table = FALSE;
+
public function __construct()
{
// Assign the main database object to $this->db
@@ -50,7 +55,7 @@ abstract class CI_DB_utility extends CI_DB_forge {
/**
* List databases
*
- * @return bool
+ * @return array
*/
public function list_databases()
{
@@ -59,18 +64,25 @@ abstract class CI_DB_utility extends CI_DB_forge {
{
return $this->data_cache['db_names'];
}
+ elseif ($this->_list_databases === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
+ }
+
+ $this->data_cache['db_names'] = array();
- $query = $this->db->query($this->_list_databases());
- $dbs = array();
- if ($query->num_rows() > 0)
+ $query = $this->db->query($this->_list_databases);
+ if ($query === FALSE)
{
- foreach ($query->result_array() as $row)
- {
- $dbs[] = current($row);
- }
+ return $this->data_cache['db_names'];
+ }
+
+ for ($i = 0, $c = count($query); $i < $c; $i++)
+ {
+ $this->data_cache['db_names'] = current($query[$i]);
}
- return $this->data_cache['db_names'] = $dbs;
+ return $this->data_cache['db_names'];
}
// --------------------------------------------------------------------
@@ -79,48 +91,36 @@ abstract class CI_DB_utility extends CI_DB_forge {
* Determine if a particular database exists
*
* @param string
- * @return boolean
+ * @return bool
*/
public function database_exists($database_name)
{
- // Some databases won't have access to the list_databases() function, so
- // this is intended to allow them to override with their own functions as
- // defined in $driver_utility.php
- if (method_exists($this, '_database_exists'))
- {
- return $this->_database_exists($database_name);
- }
- else
- {
- return ( ! in_array($database_name, $this->list_databases())) ? FALSE : TRUE;
- }
+ return in_array($database_name, $this->list_databases());
}
-
// --------------------------------------------------------------------
/**
* Optimize Table
*
* @param string the table name
- * @return bool
+ * @return mixed
*/
public function optimize_table($table_name)
{
- $sql = $this->_optimize_table($table_name);
-
- if (is_bool($sql))
+ if ($this->_optimize_table === FALSE)
{
- show_error('db_must_use_set');
- return FALSE;
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
}
- $query = $this->db->query($sql);
- $res = $query->result_array();
+ $query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
+ if ($query !== FALSE)
+ {
+ $query = $query->result_array();
+ return current($res);
+ }
- // Note: Due to a bug in current() that affects some versions
- // of PHP we can not pass function call directly into it
- return current($res);
+ return FALSE;
}
// --------------------------------------------------------------------
@@ -128,26 +128,26 @@ abstract class CI_DB_utility extends CI_DB_forge {
/**
* Optimize Database
*
- * @return array
+ * @return mixed
*/
public function optimize_database()
{
+ if ($this->_optimize_table === FALSE)
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
+ }
+
$result = array();
foreach ($this->db->list_tables() as $table_name)
{
- $sql = $this->_optimize_table($table_name);
-
- if (is_bool($sql))
+ $res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
+ if (is_bool($res))
{
- return $sql;
+ return $res;
}
- $query = $this->db->query($sql);
-
// Build the result array...
- // Note: Due to a bug in current() that affects some versions
- // of PHP we can not pass function call directly into it
- $res = $query->result_array();
+ $res = $res->result_array();
$res = current($res);
$key = str_replace($this->db->database.'.', '', current($res));
$keys = array_keys($res);
@@ -165,23 +165,23 @@ abstract class CI_DB_utility extends CI_DB_forge {
* Repair Table
*
* @param string the table name
- * @return bool
+ * @return mixed
*/
public function repair_table($table_name)
{
- $sql = $this->_repair_table($table_name);
-
- if (is_bool($sql))
+ if ($this->_repair_table === FALSE)
{
- return $sql;
+ return ($this->db->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
}
- $query = $this->db->query($sql);
+ $query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name)));
+ if (is_bool($query))
+ {
+ return $query;
+ }
- // Note: Due to a bug in current() that affects some versions
- // of PHP we can not pass function call directly into it
- $res = $query->result_array();
- return current($res);
+ $query = $query->result_array();
+ return current($query);
}
// --------------------------------------------------------------------
@@ -212,7 +212,7 @@ abstract class CI_DB_utility extends CI_DB_forge {
$out = rtrim($out).$newline;
// Next blast through the result array and build out the rows
- foreach ($query->result_array() as $row)
+ while ($row = $query->unbuffered_row('array'))
{
foreach ($row as $item)
{
@@ -257,18 +257,18 @@ abstract class CI_DB_utility extends CI_DB_forge {
$CI->load->helper('xml');
// Generate the result
- $xml = "<{$root}>".$newline;
- foreach ($query->result_array() as $row)
+ $xml = '<'.$root.'>'.$newline;
+ while ($row = $query->unbuffered_row())
{
- $xml .= $tab."<{$element}>".$newline;
+ $xml .= $tab.'<'.$element.'>'.$newline;
foreach ($row as $key => $val)
{
- $xml .= $tab.$tab."<{$key}>".xml_convert($val)."</{$key}>".$newline;
+ $xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).'</'.$key.'>'.$newline;
}
- $xml .= $tab."</{$element}>".$newline;
+ $xml .= $tab.'</'.$element.'>'.$newline;
}
- return $xml .= "</$root>".$newline;
+ return $xml.'</'.$root.'>'.$newline;
}
// --------------------------------------------------------------------
@@ -328,8 +328,8 @@ abstract class CI_DB_utility extends CI_DB_forge {
// Is the encoder supported? If not, we'll either issue an
// error or use plain text depending on the debug settings
- if (($prefs['format'] === 'gzip' AND ! @function_exists('gzencode'))
- OR ($prefs['format'] === 'zip' AND ! @function_exists('gzcompress')))
+ if (($prefs['format'] === 'gzip' && ! @function_exists('gzencode'))
+ OR ($prefs['format'] === 'zip' && ! @function_exists('gzcompress')))
{
if ($this->db->db_debug)
{
@@ -343,7 +343,7 @@ abstract class CI_DB_utility extends CI_DB_forge {
if ($prefs['format'] === 'zip')
{
// Set the filename if not provided (only needed with Zip files)
- if ($prefs['filename'] == '')
+ if ($prefs['filename'] === '')
{
$prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database)
.date('Y-m-d_H-i', time()).'.sql';
@@ -369,7 +369,7 @@ abstract class CI_DB_utility extends CI_DB_forge {
$CI->zip->add_data($prefs['filename'], $this->_backup($prefs));
return $CI->zip->get_zip();
}
- elseif ($prefs['format'] == 'txt') // Was a text file requested?
+ elseif ($prefs['format'] === 'txt') // Was a text file requested?
{
return $this->_backup($prefs);
}
diff --git a/system/database/drivers/cubrid/cubrid_driver.php b/system/database/drivers/cubrid/cubrid_driver.php
index bed3d8685..6b67b7546 100644
--- a/system/database/drivers/cubrid/cubrid_driver.php
+++ b/system/database/drivers/cubrid/cubrid_driver.php
@@ -21,7 +21,7 @@
* @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 2.0.2
+ * @since Version 2.1
* @filesource
*/
@@ -29,7 +29,7 @@
* CUBRID Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -43,7 +43,7 @@ class CI_DB_cubrid_driver extends CI_DB {
public $dbdriver = 'cubrid';
// The character used for escaping - no need in CUBRID
- protected $_escape_char = '';
+ protected $_escape_char = '`';
// clause and character used for LIKE escape sequences - not used in CUBRID
protected $_like_escape_str = '';
@@ -74,7 +74,7 @@ class CI_DB_cubrid_driver extends CI_DB {
else
{
// If no port is defined by the user, use the default value
- $this->port == '' OR $this->port = 33000;
+ empty($this->port) OR $this->port = 33000;
}
}
@@ -159,22 +159,6 @@ class CI_DB_cubrid_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- // In CUBRID there is no need to select a database as the database
- // is chosen at the connection time.
- // So, to determine if the database is "selected", all we have to
- // do is ping the server and return that value.
- return cubrid_ping($this->conn_id);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Database version number
*
* @return string
@@ -208,13 +192,8 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -222,7 +201,7 @@ class CI_DB_cubrid_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
+ $this->_trans_failure = ($test_mode === TRUE);
if (cubrid_get_autocommit($this->conn_id))
{
@@ -241,13 +220,8 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -271,13 +245,8 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -313,7 +282,9 @@ class CI_DB_cubrid_driver extends CI_DB {
return $str;
}
- if (function_exists('cubrid_real_escape_string') AND is_resource($this->conn_id))
+ if (function_exists('cubrid_real_escape_string') &&
+ (is_resource($this->conn_id)
+ OR (get_resource_type($this->conn_id) === 'Unknown' && preg_match('/Resource id #/', strval($this->conn_id)))))
{
$str = cubrid_real_escape_string($str, $this->conn_id);
}
@@ -325,7 +296,7 @@ class CI_DB_cubrid_driver extends CI_DB {
// escape LIKE condition wildcards
if ($like === TRUE)
{
- $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);
+ return str_replace(array('%', '_'), array('\\%', '\\_'), $str);
}
return $str;
@@ -358,35 +329,6 @@ class CI_DB_cubrid_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified table
- *
- * @param string
- * @return int
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -396,11 +338,11 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
protected function _list_tables($prefix_limit = FALSE)
{
- $sql = "SHOW TABLES";
+ $sql = 'SHOW TABLES';
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
- $sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%'";
+ return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
}
return $sql;
@@ -433,7 +375,7 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
protected function _field_data($table)
{
- return "SELECT * FROM ".$table." LIMIT 1";
+ return 'SELECT * FROM '.$table.' LIMIT 1';
}
// --------------------------------------------------------------------
@@ -451,157 +393,9 @@ class CI_DB_cubrid_driver extends CI_DB {
return array('code' => cubrid_errno($this->conn_id), 'message' => cubrid_error($this->conn_id));
}
- /**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
// --------------------------------------------------------------------
/**
- * From Tables
- *
- * This function implicitly groups FROM tables so there is no confusion
- * about operator precedence in harmony with SQL standards
- *
- * @param array
- * @return string
- */
- protected function _from_tables($tables)
- {
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")";
- }
-
- // --------------------------------------------------------------------
-
-
- /**
- * Replace statement
- *
- * Generates a platform-specific replace string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _replace($table, $keys, $values)
- {
- return "REPLACE INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")";
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert_batch statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert_batch($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES ".implode(', ', $values);
- }
-
- // --------------------------------------------------------------------
-
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = sprintf('"%s" = %s', $key, $val);
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
-
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
-
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
-
- $sql .= $orderby.$limit;
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
-
- /**
* Update_Batch statement
*
* Generates a platform-specific batch update string from the supplied data
@@ -614,90 +408,30 @@ class CI_DB_cubrid_driver extends CI_DB {
protected function _update_batch($table, $values, $index, $where = NULL)
{
$ids = array();
- $where = ($where != '' AND count($where) >=1) ? implode(" ", $where).' AND ' : '';
-
foreach ($values as $key => $val)
{
$ids[] = $val[$index];
foreach (array_keys($val) as $field)
{
- if ($field != $index)
+ if ($field !== $index)
{
$final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
}
}
}
- $sql = "UPDATE ".$table." SET ";
$cases = '';
-
foreach ($final as $k => $v)
{
- $cases .= $k.' = CASE '."\n";
- foreach ($v as $row)
- {
- $cases .= $row."\n";
- }
-
- $cases .= 'ELSE '.$k.' END, ';
- }
-
- $sql .= substr($cases, 0, -2);
-
- $sql .= ' WHERE '.$where.$index.' IN ('.implode(',', $ids).')';
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Truncate statement
- *
- * Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
- *
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return "TRUNCATE ".$table;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
- *
- * Generates a platform-specific delete string from the supplied data
- *
- * @param string the table name
- * @param array the where clause
- * @param string the limit clause
- * @return string
- */
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
- {
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
+ $cases .= $k." = CASE \n"
+ .implode("\n", $v)
+ .'ELSE '.$k.' END, ';
}
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- return "DELETE FROM ".$table.$conditions.$limit;
+ return 'UPDATE '.$table.' SET '.substr($cases, 0, -2)
+ .' WHERE '.(($where !== '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
+ .$index.' IN ('.implode(',', $ids).')';
}
// --------------------------------------------------------------------
@@ -714,16 +448,7 @@ class CI_DB_cubrid_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- if ($offset == 0)
- {
- $offset = '';
- }
- else
- {
- $offset .= ", ";
- }
-
- return $sql."LIMIT ".$offset.$limit;
+ return $sql.'LIMIT '.($offset == 0 ? '' : $offset.', ').$limit;
}
// --------------------------------------------------------------------
@@ -731,12 +456,11 @@ class CI_DB_cubrid_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @cubrid_close($conn_id);
+ @cubrid_close($this->conn_id);
}
}
diff --git a/system/database/drivers/cubrid/cubrid_forge.php b/system/database/drivers/cubrid/cubrid_forge.php
index bbda484c4..d328aa241 100644
--- a/system/database/drivers/cubrid/cubrid_forge.php
+++ b/system/database/drivers/cubrid/cubrid_forge.php
@@ -21,7 +21,7 @@
* @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 1.0
+ * @since Version 2.1
* @filesource
*/
@@ -34,35 +34,8 @@
*/
class CI_DB_cubrid_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return bool
- */
- public function _create_database($name)
- {
- // CUBRID does not allow to create a database in SQL. The GUI tools
- // have to be used for this purpose.
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- // CUBRID does not allow to drop a database in SQL. The GUI tools
- // have to be used for this purpose.
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_create_database = FALSE;
+ protected $_drop_database = FALSE;
/**
* Process Fields
@@ -82,35 +55,33 @@ class CI_DB_cubrid_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t\"".$this->db->protect_identifiers($field).'"';
+ $sql .= "\n\t".$this->db->escape_identifiers($field);
- if (array_key_exists('NAME', $attributes))
- {
- $sql .= ' '.$this->db->protect_identifiers($attributes['NAME']).' ';
- }
+ empty($attributes['NAME']) OR $sql .= ' '.$this->db->escape_identifiers($attributes['NAME']).' ';
- if (array_key_exists('TYPE', $attributes))
+ if ( ! empty($attributes['TYPE']))
{
$sql .= ' '.$attributes['TYPE'];
- if (array_key_exists('CONSTRAINT', $attributes))
+ if ( ! empty($attributes['CONSTRAINT']))
{
- switch ($attributes['TYPE'])
+ switch (strtolower($attributes['TYPE']))
{
case 'decimal':
case 'float':
case 'numeric':
$sql .= '('.implode(',', $attributes['CONSTRAINT']).')';
break;
- case 'enum': // As of version 8.4.0 CUBRID does not support
- // enum data type.
- break;
+ case 'enum':
+ // Will be supported in the future as part a part of
+ // MySQL compatibility features.
+ break;
case 'set':
$sql .= '("'.implode('","', $attributes['CONSTRAINT']).'")';
break;
@@ -120,33 +91,29 @@ class CI_DB_cubrid_forge extends CI_DB_forge {
}
}
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ /* As of version 8.4.1 CUBRID does not support UNSIGNED INTEGER data type.
+ * Will be supported in the next release as a part of MySQL Compatibility.
+ *
+ if (isset($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
- //$sql .= ' UNSIGNED';
- // As of version 8.4.0 CUBRID does not support UNSIGNED INTEGER data type.
- // Will be supported in the next release as a part of MySQL Compatibility.
+ $sql .= ' UNSIGNED';
}
+ */
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
- if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE)
+ if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE)
{
$sql .= ' UNIQUE';
}
@@ -174,27 +141,24 @@ class CI_DB_cubrid_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
+ /* As of version 8.4.1 CUBRID does not support this SQL syntax.
if ($if_not_exists === TRUE)
{
- //$sql .= 'IF NOT EXISTS ';
- // As of version 8.4.0 CUBRID does not support this SQL syntax.
+ $sql .= 'IF NOT EXISTS ';
}
+ */
- $sql .= $this->db->_escape_identifiers($table)." (";
-
- $sql .= $this->_process_fields($fields);
+ $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields);
// If there is a PK defined
if (count($primary_keys) > 0)
{
- $key_name = 'pk_'.$table.'_'.$this->db->protect_identifiers(implode('_', $primary_keys));
-
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tCONSTRAINT " . $key_name . " PRIMARY KEY(" . implode(', ', $primary_keys) . ")";
+ $key_name = $this->db->escape_identifiers('pk_'.$table.'_'.implode('_', $primary_keys));
+ $sql .= ",\n\tCONSTRAINT ".$key_name.' PRIMARY KEY('.implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
@@ -203,34 +167,20 @@ class CI_DB_cubrid_forge extends CI_DB_forge {
{
if (is_array($key))
{
- $key_name = $this->db->protect_identifiers(implode('_', $key));
- $key = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers('idx_'.$table.implode('_', $key));
+ $key = $this->db->escape_identifiers($key);
}
else
{
- $key_name = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers('idx_'.$table.$key);
$key = array($key_name);
}
- $sql .= ",\n\tKEY \"{$key_name}\" (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tKEY ".$key_name.' ('.implode(', ', $key).')';
}
}
- $sql .= "\n);";
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return string
- */
- public function _drop_table($table)
- {
- return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table);
+ return $sql."\n);";
}
// --------------------------------------------------------------------
@@ -247,40 +197,18 @@ class CI_DB_cubrid_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $fields, $after_field = '')
+ protected function _alter_table($alter_type, $table, $fields, $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' ';
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' ';
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
- {
- return $sql.$this->db->protect_identifiers($fields);
- }
-
- $sql .= $this->_process_fields($fields);
-
- if ($after_field != '')
+ if ($alter_type === 'DROP')
{
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
+ return $sql.$this->db->escape_identifiers($fields);
}
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'RENAME TABLE '.$this->db->protect_identifiers($table_name).' AS '.$this->db->protect_identifiers($new_table_name);
+ return $sql.$this->_process_fields($fields)
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/cubrid/cubrid_result.php b/system/database/drivers/cubrid/cubrid_result.php
index 6a61a213d..3eb9f7e3d 100644
--- a/system/database/drivers/cubrid/cubrid_result.php
+++ b/system/database/drivers/cubrid/cubrid_result.php
@@ -21,7 +21,7 @@
* @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 2.0.2
+ * @since Version 2.1
* @filesource
*/
@@ -84,53 +84,20 @@ class CI_DB_cubrid_result extends CI_DB_result {
public function field_data()
{
$retval = array();
-
- $tablePrimaryKeys = array();
+ $i = 0;
while ($field = cubrid_fetch_field($this->result_id))
{
- $F = new stdClass();
- $F->name = $field->name;
- $F->type = $field->type;
- $F->default = $field->def;
- $F->max_length = $field->max_length;
-
- // At this moment primary_key property is not returned when
- // cubrid_fetch_field is called. The following code will
- // provide a patch for it. primary_key property will be added
- // in the next release.
-
- // TODO: later version of CUBRID will provide primary_key
- // property.
- // When PK is defined in CUBRID, an index is automatically
- // created in the db_index system table in the form of
- // pk_tblname_fieldname. So the following will count how many
- // columns are there which satisfy this format.
- // The query will search for exact single columns, thus
- // compound PK is not supported.
- $res = cubrid_query($this->conn_id,
- "SELECT COUNT(*) FROM db_index WHERE class_name = '" . $field->table .
- "' AND is_primary_key = 'YES' AND index_name = 'pk_" .
- $field->table . "_" . $field->name . "'"
- );
-
- if ($res)
- {
- $row = cubrid_fetch_array($res, CUBRID_NUM);
- $F->primary_key = ($row[0] > 0 ? 1 : null);
- }
- else
- {
- $F->primary_key = null;
- }
-
- if (is_resource($res))
- {
- cubrid_close_request($res);
- $this->result_id = FALSE;
- }
-
- $retval[] = $F;
+ $retval[$i] = new stdClass();
+ $retval[$i]->name = $field->name;
+ // CUBRID returns type as e.g. varchar(100),
+ // so we need to remove all digits and brackets.
+ $retval[$i]->type = preg_replace('/[\d()]/', '', $field->type);
+ $retval[$i]->default = $field->def;
+ // Use CUBRID's native API to obtain column's max_length,
+ // otherwise $field->max_length has incorrect info
+ $retval[$i]->max_length = cubrid_field_len($this->result_id, $i);
+ $retval[$i++]->primary_key = $field->primary_key;
}
return $retval;
@@ -145,9 +112,8 @@ class CI_DB_cubrid_result extends CI_DB_result {
*/
public function free_result()
{
- if(is_resource($this->result_id) ||
- get_resource_type($this->result_id) == "Unknown" &&
- preg_match('/Resource id #/', strval($this->result_id)))
+ if (is_resource($this->result_id) OR
+ (get_resource_type($this->result_id) === 'Unknown' && preg_match('/Resource id #/', strval($this->result_id))))
{
cubrid_close_request($this->result_id);
$this->result_id = FALSE;
@@ -163,7 +129,7 @@ class CI_DB_cubrid_result extends CI_DB_result {
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
diff --git a/system/database/drivers/cubrid/cubrid_utility.php b/system/database/drivers/cubrid/cubrid_utility.php
index dafd66146..c8cee99b6 100644
--- a/system/database/drivers/cubrid/cubrid_utility.php
+++ b/system/database/drivers/cubrid/cubrid_utility.php
@@ -21,7 +21,7 @@
* @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 1.0
+ * @since Version 2.1
* @filesource
*/
@@ -39,69 +39,25 @@ class CI_DB_cubrid_utility extends CI_DB_utility {
*
* @return array
*/
- public function _list_databases()
+ public function list_databases()
{
- // CUBRID does not allow to see the list of all databases on the
- // server. It is the way its architecture is designed. Every
- // database is independent and isolated.
- // For this reason we can return only the name of the currect
- // connected database.
- if ($this->conn_id)
+ if (isset($this->data_cache['db_names']))
{
- return "SELECT '" . $this->database . "'";
+ return $this->data_cache['db_names'];
}
- else
- {
- return FALSE;
- }
- }
-
- // --------------------------------------------------------------------
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- * @link http://www.cubrid.org/manual/840/en/Optimize%20Database
- */
- public function _optimize_table($table)
- {
- // No SQL based support in CUBRID as of version 8.4.0. Database or
- // table optimization can be performed using CUBRID Manager
- // database administration tool. See the link above for more info.
- return FALSE;
+ return $this->data_cache['db_names'] = cubrid_list_dbs($this->db->conn_id);
}
// --------------------------------------------------------------------
/**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- * @link http://www.cubrid.org/manual/840/en/Checking%20Database%20Consistency
- */
- public function _repair_table($table)
- {
- // Not supported in CUBRID as of version 8.4.0. Database or
- // table consistency can be checked using CUBRID Manager
- // database administration tool. See the link above for more info.
- return FALSE;
- }
-
- // --------------------------------------------------------------------
- /**
* CUBRID Export
*
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// No SQL based support in CUBRID as of version 8.4.0. Database or
// table backup can be performed using CUBRID Manager
diff --git a/system/database/drivers/interbase/interbase_driver.php b/system/database/drivers/interbase/interbase_driver.php
index d8b6ae571..5a03607ee 100644
--- a/system/database/drivers/interbase/interbase_driver.php
+++ b/system/database/drivers/interbase/interbase_driver.php
@@ -29,7 +29,7 @@
* Firebird/Interbase Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -85,19 +85,6 @@ class CI_DB_interbase_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return bool
- */
- public function db_select()
- {
- // Connection selects the database
- return TRUE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Database version number
*
* @return string
@@ -257,35 +244,6 @@ class CI_DB_interbase_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $query = $query->row();
- $this->_reset_select();
- return (int) $query->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -297,7 +255,7 @@ class CI_DB_interbase_driver extends CI_DB {
{
$sql = 'SELECT "RDB$RELATION_NAME" FROM "RDB$RELATIONS" WHERE "RDB$RELATION_NAME" NOT LIKE \'RDB$%\' AND "RDB$RELATION_NAME" NOT LIKE \'MON$%\'';
- if ($prefix_limit !== FALSE && $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
return $sql.' AND "RDB$RELATION_NAME" LIKE \''.$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
@@ -356,38 +314,6 @@ class CI_DB_interbase_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This public function escapes column and table names
- *
- * @param string
- * @return string
- */
- protected function _escape_identifiers($item)
- {
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item);
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char);
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This public function implicitly groups FROM tables so there is no confusion
@@ -398,30 +324,7 @@ class CI_DB_interbase_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- //Interbase/Firebird doesn't like grouped tables
- return implode(', ', $tables);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
// --------------------------------------------------------------------
@@ -435,20 +338,26 @@ class CI_DB_interbase_driver extends CI_DB {
* @param array the update data
* @param array the where clause
* @param array the orderby clause
- * @param array the limit clause
+ * @param array the limit clause (ignored)
+ * @param array the like clause
* @return string
*/
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
+ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
{
foreach ($values as $key => $val)
{
$valstr[] = $key.' = '.$val;
}
- //$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
+ $where = empty($where) ? '' : ' WHERE '.implode(' ', $where);
+
+ if ( ! empty($like))
+ {
+ $where .= ($where === '' ? ' WHERE ' : ' AND ').implode(' ', $like);
+ }
return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
- .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '')
+ .$where
.(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '');
}
@@ -459,15 +368,16 @@ class CI_DB_interbase_driver extends CI_DB {
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This public function maps to "DELETE FROM table"
+ *
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
* @return string
*/
protected function _truncate($table)
{
- return $this->_delete($table);
+ return 'DELETE FROM '.$table;
}
// --------------------------------------------------------------------
@@ -479,25 +389,18 @@ class CI_DB_interbase_driver extends CI_DB {
*
* @param string the table name
* @param array the where clause
- * @param string the limit clause
+ * @param array the like clause
+ * @param string the limit clause (ignored)
* @return string
*/
protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ".implode("\n", $where)
- .((count($where) > 0 && count($like) > 0) ? ' AND ' : '')
- .implode("\n", $like);
- }
- else
- {
- $conditions = '';
- }
+ $conditions = array();
- //$limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
- return 'DELETE FROM '.$table.' '.$conditions;
+ return 'DELETE FROM '.$table.(count($conditions) > 0 ? ' WHERE '.implode(' AND ', $conditions) : '');
}
// --------------------------------------------------------------------
@@ -534,12 +437,11 @@ class CI_DB_interbase_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @ibase_close($conn_id);
+ @ibase_close($this->conn_id);
}
}
diff --git a/system/database/drivers/interbase/interbase_forge.php b/system/database/drivers/interbase/interbase_forge.php
index f46043569..3f9967f1f 100644
--- a/system/database/drivers/interbase/interbase_forge.php
+++ b/system/database/drivers/interbase/interbase_forge.php
@@ -25,8 +25,6 @@
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Interbase/Firebird Forge Class
*
@@ -36,18 +34,22 @@
*/
class CI_DB_interbase_forge extends CI_DB_forge {
+ protected $_drop_table = 'DROP TABLE %s';
+
/**
* Create database
*
* @param string the database name
* @return string
*/
- protected function _create_database($filename='')
+ public function create_database($db_name)
{
- // Firebird databases are flat files, so a path is required
+ // Firebird databases are flat files, so a path is required
+
// Hostname is needed for remote access
- return 'CREATE DATABASE "'.$this->hostname.':'.$filename.'"';
-
+ empty($this->db->hostname) OR $db_name = $this->hostname.':'.$db_name;
+
+ return parent::create_database('"'.$db_name.'"');
}
// --------------------------------------------------------------------
@@ -55,14 +57,20 @@ class CI_DB_interbase_forge extends CI_DB_forge {
/**
* Drop database
*
- * @param string the database name - not used in this driver
- * - the current db is dropped
+ * @param string the database name
+ * - not used in this driver, the current db is dropped
* @return bool
*/
- protected function _drop_database($name='')
+ public function drop_database($db_name = '')
{
- return ibase_drop_db($this->conn_id);
+ if ( ! ibase_drop_db($this->conn_id))
+ {
+ return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
+ }
+
+ return TRUE;
}
+
// --------------------------------------------------------------------
/**
@@ -72,14 +80,14 @@ class CI_DB_interbase_forge extends CI_DB_forge {
* @param array the fields
* @param mixed primary key(s)
* @param mixed key(s)
- * @param boolean should 'IF NOT EXISTS' be added to the SQL
+ * @param bool should 'IF NOT EXISTS' be added to the SQL
* @return string
*/
protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
- $sql .= $this->db->protect_identifiers($table)."(";
+ $sql .= $this->db->escape_identifiers($table).'(';
$current_field_count = 0;
foreach ($fields as $field => $attributes)
@@ -89,41 +97,30 @@ class CI_DB_interbase_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field);
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- $sql .= ' '.$attributes['TYPE'];
+ empty($attributes['CONSTRAINT']) OR $sql .= '('.$attributes['CONSTRAINT'].')';
- if (array_key_exists('CONSTRAINT', $attributes))
- {
- $sql .= '('.$attributes['CONSTRAINT'].')';
- }
-
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -138,42 +135,23 @@ class CI_DB_interbase_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $primary_keys = $this->db->escape_identifiers($primary_keys);
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $primary_keys).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tUNIQUE (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tUNIQUE (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return string
- */
- protected function _drop_table($table)
- {
- return 'DROP TABLE '.$name;
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -189,54 +167,19 @@ class CI_DB_interbase_forge extends CI_DB_forge {
* @param string the table name
* @param string the column definition
* @param string the default value
- * @param boolean should 'NOT NULL' be added
+ * @param bool should 'NOT NULL' be added
* @param string the field after which we should add the new field
* @return string
*/
protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table)." $alter_type ".$this->db->protect_identifiers($column_name);
-
- $sql .= " {$column_definition}";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"{$default_value}\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- $sql .= ' AFTER ' . $this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
+ return 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name)
+ .' '.$column_definition
+ .($default_value !== '' ? ' DEFAULT "'.$default_value.'"' : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- protected function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
- }
}
/* End of file interbase_forge.php */
diff --git a/system/database/drivers/interbase/interbase_result.php b/system/database/drivers/interbase/interbase_result.php
index fd4178dec..5ddb6fa47 100644
--- a/system/database/drivers/interbase/interbase_result.php
+++ b/system/database/drivers/interbase/interbase_result.php
@@ -131,23 +131,6 @@ class CI_DB_interbase_result extends CI_DB_result {
// --------------------------------------------------------------------
/**
- * Data Seek
- *
- * Moves the internal pointer to the desired offset. We call
- * this internally before fetching results to make sure the
- * result set starts at zero
- *
- * @return array
- */
- protected function _data_seek($n = 0)
- {
- // Interbase driver doesn't implement a suitable function
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Result - associative array
*
* Returns the result set as an array
diff --git a/system/database/drivers/interbase/interbase_utility.php b/system/database/drivers/interbase/interbase_utility.php
index a88055ee0..164211836 100644
--- a/system/database/drivers/interbase/interbase_utility.php
+++ b/system/database/drivers/interbase/interbase_utility.php
@@ -25,8 +25,6 @@
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Interbase/Firebird Utility Class
*
@@ -36,56 +34,7 @@
*/
class CI_DB_interbase_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * I don't believe you can do a database listing with Firebird
- * since each database is its own file. I suppose we could
- * try reading a directory looking for Firebird files, but
- * that doesn't seem like a terribly good idea
- *
- * @return bool
- */
- public function _list_databases()
- {
- if ($this->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Is optimization even supported in Interbase/Firebird?
- *
- * @param string the table name
- * @return object
- */
- public function _optimize_table($table)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Table repairs are not supported in Interbase/Firebird
- *
- * @param string the table name
- * @return object
- */
- public function _repair_table($table)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = FALSE;
/**
* Interbase/Firebird Export
@@ -93,22 +42,20 @@ class CI_DB_interbase_utility extends CI_DB_utility {
* @param string $filename
* @return mixed
*/
- public function backup($filename)
+ protected function _backup($filename)
{
if ($service = ibase_service_attach($this->db->hostname, $this->db->username, $this->db->password))
{
$res = ibase_backup($service, $this->db->database, $filename.'.fbk');
-
- //Close the service connection
+
+ // Close the service connection
ibase_service_detach($service);
-
return $res;
}
- else
- {
- return FALSE;
- }
+
+ return FALSE;
}
+
}
/* End of file interbase_utility.php */
diff --git a/system/database/drivers/mssql/mssql_driver.php b/system/database/drivers/mssql/mssql_driver.php
index 912808631..87094e76e 100644
--- a/system/database/drivers/mssql/mssql_driver.php
+++ b/system/database/drivers/mssql/mssql_driver.php
@@ -29,7 +29,7 @@
* MS SQL Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -43,7 +43,7 @@ class CI_DB_mssql_driver extends CI_DB {
public $dbdriver = 'mssql';
// The character used for escaping
- protected $_escape_char = '';
+ protected $_escape_char = '"';
// clause and character used for LIKE escape sequences
protected $_like_escape_str = " ESCAPE '%s' ";
@@ -52,10 +52,33 @@ class CI_DB_mssql_driver extends CI_DB {
/**
* The syntax to count rows is slightly different across different
* database engines, so this string appears in each driver and is
- * used for the count_all() and count_all_results() functions.
+ * used for the count_all() and count_all_results() methods.
*/
protected $_count_string = 'SELECT COUNT(*) AS ';
- protected $_random_keyword = ' ASC'; // not currently supported
+ protected $_random_keyword = ' NEWID()';
+
+ // MSSQL-specific properties
+ protected $_quoted_identifier = TRUE;
+
+ /*
+ * Constructor
+ *
+ * Appends the port number to the hostname, if needed.
+ *
+ * @param array
+ * @return void
+ */
+ public function __construct($params)
+ {
+ parent::__construct($params);
+
+ if ( ! empty($this->port))
+ {
+ $this->hostname .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port;
+ }
+ }
+
+ // --------------------------------------------------------------------
/**
* Non-persistent database connection
@@ -64,12 +87,7 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function db_connect()
{
- if ($this->port != '')
- {
- $this->hostname .= ','.$this->port;
- }
-
- return @mssql_connect($this->hostname, $this->username, $this->password);
+ return $this->_mssql_connect();
}
// --------------------------------------------------------------------
@@ -81,12 +99,35 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function db_pconnect()
{
- if ($this->port != '')
+ return $this->_mssql_connect(TRUE);
+ }
+
+ // --------------------------------------------------------------------
+
+ /*
+ * MSSQL Connect
+ *
+ * @param bool
+ * @return resource
+ */
+ protected function _mssql_connect($persistent = FALSE)
+ {
+ $conn_id = ($persistent)
+ ? @mssql_pconnect($this->hostname, $this->username, $this->password)
+ : @mssql_connect($this->hostname, $this->username, $this->password);
+
+ if ( ! $conn_id)
{
- $this->hostname .= ','.$this->port;
+ return FALSE;
}
- return @mssql_pconnect($this->hostname, $this->username, $this->password);
+ // Determine how identifiers are escaped
+ $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
+ $query = $query->row_array();
+ $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query->qi;
+ $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
+
+ return $conn_id;
}
// --------------------------------------------------------------------
@@ -106,7 +147,7 @@ class CI_DB_mssql_driver extends CI_DB {
// Note: The brackets are required in the event that the DB name
// contains reserved characters
- if (@mssql_select_db('['.$database.']', $this->conn_id))
+ if (@mssql_select_db($this->escape_identifiers($database), $this->conn_id))
{
$this->database = $database;
return TRUE;
@@ -121,7 +162,7 @@ class CI_DB_mssql_driver extends CI_DB {
* Execute the query
*
* @param string an SQL query
- * @return resource
+ * @return mixed resource if rows are returned, bool otherwise
*/
protected function _execute($sql)
{
@@ -137,13 +178,8 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -151,10 +187,9 @@ class CI_DB_mssql_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
+ $this->_trans_failure = ($test_mode === TRUE);
- $this->simple_query('BEGIN TRAN');
- return TRUE;
+ return $this->simple_query('BEGIN TRAN');
}
// --------------------------------------------------------------------
@@ -166,19 +201,13 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
- $this->simple_query('COMMIT TRAN');
- return TRUE;
+ return $this->simple_query('COMMIT TRAN');
}
// --------------------------------------------------------------------
@@ -190,19 +219,13 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
- $this->simple_query('ROLLBACK TRAN');
- return TRUE;
+ return $this->simple_query('ROLLBACK TRAN');
}
// --------------------------------------------------------------------
@@ -232,7 +255,7 @@ class CI_DB_mssql_driver extends CI_DB {
// escape LIKE condition wildcards
if ($like === TRUE)
{
- $str = str_replace(
+ return str_replace(
array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str
@@ -265,11 +288,13 @@ class CI_DB_mssql_driver extends CI_DB {
*/
public function insert_id()
{
- $ver = self::_parse_major_version($this->version());
- $sql = ($ver >= 8 ? "SELECT SCOPE_IDENTITY() AS last_id" : "SELECT @@IDENTITY AS last_id");
- $query = $this->query($sql);
- $row = $query->row();
- return $row->last_id;
+ $query = (self::_parse_major_version($this->version()) > 7)
+ ? 'SELECT SCOPE_IDENTITY() AS last_id'
+ : 'SELECT @@IDENTITY AS last_id';
+
+ $query = $this->query($query);
+ $query = $query->row();
+ return $query->last_id;
}
// --------------------------------------------------------------------
@@ -304,35 +329,6 @@ class CI_DB_mssql_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -345,7 +341,7 @@ class CI_DB_mssql_driver extends CI_DB {
$sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
// for future compatibility
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE AND $this->dbprefix !== '')
{
//$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
return FALSE; // not currently supported
@@ -381,7 +377,7 @@ class CI_DB_mssql_driver extends CI_DB {
*/
protected function _field_data($table)
{
- return "SELECT TOP 1 * FROM ".$table;
+ return 'SELECT TOP 1 * FROM '.$table;
}
// --------------------------------------------------------------------
@@ -404,47 +400,6 @@ class CI_DB_mssql_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
@@ -455,29 +410,7 @@ class CI_DB_mssql_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return implode(', ', $tables);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
// --------------------------------------------------------------------
@@ -490,46 +423,44 @@ class CI_DB_mssql_driver extends CI_DB {
* @param string the table name
* @param array the update data
* @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
+ * @param array the orderby clause (ignored)
+ * @param array the limit clause (ignored)
+ * @param array the like clause
* @return string
*/
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
+ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
{
- foreach ($values as $key => $val)
+ foreach($values as $key => $val)
{
- $valstr[] = $key." = ".$val;
+ $valstr[] = $key.' = '.$val;
}
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
+ $where = empty($where) ? '' : ' WHERE '.implode(' ', $where);
- $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
-
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
-
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
-
- $sql .= $orderby.$limit;
+ if ( ! empty($like))
+ {
+ $where .= ($where === '' ? ' WHERE ' : ' AND ').implode(' ', $like);
+ }
- return $sql;
+ return 'UPDATE '.$table.' SET '.implode(', ', $valstr).' WHERE '.$where;
}
-
// --------------------------------------------------------------------
/**
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
+ *
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
* @return string
*/
protected function _truncate($table)
{
- return "TRUNCATE ".$table;
+ return 'TRUNCATE TABLE '.$table;
}
// --------------------------------------------------------------------
@@ -541,28 +472,22 @@ class CI_DB_mssql_driver extends CI_DB {
*
* @param string the table name
* @param array the where clause
+ * @param array the like clause
* @param string the limit clause
* @return string
*/
protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
- $conditions = '';
+ $conditions = array();
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
+ $conditions = (count($conditions) > 0) ? ' WHERE '.implode(' AND ', $conditions) : '';
- return "DELETE FROM ".$table.$conditions.$limit;
+ return ($limit)
+ ? 'WITH ci_delete AS (SELECT TOP '.$limit.' * FROM '.$table.$conditions.') DELETE FROM ci_delete'
+ : 'DELETE FROM '.$table.$conditions;
}
// --------------------------------------------------------------------
@@ -579,9 +504,7 @@ class CI_DB_mssql_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- $i = $limit + $offset;
-
- return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$i.' ', $sql);
+ return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.($limit + $offset).' ', $sql);
}
// --------------------------------------------------------------------
@@ -589,12 +512,11 @@ class CI_DB_mssql_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @mssql_close($conn_id);
+ @mssql_close($this->conn_id);
}
}
diff --git a/system/database/drivers/mssql/mssql_forge.php b/system/database/drivers/mssql/mssql_forge.php
index 2e3e314ed..3a3528f7b 100644
--- a/system/database/drivers/mssql/mssql_forge.php
+++ b/system/database/drivers/mssql/mssql_forge.php
@@ -34,44 +34,7 @@
*/
class CI_DB_mssql_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return string
- */
- public function _create_database($name)
- {
- return "CREATE DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return string
- */
- public function _drop_database($name)
- {
- return "DROP DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @param string table name
- * @return string
- */
- public function _drop_table($table)
- {
- return "DROP TABLE ".$this->db->_escape_identifiers($table);
- }
-
- // --------------------------------------------------------------------
+ protected $_drop_table = 'DROP TABLE %s';
/**
* Create Table
@@ -83,18 +46,15 @@ class CI_DB_mssql_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return string
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
- $sql = 'CREATE TABLE ';
+ $sql = ($if_not_exists === TRUE)
+ ? "IF NOT EXISTS (SELECT * FROM sysobjects WHERE ID = object_id(N'".$table."') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)\n"
+ : '';
- if ($if_not_exists === TRUE)
- {
- $sql .= 'IF NOT EXISTS ';
- }
+ $sql .= 'CREATE TABLE '.$this->db->escape_identifiers($table).' (';
- $sql .= $this->db->_escape_identifiers($table)." (";
$current_field_count = 0;
-
foreach ($fields as $field => $attributes)
{
// Numeric field names aren't allowed in databases, so if the key is
@@ -102,41 +62,33 @@ class CI_DB_mssql_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field);
-
- $sql .= ' '.$attributes['TYPE'];
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- if (array_key_exists('CONSTRAINT', $attributes))
+ if (stripos($attributes['TYPE'], 'INT') === FALSE && ! empty($attributes['CONSTRAINT']))
{
$sql .= '('.$attributes['CONSTRAINT'].')';
}
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -151,30 +103,22 @@ class CI_DB_mssql_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tFOREIGN KEY (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -194,56 +138,20 @@ class CI_DB_mssql_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name);
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name);
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ if ($alter_type === 'DROP')
{
return $sql;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- // I think this syntax will work, but can find little documentation on renaming tables in MSSQL
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ return $sql.' '.$column_definition
+ .($default_value != '' ? ' DEFAULT "'.$default_value.'"' : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field != '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/mssql/mssql_result.php b/system/database/drivers/mssql/mssql_result.php
index 2723f4614..5929306af 100644
--- a/system/database/drivers/mssql/mssql_result.php
+++ b/system/database/drivers/mssql/mssql_result.php
@@ -92,12 +92,12 @@ class CI_DB_mssql_result extends CI_DB_result {
$retval = array();
while ($field = mssql_fetch_field($this->result_id))
{
- $F = new stdClass();
- $F->name = $field->name;
- $F->type = $field->type;
+ $F = new stdClass();
+ $F->name = $field->name;
+ $F->type = $field->type;
$F->max_length = $field->max_length;
$F->primary_key = 0;
- $F->default = '';
+ $F->default = '';
$retval[] = $F;
}
@@ -126,11 +126,11 @@ class CI_DB_mssql_result extends CI_DB_result {
/**
* Data Seek
*
- * Moves the internal pointer to the desired offset. We call
+ * Moves the internal pointer to the desired offset. We call
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
diff --git a/system/database/drivers/mssql/mssql_utility.php b/system/database/drivers/mssql/mssql_utility.php
index 5c144330d..69fcec5f6 100644
--- a/system/database/drivers/mssql/mssql_utility.php
+++ b/system/database/drivers/mssql/mssql_utility.php
@@ -34,55 +34,16 @@
*/
class CI_DB_mssql_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return string
- */
- public function _list_databases()
- {
- return "EXEC sp_helpdb"; // Can also be: EXEC sp_databases
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- return FALSE; // Is this supported in MS SQL?
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- return FALSE; // Is this supported in MS SQL?
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = 'EXEC sp_helpdb'; // Can also be: EXEC sp_databases
+ protected $_optimize_table = 'ALTER INDEX all ON %s REORGANIZE';
/**
* MSSQL Export
*
* @param array Preferences
- * @return mixed
+ * @return bool
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/mysql/mysql_driver.php b/system/database/drivers/mysql/mysql_driver.php
index bef4111c3..8938d22b5 100644
--- a/system/database/drivers/mysql/mysql_driver.php
+++ b/system/database/drivers/mysql/mysql_driver.php
@@ -29,7 +29,7 @@
* MySQL Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -47,7 +47,7 @@ class CI_DB_mysql_driver extends CI_DB {
// clause and character used for LIKE escape sequences - not used in MySQL
protected $_like_escape_str = '';
- protected $_like_escape_chr = '';
+ protected $_like_escape_chr = '\\';
/**
* The syntax to count rows is slightly different across different
@@ -68,7 +68,7 @@ class CI_DB_mysql_driver extends CI_DB {
{
parent::__construct($params);
- if ($this->port != '')
+ if ( ! empty($this->port))
{
$this->hostname .= ':'.$this->port;
}
@@ -291,7 +291,9 @@ class CI_DB_mysql_driver extends CI_DB {
// escape LIKE condition wildcards
if ($like === TRUE)
{
- return str_replace(array('%', '_'), array('\\%', '\\_'), $str);
+ return str_replace(array($this->_like_escape_chr, '%', '_'),
+ array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
+ $str);
}
return $str;
@@ -324,35 +326,6 @@ class CI_DB_mysql_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $query = $query->row();
- $this->_reset_select();
- return (int) $query->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -364,7 +337,7 @@ class CI_DB_mysql_driver extends CI_DB {
{
$sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char;
- if ($prefix_limit !== FALSE && $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
}
@@ -397,7 +370,7 @@ class CI_DB_mysql_driver extends CI_DB {
*/
public function field_data($table = '')
{
- if ($table == '')
+ if ($table === '')
{
return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
}
@@ -439,150 +412,6 @@ class CI_DB_mysql_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item);
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * From Tables
- *
- * This function implicitly groups FROM tables so there is no confusion
- * about operator precedence in harmony with SQL standards
- *
- * @param string table name
- * @return string
- */
- protected function _from_tables($tables)
- {
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
- }
-
- // --------------------------------------------------------------------
-
-
- /**
- * Replace statement
- *
- * Generates a platform-specific replace string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _replace($table, $keys, $values)
- {
- return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert_batch statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert_batch($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
- }
-
- // --------------------------------------------------------------------
-
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key.' = '.$val;
- }
-
- $where = ($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '';
- if (count($like) > 0)
- {
- $where .= ($where == '' ? ' WHERE ' : ' AND ').implode(' ', $like);
- }
-
- return 'UPDATE '.$table.' SET '.implode(', ', $valstr).$where
- .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '')
- .( ! $limit ? '' : ' LIMIT '.$limit);
- }
-
- // --------------------------------------------------------------------
-
-
- /**
* Update_Batch statement
*
* Generates a platform-specific batch update string from the supplied data
@@ -601,7 +430,7 @@ class CI_DB_mysql_driver extends CI_DB {
foreach (array_keys($val) as $field)
{
- if ($field != $index)
+ if ($field !== $index)
{
$final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
}
@@ -617,60 +446,13 @@ class CI_DB_mysql_driver extends CI_DB {
}
return 'UPDATE '.$table.' SET '.substr($cases, 0, -2)
- .' WHERE '.(($where != '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
+ .' WHERE '.(($where !== '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
.$index.' IN('.implode(',', $ids).')';
}
// --------------------------------------------------------------------
/**
- * Truncate statement
- *
- * Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
- *
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return 'TRUNCATE '.$table;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
- *
- * Generates a platform-specific delete string from the supplied data
- *
- * @param string the table name
- * @param array the where clause
- * @param string the limit clause
- * @return string
- */
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
- {
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ".implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= ' AND ';
- }
- $conditions .= implode("\n", $like);
- }
-
- return 'DELETE FROM '.$table.$conditions.( ! $limit ? '' : ' LIMIT '.$limit);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Limit string
*
* Generates a platform-specific LIMIT clause
@@ -690,12 +472,11 @@ class CI_DB_mysql_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @mysql_close($conn_id);
+ @mysql_close($this->conn_id);
}
}
diff --git a/system/database/drivers/mysql/mysql_forge.php b/system/database/drivers/mysql/mysql_forge.php
index 11172b41b..d22454d84 100644
--- a/system/database/drivers/mysql/mysql_forge.php
+++ b/system/database/drivers/mysql/mysql_forge.php
@@ -34,31 +34,7 @@
*/
class CI_DB_mysql_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return string
- */
- public function _create_database($name)
- {
- return 'CREATE DATABASE '.$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return string
- */
- public function _drop_database($name)
- {
- return 'DROP DATABASE '.$name;
- }
-
- // --------------------------------------------------------------------
+ protected $_create_database = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s';
/**
* Process Fields
@@ -84,8 +60,9 @@ class CI_DB_mysql_forge extends CI_DB_forge {
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field)
- .( ! empty($attributes['NAME']) ? ' '.$this->db->protect_identifiers($attributes['NAME']).' ' : '');
+ $sql .= "\n\t".$this->db->escape_identifiers($field);
+
+ empty($attributes['NAME']) OR ' '.$this->db->escape_identifiers($attributes['NAME']).' ';
if ( ! empty($attributes['TYPE']))
{
@@ -110,10 +87,23 @@ class CI_DB_mysql_forge extends CI_DB_forge {
}
}
- $sql .= (( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE) ? ' UNSIGNED' : '')
- .(isset($attributes['DEFAULT']) ? " DEFAULT '".$attributes['DEFAULT']."'" : '')
- .(( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE) ? ' NULL' : ' NOT NULL')
- .(( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) ? ' AUTO_INCREMENT' : '');
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
+ {
+ $sql .= ' UNSIGNED';
+ }
+
+ if (isset($attributes['DEFAULT']))
+ {
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
+ }
+
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
+
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
+ {
+ $sql .= ' AUTO_INCREMENT';
+ }
}
// don't add a comma on the end of the last field
@@ -138,7 +128,7 @@ class CI_DB_mysql_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -147,12 +137,12 @@ class CI_DB_mysql_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= $this->db->protect_identifiers($table).' ('.$this->_process_fields($fields);
+ $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields);
if (count($primary_keys) > 0)
{
- $key_name = $this->db->protect_identifiers(implode('_', $primary_keys));
- $sql .= ",\n\tPRIMARY KEY ".$key_name.' ('.implode(', ', $this->db->protect_identifiers($primary_keys)).')';
+ $key_name = $this->db->escape_identifiers(implode('_', $primary_keys));
+ $sql .= ",\n\tPRIMARY KEY ".$key_name.' ('.implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
@@ -161,12 +151,12 @@ class CI_DB_mysql_forge extends CI_DB_forge {
{
if (is_array($key))
{
- $key_name = $this->db->protect_identifiers(implode('_', $key));
- $key = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers(implode('_', $key));
+ $key = $this->db->escape_identifiers($key);
}
else
{
- $key_name = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers($key);
$key = array($key_name);
}
@@ -180,19 +170,6 @@ class CI_DB_mysql_forge extends CI_DB_forge {
// --------------------------------------------------------------------
/**
- * Drop Table
- *
- * @param string table name
- * @return string
- */
- public function _drop_table($table)
- {
- return 'DROP TABLE IF EXISTS '.$this->db->protect_identifiers($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Alter table query
*
* Generates a platform-specific query so that a table can be altered
@@ -204,34 +181,18 @@ class CI_DB_mysql_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $fields, $after_field = '')
+ protected function _alter_table($alter_type, $table, $fields, $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' ';
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' ';
// DROP has everything it needs now.
if ($alter_type === 'DROP')
{
- return $sql.$this->db->protect_identifiers($fields);
+ return $sql.$this->db->escape_identifiers($fields);
}
return $sql.$this->_process_fields($fields)
- .($after_field != '' ? ' AFTER '.$this->db->protect_identifiers($after_field) : '');
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/mysql/mysql_result.php b/system/database/drivers/mysql/mysql_result.php
index f76076f4c..14d6d072a 100644
--- a/system/database/drivers/mysql/mysql_result.php
+++ b/system/database/drivers/mysql/mysql_result.php
@@ -128,7 +128,7 @@ class CI_DB_mysql_result extends CI_DB_result {
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
diff --git a/system/database/drivers/mysql/mysql_utility.php b/system/database/drivers/mysql/mysql_utility.php
index 2d89cb9cb..f0bbc665e 100644
--- a/system/database/drivers/mysql/mysql_utility.php
+++ b/system/database/drivers/mysql/mysql_utility.php
@@ -34,54 +34,17 @@
*/
class CI_DB_mysql_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return string
- */
- public function _list_databases()
- {
- return 'SHOW DATABASES';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return string
- */
- public function _optimize_table($table)
- {
- return 'OPTIMIZE TABLE '.$this->db->protect_identifiers($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return string
- */
- public function _repair_table($table)
- {
- return 'REPAIR TABLE '.$this->db->protect_identifiers($table);
- }
+ protected $_list_databases = 'SHOW DATABASES';
+ protected $_optimize_table = 'OPTIMIZE TABLE %s';
+ protected $_repair_table = 'REPAIR TABLE %s';
- // --------------------------------------------------------------------
/**
* MySQL Export
*
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
if (count($params) === 0)
{
@@ -102,7 +65,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
}
// Get the table schema
- $query = $this->db->query('SHOW CREATE TABLE '.$this->db->protect_identifiers($this->db->database).'.'.$this->db->protect_identifiers($table));
+ $query = $this->db->query('SHOW CREATE TABLE '.$this->db->escape_identifiers($this->db->database.'.'.$table));
// No result means the table name was invalid
if ($query === FALSE)
@@ -113,7 +76,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
// Write out the table schema
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
- if ($add_drop == TRUE)
+ if ($add_drop === TRUE)
{
$output .= 'DROP TABLE IF EXISTS '.$this->db->protect_identifiers($table).';'.$newline.$newline;
}
@@ -129,7 +92,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
}
// If inserts are not needed we're done...
- if ($add_insert == FALSE)
+ if ($add_insert === FALSE)
{
continue;
}
@@ -137,7 +100,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
// Grab all the data from the current table
$query = $this->db->query('SELECT * FROM '.$this->db->protect_identifiers($table));
- if ($query->num_rows() == 0)
+ if ($query->num_rows() === 0)
{
continue;
}
@@ -157,7 +120,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
TRUE);
// Create a string of field names
- $field_str .= $this->db->protect_identifiers($field->name).', ';
+ $field_str .= $this->db->escape_identifiers($field->name).', ';
$i++;
}
@@ -180,7 +143,7 @@ class CI_DB_mysql_utility extends CI_DB_utility {
else
{
// Escape the data if it's not an integer
- $val_str .= ($is_int[$i] == FALSE) ? $this->db->escape($v) : $v;
+ $val_str .= ($is_int[$i] === FALSE) ? $this->db->escape($v) : $v;
}
// Append a comma
diff --git a/system/database/drivers/mysqli/mysqli_driver.php b/system/database/drivers/mysqli/mysqli_driver.php
index 47b0449d6..d3fb77a22 100644
--- a/system/database/drivers/mysqli/mysqli_driver.php
+++ b/system/database/drivers/mysqli/mysqli_driver.php
@@ -29,7 +29,7 @@
* MySQLi Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -47,7 +47,7 @@ class CI_DB_mysqli_driver extends CI_DB {
// clause and character used for LIKE escape sequences - not used in MySQL
protected $_like_escape_str = '';
- protected $_like_escape_chr = '';
+ protected $_like_escape_chr = '\\';
/**
* The syntax to count rows is slightly different across different
@@ -71,9 +71,9 @@ class CI_DB_mysqli_driver extends CI_DB {
*/
public function db_connect()
{
- return ($this->port != '')
- ? @new mysqli($this->hostname, $this->username, $this->password, $this->database, $this->port)
- : @new mysqli($this->hostname, $this->username, $this->password, $this->database);
+ return empty($this->port)
+ ? @new mysqli($this->hostname, $this->username, $this->password, $this->database)
+ : @new mysqli($this->hostname, $this->username, $this->password, $this->database, $this->port);
}
// --------------------------------------------------------------------
@@ -91,9 +91,9 @@ class CI_DB_mysqli_driver extends CI_DB {
return $this->db_connect();
}
- return ($this->port != '')
- ? @new mysqli('p:'.$this->hostname, $this->username, $this->password, $this->database, $this->port)
- : @new mysqli('p:'.$this->hostname, $this->username, $this->password, $this->database);
+ return empty($this->port)
+ ? @new mysqli('p:'.$this->hostname, $this->username, $this->password, $this->database)
+ : @new mysqli('p:'.$this->hostname, $this->username, $this->password, $this->database, $this->port);
}
// --------------------------------------------------------------------
@@ -291,7 +291,9 @@ class CI_DB_mysqli_driver extends CI_DB {
// escape LIKE condition wildcards
if ($like === TRUE)
{
- return str_replace(array('%', '_'), array('\\%', '\\_'), $str);
+ return str_replace(array($this->_like_escape_chr, '%', '_'),
+ array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
+ $str);
}
return $str;
@@ -324,35 +326,6 @@ class CI_DB_mysqli_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $query = $query->row();
- $this->_reset_select();
- return (int) $query->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -364,7 +337,7 @@ class CI_DB_mysqli_driver extends CI_DB {
{
$sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char;
- if ($prefix_limit !== FALSE && $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
}
@@ -397,7 +370,7 @@ class CI_DB_mysqli_driver extends CI_DB {
*/
public function field_data($table = '')
{
- if ($table == '')
+ if ($table === '')
{
return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE;
}
@@ -439,143 +412,6 @@ class CI_DB_mysqli_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item);
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * From Tables
- *
- * This function implicitly groups FROM tables so there is no confusion
- * about operator precedence in harmony with SQL standards
- *
- * @param string
- * @return string
- */
- protected function _from_tables($tables)
- {
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert_batch statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert_batch($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
- }
-
- // --------------------------------------------------------------------
-
-
- /**
- * Replace statement
- *
- * Generates a platform-specific replace string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _replace($table, $keys, $values)
- {
- return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key.' = '.$val;
- }
-
- return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
- .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '')
- .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '')
- .( ! $limit ? '' : ' LIMIT '.$limit);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Update_Batch statement
*
* Generates a platform-specific batch update string from the supplied data
@@ -594,7 +430,7 @@ class CI_DB_mysqli_driver extends CI_DB {
foreach (array_keys($val) as $field)
{
- if ($field != $index)
+ if ($field !== $index)
{
$final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
}
@@ -609,62 +445,16 @@ class CI_DB_mysqli_driver extends CI_DB {
.'ELSE '.$k.' END, ';
}
- $where = ($where != '' && count($where) > 0) ? implode(' ', $where).' AND ' : '';
+ $where = ($where !== '' && count($where) > 0) ? implode(' ', $where).' AND ' : '';
return 'UPDATE '.$table.' SET '.substr($cases, 0, -2)
- .' WHERE '.(($where != '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
+ .' WHERE '.(($where !== '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
.$index.' IN('.implode(',', $ids).')';
}
// --------------------------------------------------------------------
/**
- * Truncate statement
- *
- * Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
- *
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return 'TRUNCATE '.$table;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
- *
- * Generates a platform-specific delete string from the supplied data
- *
- * @param string the table name
- * @param array the where clause
- * @param string the limit clause
- * @return string
- */
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
- {
- $conditions = '';
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ".implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= ' AND ';
- }
- $conditions .= implode("\n", $like);
- }
-
- return 'DELETE FROM '.$table.$conditions.( ! $limit ? '' : ' LIMIT '.$limit);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Limit string
*
* Generates a platform-specific LIMIT clause
@@ -685,13 +475,11 @@ class CI_DB_mysqli_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param object
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
$this->conn_id->close();
- $this->conn_id = FALSE;
}
}
diff --git a/system/database/drivers/mysqli/mysqli_forge.php b/system/database/drivers/mysqli/mysqli_forge.php
index 8cf0ae1fd..b74c775b2 100644
--- a/system/database/drivers/mysqli/mysqli_forge.php
+++ b/system/database/drivers/mysqli/mysqli_forge.php
@@ -34,31 +34,7 @@
*/
class CI_DB_mysqli_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return string
- */
- public function _create_database($name)
- {
- return 'CREATE DATABASE '.$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return string
- */
- public function _drop_database($name)
- {
- return 'DROP DATABASE '.$name;
- }
-
- // --------------------------------------------------------------------
+ protected $_create_database = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s';
/**
* Process Fields
@@ -84,13 +60,13 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field)
- .( ! empty($attributes['NAME']) ? ' '.$this->db->protect_identifiers($attributes['NAME']).' ' : '')
- ;
+ $sql .= "\n\t".$this->db->escape_identifiers($field);
+
+ empty($attributes['NAME']) OR $sql .= ' '.$this->db->escape_identifiers($attributes['NAME']).' ';
if ( ! empty($attributes['TYPE']))
{
- $sql .= ' '.$attributes['TYPE'];
+ $sql .= ' '.$attributes['TYPE'];
if ( ! empty($attributes['CONSTRAINT']))
{
@@ -111,10 +87,23 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
}
}
- $sql .= (( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE) ? ' UNSIGNED' : '')
- .(isset($attributes['DEFAULT']) ? " DEFAULT '".$attributes['DEFAULT']."'" : '')
- .(( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE) ? ' NULL' : ' NOT NULL')
- .(( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) ? ' AUTO_INCREMENT' : '');
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
+ {
+ $sql .= ' UNSIGNED';
+ }
+
+ if (isset($attributes['DEFAULT']))
+ {
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
+ }
+
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
+
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
+ {
+ $sql .= ' AUTO_INCREMENT';
+ }
}
// don't add a comma on the end of the last field
@@ -139,7 +128,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -148,12 +137,12 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= $this->db->_escape_identifiers($table).' ('.$this->_process_fields($fields);
+ $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields);
if (count($primary_keys) > 0)
{
- $key_name = $this->db->protect_identifiers(implode('_', $primary_keys));
- $sql .= ",\n\tPRIMARY KEY ".$key_name.' ('.implode(', ', $this->db->protect_identifiers($primary_keys)).')';
+ $key_name = $this->db->escape_identifiers(implode('_', $primary_keys));
+ $sql .= ",\n\tPRIMARY KEY ".$key_name.' ('.implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
@@ -162,12 +151,12 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
{
if (is_array($key))
{
- $key_name = $this->db->protect_identifiers(implode('_', $key));
- $key = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers(implode('_', $key));
+ $key = $this->db->escape_identifiers($key);
}
else
{
- $key_name = $this->db->protect_identifiers($key);
+ $key_name = $this->db->escape_identifiers($key);
$key = array($key_name);
}
@@ -181,18 +170,6 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
// --------------------------------------------------------------------
/**
- * Drop Table
- *
- * @return string
- */
- public function _drop_table($table)
- {
- return 'DROP TABLE IF EXISTS '.$this->db->_escape_identifiers($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
* Alter table query
*
* Generates a platform-specific query so that a table can be altered
@@ -204,34 +181,18 @@ class CI_DB_mysqli_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $fields, $after_field = '')
+ protected function _alter_table($alter_type, $table, $fields, $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' ';
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' ';
// DROP has everything it needs now.
if ($alter_type === 'DROP')
{
- return $sql.$this->db->protect_identifiers($fields);
+ return $sql.$this->db->escape_identifiers($fields);
}
return $sql.$this->_process_fields($fields)
- .($after_field != '' ? ' AFTER '.$this->db->protect_identifiers($after_field) : '');
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/mysqli/mysqli_result.php b/system/database/drivers/mysqli/mysqli_result.php
index cf0362217..9b4d494d4 100644
--- a/system/database/drivers/mysqli/mysqli_result.php
+++ b/system/database/drivers/mysqli/mysqli_result.php
@@ -125,11 +125,11 @@ class CI_DB_mysqli_result extends CI_DB_result {
/**
* Data Seek
*
- * Moves the internal pointer to the desired offset. We call
+ * Moves the internal pointer to the desired offset. We call
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
diff --git a/system/database/drivers/mysqli/mysqli_utility.php b/system/database/drivers/mysqli/mysqli_utility.php
index 4d7002e78..27d4ef817 100644
--- a/system/database/drivers/mysqli/mysqli_utility.php
+++ b/system/database/drivers/mysqli/mysqli_utility.php
@@ -34,47 +34,9 @@
*/
class CI_DB_mysqli_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return string
- */
- public function _list_databases()
- {
- return 'SHOW DATABASES';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return string
- */
- public function _optimize_table($table)
- {
- return 'OPTIMIZE TABLE '.$this->db->_escape_identifiers($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return string
- */
- public function _repair_table($table)
- {
- return 'REPAIR TABLE '.$this->db->_escape_identifiers($table);
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = 'SHOW DATABASES';
+ protected $_optimize_table = 'OPTIMIZE TABLE %s';
+ protected $_repair_table = 'REPAIR TABLE %s';
/**
* MySQLi Export
@@ -82,7 +44,7 @@ class CI_DB_mysqli_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/oci8/oci8_driver.php b/system/database/drivers/oci8/oci8_driver.php
index 3bc8c114c..e78091614 100644
--- a/system/database/drivers/oci8/oci8_driver.php
+++ b/system/database/drivers/oci8/oci8_driver.php
@@ -29,7 +29,7 @@
* oci8 Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -46,7 +46,6 @@
* permit access to oracle databases
*
* @author Kelly McArdle
- *
*/
class CI_DB_oci8_driver extends CI_DB {
@@ -68,7 +67,7 @@ class CI_DB_oci8_driver extends CI_DB {
protected $_random_keyword = ' ASC'; // not currently supported
// Set "auto commit" by default
- protected $_commit = OCI_COMMIT_ON_SUCCESS;
+ public $commit_mode = OCI_COMMIT_ON_SUCCESS;
// need to track statement id and cursor id
public $stmt_id;
@@ -186,19 +185,6 @@ class CI_DB_oci8_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- // Not in Oracle - schemas are actually usernames
- return TRUE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Database version number
*
* @return string
@@ -220,12 +206,13 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _execute($sql)
{
- // oracle must parse the query before it is run. All of the actions with
- // the query are based on the statement id returned by ociparse
+ /* Oracle must parse the query before it is run. All of the actions with
+ * the query are based on the statement id returned by oci_parse().
+ */
$this->stmt_id = FALSE;
$this->_set_stmt_id($sql);
oci_set_prefetch($this->stmt_id, 1000);
- return @oci_execute($this->stmt_id, $this->_commit);
+ return @oci_execute($this->stmt_id, $this->commit_mode);
}
/**
@@ -251,8 +238,7 @@ class CI_DB_oci8_driver extends CI_DB {
*/
public function get_cursor()
{
- $this->curs_id = oci_new_cursor($this->conn_id);
- return $this->curs_id;
+ return $this->curs_id = oci_new_cursor($this->conn_id);
}
// --------------------------------------------------------------------
@@ -260,23 +246,23 @@ class CI_DB_oci8_driver extends CI_DB {
/**
* Stored Procedure. Executes a stored procedure
*
- * @param string package stored procedure is in
- * @param string stored procedure to execute
+ * @param string package name in which the stored procedure is in
+ * @param string stored procedure name to execute
* @param array parameters
- * @return object
+ * @return mixed
*
* params array keys
*
* KEY OPTIONAL NOTES
- * name no the name of the parameter should be in :<param_name> format
- * value no the value of the parameter. If this is an OUT or IN OUT parameter,
- * this should be a reference to a variable
- * type yes the type of the parameter
- * length yes the max size of the parameter
+ * name no the name of the parameter should be in :<param_name> format
+ * value no the value of the parameter. If this is an OUT or IN OUT parameter,
+ * this should be a reference to a variable
+ * type yes the type of the parameter
+ * length yes the max size of the parameter
*/
public function stored_procedure($package, $procedure, $params)
{
- if ($package == '' OR $procedure == '' OR ! is_array($params))
+ if ($package === '' OR $procedure === '' OR ! is_array($params))
{
if ($this->db_debug)
{
@@ -287,24 +273,24 @@ class CI_DB_oci8_driver extends CI_DB {
}
// build the query string
- $sql = "begin $package.$procedure(";
+ $sql = 'BEGIN '.$package.'.'.$procedure.'(';
$have_cursor = FALSE;
foreach ($params as $param)
{
- $sql .= $param['name'] . ",";
+ $sql .= $param['name'].',';
- if (array_key_exists('type', $param) && ($param['type'] === OCI_B_CURSOR))
+ if (isset($param['type']) && $param['type'] === OCI_B_CURSOR)
{
$have_cursor = TRUE;
}
}
- $sql = trim($sql, ",") . "); end;";
+ $sql = trim($sql, ',') . '); END;';
$this->stmt_id = FALSE;
$this->_set_stmt_id($sql);
$this->_bind_params($params);
- $this->query($sql, FALSE, $have_cursor);
+ return $this->query($sql, FALSE, $have_cursor);
}
// --------------------------------------------------------------------
@@ -360,7 +346,7 @@ class CI_DB_oci8_driver extends CI_DB {
// even if the queries produce a successful result.
$this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
- $this->_commit = OCI_DEFAULT;
+ $this->commit_mode = (is_php('5.3.2')) ? OCI_NO_AUTO_COMMIT : OCI_DEFAULT;
return TRUE;
}
@@ -384,9 +370,8 @@ class CI_DB_oci8_driver extends CI_DB {
return TRUE;
}
- $ret = oci_commit($this->conn_id);
- $this->_commit = OCI_COMMIT_ON_SUCCESS;
- return $ret;
+ $this->commit_mode = OCI_COMMIT_ON_SUCCESS;
+ return oci_commit($this->conn_id);
}
// --------------------------------------------------------------------
@@ -398,20 +383,14 @@ class CI_DB_oci8_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
- $ret = oci_rollback($this->conn_id);
- $this->_commit = OCI_COMMIT_ON_SUCCESS;
- return $ret;
+ $this->commit_mode = OCI_COMMIT_ON_SUCCESS;
+ return oci_rollback($this->conn_id);
}
// --------------------------------------------------------------------
@@ -476,35 +455,6 @@ class CI_DB_oci8_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query == FALSE)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Show table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -514,11 +464,11 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _list_tables($prefix_limit = FALSE)
{
- $sql = "SELECT TABLE_NAME FROM ALL_TABLES";
+ $sql = 'SELECT TABLE_NAME FROM ALL_TABLES';
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
- $sql .= " WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
+ return $sql." WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
return $sql;
@@ -536,7 +486,7 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _list_columns($table = '')
{
- return "SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = '$table'";
+ return 'SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = \''.$table.'\'';
}
// --------------------------------------------------------------------
@@ -551,7 +501,7 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _field_data($table)
{
- return "SELECT * FROM ".$table." where rownum = 1";
+ return 'SELECT * FROM '.$table.' WHERE rownum = 1';
}
// --------------------------------------------------------------------
@@ -588,47 +538,6 @@ class CI_DB_oci8_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
@@ -639,29 +548,7 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return implode(', ', $tables);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
// --------------------------------------------------------------------
@@ -683,46 +570,10 @@ class CI_DB_oci8_driver extends CI_DB {
for ($i = 0, $c = count($values); $i < $c; $i++)
{
- $sql .= ' INTO ' . $table . ' (' . $keys . ') VALUES ' . $values[$i] . "\n";
+ $sql .= ' INTO '.$table.' ('.$keys.') VALUES '.$values[$i]."\n";
}
- $sql .= 'SELECT * FROM dual';
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key." = ".$val;
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
-
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
-
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
-
- $sql .= $orderby.$limit;
-
- return $sql;
+ return $sql.'SELECT * FROM dual';
}
// --------------------------------------------------------------------
@@ -731,15 +582,16 @@ class CI_DB_oci8_driver extends CI_DB {
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
+ *
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
* @return string
*/
protected function _truncate($table)
{
- return "TRUNCATE TABLE ".$table;
+ return 'TRUNCATE TABLE '.$table;
}
// --------------------------------------------------------------------
@@ -751,28 +603,19 @@ class CI_DB_oci8_driver extends CI_DB {
*
* @param string the table name
* @param array the where clause
+ * @param array the like clause
* @param string the limit clause
* @return string
*/
protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
+ $conditions = array();
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
- }
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
+ empty($limit) OR $conditions[] = 'rownum <= '.$limit;
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- return "DELETE FROM ".$table.$conditions.$limit;
+ return 'DELETE FROM '.$table.(count($conditions) > 0 ? ' WHERE '.implode(' AND ', $conditions) : '');
}
// --------------------------------------------------------------------
@@ -789,18 +632,9 @@ class CI_DB_oci8_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- $limit = $offset + $limit;
- $newsql = "SELECT * FROM (select inner_query.*, rownum rnum FROM ($sql) inner_query WHERE rownum < $limit)";
-
- if ($offset != 0)
- {
- $newsql .= " WHERE rnum >= $offset";
- }
-
- // remember that we used limits
$this->limit_used = TRUE;
-
- return $newsql;
+ return 'SELECT * FROM (SELECT inner_query.*, rownum rnum FROM ('.$sql.') inner_query WHERE rownum < '.($offset + $limit).')'
+ .($offset !== 0 ? ' WHERE rnum >= '.$offset : '');
}
// --------------------------------------------------------------------
@@ -808,12 +642,11 @@ class CI_DB_oci8_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @oci_close($conn_id);
+ @oci_close($this->conn_id);
}
}
diff --git a/system/database/drivers/oci8/oci8_forge.php b/system/database/drivers/oci8/oci8_forge.php
index 8285a29d2..92e8c02ed 100644
--- a/system/database/drivers/oci8/oci8_forge.php
+++ b/system/database/drivers/oci8/oci8_forge.php
@@ -34,31 +34,9 @@
*/
class CI_DB_oci8_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return bool
- */
- public function _create_database($name)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_create_database = FALSE;
+ protected $_drop_database = FALSE;
+ protected $_drop_table = 'DROP TABLE %s';
/**
* Create Table
@@ -68,9 +46,9 @@ class CI_DB_oci8_forge extends CI_DB_forge {
* @param mixed primary key(s)
* @param mixed key(s)
* @param bool should 'IF NOT EXISTS' be added to the SQL
- * @return bool
+ * @return string
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -79,7 +57,7 @@ class CI_DB_oci8_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= $this->db->_escape_identifiers($table).' (';
+ $sql .= $this->db->escape_identifiers($table).' (';
$current_field_count = 0;
foreach ($fields as $field => $attributes)
@@ -95,11 +73,22 @@ class CI_DB_oci8_forge extends CI_DB_forge {
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field).' '.$attributes['TYPE']
- .((isset($attributes['UNSINGED']) && $attributes['UNSIGNED'] === TRUE) ? ' UNSIGNED' : '')
- .(isset($attributes['DEFAULT']) ? " DEFAULT '".$attributes['DEFAULT']."'" : '')
- .((isset($attributes['NULL']) && $attributes['NULL'] === TRUE) ? '' : ' NOT NULL')
- .(isset($attributes['CONSTRAINT']) ? ' CONSTRAINT '.$attributes['CONSTRAINT'] : '');
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
+
+ if (isset($attributes['UNSINGED']) && $attributes['UNSIGNED'] === TRUE)
+ {
+ $sql .= ' UNSIGNED';
+ }
+
+ if (isset($attributes['DEFAULT']))
+ {
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
+ }
+
+ $sql .= (isset($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? '' : ' NOT NULL';
+
+ empty($attributes['CONSTRAINT']) OR ' CONSTRAINT '.$attributes['CONSTRAINT'];
}
// don't add a comma on the end of the last field
@@ -111,24 +100,18 @@ class CI_DB_oci8_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tCONSTRAINT ".$table.' PRIMARY KEY ('.implode(', ', $primary_keys).')';
+ $sql .= ",\n\tCONSTRAINT ".$table.' PRIMARY KEY ('.implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tUNIQUE COLUMNS (".implode(', ', $key).")";
+ $sql .= ",\n\tUNIQUE COLUMNS (".implode(', ', $key).')';
}
}
@@ -138,18 +121,6 @@ class CI_DB_oci8_forge extends CI_DB_forge {
// --------------------------------------------------------------------
/**
- * Drop Table
- *
- * @return bool
- */
- public function _drop_table($table)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Alter table query
*
* Generates a platform-specific query so that a table can be altered
@@ -164,55 +135,21 @@ class CI_DB_oci8_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name);
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name);
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ if ($alter_type === 'DROP')
{
return $sql;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ return $sql.' '.$column_definition
+ .($default_value !== '' ? ' DEFAULT "'.$default_value.'"' : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
}
}
diff --git a/system/database/drivers/oci8/oci8_result.php b/system/database/drivers/oci8/oci8_result.php
index c3f775730..6fb6c81f1 100644
--- a/system/database/drivers/oci8/oci8_result.php
+++ b/system/database/drivers/oci8/oci8_result.php
@@ -39,6 +39,12 @@ class CI_DB_oci8_result extends CI_DB_result {
public $stmt_id;
public $curs_id;
public $limit_used;
+ public $commit_mode;
+
+ /* Overwriting the parent here, so we have a way to know if it's
+ * already called or not:
+ */
+ public $num_rows;
public function __construct(&$driver_object)
{
@@ -46,28 +52,32 @@ class CI_DB_oci8_result extends CI_DB_result {
$this->stmt_id = $driver_object->stmt_id;
$this->curs_id = $driver_object->curs_id;
$this->limit_used = $driver_object->limit_used;
+ $this->commit_mode =& $driver_object->commit_mode;
$driver_object->stmt_id = FALSE;
}
/**
* Number of rows in the result set.
*
- * Oracle doesn't have a graceful way to retun the number of rows
+ * Oracle doesn't have a graceful way to return the number of rows
* so we have to use what amounts to a hack.
*
* @return int
*/
public function num_rows()
{
- if ($this->num_rows === 0 && count($this->result_array()) > 0)
+ if ( ! is_int($this->num_rows))
{
- $this->num_rows = count($this->result_array());
- @oci_execute($this->stmt_id, OCI_DEFAULT);
-
- if ($this->curs_id)
+ if (count($this->result_array) > 0)
+ {
+ return $this->num_rows = count($this->result_array);
+ }
+ elseif (count($this->result_object) > 0)
{
- @oci_execute($this->curs_id, OCI_DEFAULT);
+ return $this->num_rows = count($this->result_object);
}
+
+ return $this->num_rows = count($this->result_array());
}
return $this->num_rows;
@@ -85,12 +95,7 @@ class CI_DB_oci8_result extends CI_DB_result {
$count = @oci_num_fields($this->stmt_id);
// if we used a limit we subtract it
- if ($this->limit_used)
- {
- $count = $count - 1;
- }
-
- return $count;
+ return ($this->limit_used) ? $count - 1 : $count;
}
// --------------------------------------------------------------------
@@ -126,10 +131,10 @@ class CI_DB_oci8_result extends CI_DB_result {
$retval = array();
for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++)
{
- $F = new stdClass();
- $F->name = oci_field_name($this->stmt_id, $c);
- $F->type = oci_field_type($this->stmt_id, $c);
- $F->max_length = oci_field_size($this->stmt_id, $c);
+ $F = new stdClass();
+ $F->name = oci_field_name($this->stmt_id, $c);
+ $F->type = oci_field_type($this->stmt_id, $c);
+ $F->max_length = oci_field_size($this->stmt_id, $c);
$retval[] = $F;
}
@@ -151,6 +156,17 @@ class CI_DB_oci8_result extends CI_DB_result {
oci_free_statement($this->result_id);
$this->result_id = FALSE;
}
+
+ if (is_resource($this->stmt_id))
+ {
+ oci_free_statement($this->stmt_id);
+ }
+
+ if (is_resource($this->curs_id))
+ {
+ oci_cancel($this->curs_id);
+ $this->curs_id = NULL;
+ }
}
// --------------------------------------------------------------------
@@ -180,13 +196,13 @@ class CI_DB_oci8_result extends CI_DB_result {
protected function _fetch_object()
{
$id = ($this->curs_id) ? $this->curs_id : $this->stmt_id;
- return @oci_fetch_object($id);
+ return oci_fetch_object($id);
}
// --------------------------------------------------------------------
/**
- * Query result. "array" version.
+ * Query result. Array version.
*
* @return array
*/
@@ -196,14 +212,429 @@ class CI_DB_oci8_result extends CI_DB_result {
{
return $this->result_array;
}
+ elseif (count($this->result_object) > 0)
+ {
+ for ($i = 0, $c = count($this->result_object); $i < $c; $i++)
+ {
+ $this->result_array[$i] = (array) $this->result_object[$i];
+ }
+
+ return $this->result_array;
+ }
+ elseif (is_array($this->row_data))
+ {
+ if (count($this->row_data) === 0)
+ {
+ return $this->result_array;
+ }
+ else
+ {
+ $row_index = count($this->row_data);
+ }
+ }
+ else
+ {
+ $row_index = 0;
+ $this->row_data = array();
+ }
$row = NULL;
while ($row = $this->_fetch_assoc())
{
- $this->result_array[] = $row;
+ $this->row_data[$row_index++] = $row;
+ }
+
+ return $this->result_array = $this->row_data;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Query result. "object" version.
+ *
+ * @return array
+ */
+ public function result_object()
+ {
+ if (count($this->result_object) > 0)
+ {
+ return $this->result_object;
+ }
+ elseif (count($this->result_array) > 0)
+ {
+ for ($i = 0, $c = count($this->result_array); $i < $c; $i++)
+ {
+ $this->result_object[] = (object) $this->result_array[$i];
+ }
+
+ return $this->result_object;
+ }
+ elseif (is_array($this->row_data))
+ {
+ if (count($this->row_data) === 0)
+ {
+ return $this->result_object;
+ }
+ else
+ {
+ $row_index = count($this->row_data);
+ for ($i = 0; $i < $row_index; $i++)
+ {
+ $this->result_object[$i] = (object) $this->row_data[$i];
+ }
+ }
+ }
+ else
+ {
+ $row_index = 0;
+ $this->row_data = array();
+ }
+
+ $row = NULL;
+ while ($row = $this->_fetch_object())
+ {
+ $this->row_data[$row_index] = (array) $row;
+ $this->result_object[$row_index++] = $row;
+ }
+
+ return $this->result_object;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Query result. Custom object version.
+ *
+ * @param string class name used to instantiate rows to
+ * @return array
+ */
+ public function custom_result_object($class_name)
+ {
+ if (isset($this->custom_result_object[$class_name]))
+ {
+ return $this->custom_result_object[$class_name];
+ }
+
+ if ( ! class_exists($class_name) OR $this->result_id === FALSE OR $this->num_rows() === 0)
+ {
+ return array();
+ }
+
+ /* Even if we didn't have result_array or result_object
+ * set prior to custom_result_object() being called,
+ * num_rows() has already done so.
+ * Pass by reference, as we don't know how
+ * large it might be and we don't want 1000 row
+ * sets being copied.
+ */
+ if (count($this->result_array) > 0)
+ {
+ $data = &$this->result_array;
+ }
+ elseif (count($this->result_object) > 0)
+ {
+ $data = &$this->result_object;
+ }
+
+ $this->custom_result_object[$class_name] = array();
+ for ($i = 0, $c = count($data); $i < $c; $i++)
+ {
+ $this->custom_result_object[$class_name][$i] = new $class_name();
+ foreach ($data[$i] as $key => $value)
+ {
+ $this->custom_result_object[$class_name][$i]->$key = $value;
+ }
+ }
+
+ return $this->custom_result_object[$class_name];
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result.
+ *
+ * Acts as a wrapper for row_object(), row_array()
+ * and custom_row_object(). Also used by first_row(), next_row()
+ * and previous_row().
+ *
+ * @param int row index
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function row($n = 0, $type = 'object')
+ {
+ if ($type === 'object')
+ {
+ return $this->row_object($n);
+ }
+ elseif ($type === 'array')
+ {
+ return $this->row_array($n);
+ }
+
+ return $this->custom_row_object($n, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Array version.
+ *
+ * @param int row index
+ * @return array
+ */
+ public function row_array($n = 0)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+
+ /* If row_data is initialized, it means that we've already tried
+ * (at least) to fetch some data, so ... check if we already have
+ * this row.
+ */
+ if (is_array($this->row_data))
+ {
+ /* If we already have row_data[$n] - return it.
+ *
+ * If we enter the elseif, there's a number of reasons to
+ * return an empty array:
+ *
+ * - count($this->row_data) === 0 means there are no results
+ * - num_rows being set, result_array and/or result_object
+ * having count() > 0 means that we've already fetched all
+ * data and $n is greater than our highest row index available
+ * - $n < $this->current_row means that if such row existed,
+ * we would've already returned it, therefore $n is an
+ * invalid index
+ */
+ if (isset($this->row_data[$n])) // We already have this row
+ {
+ $this->current_row = $n;
+ return $this->row_data[$n];
+ }
+ elseif (count($this->row_data) === 0 OR is_int($this->num_rows)
+ OR count($this->result_array) > 0 OR count($this->result_object) > 0
+ OR $n < $this->current_row)
+ {
+ // No such row exists
+ return NULL;
+ }
+
+ // Get the next row index that would actually need to be fetched
+ $current_row = ($this->current_row < count($this->row_data)) ? count($this->row_data) : $this->current_row + 1;
+ }
+ else
+ {
+ $current_row = $this->current_row = 0;
+ $this->row_data = array();
+ }
+
+ /* Fetch more data, if available
+ *
+ * NOTE: Operator precedence is important here, if you change
+ * 'AND' with '&&' - it WILL BREAK the results, as
+ * $row will be assigned the scalar value of both
+ * expressions!
+ */
+ while ($row = $this->_fetch_assoc() AND $current_row <= $n)
+ {
+ $this->row_data[$current_row++] = $row;
}
- return $this->result_array;
+ // This would mean that there's no (more) data to fetch
+ if ( ! is_array($this->row_data) OR ! isset($this->row_data[$n]))
+ {
+ // Cache what we already have
+ if (is_array($this->row_data))
+ {
+ $this->num_rows = count($this->row_data);
+ /* Usually, row_data could have less elements than result_array,
+ * but at this point - they should be exactly the same.
+ */
+ $this->result_array = $this->row_data;
+ }
+ else
+ {
+ $this->num_rows = 0;
+ }
+
+ return NULL;
+ }
+
+ $this->current_row = $n;
+ return $this->row_data[$n];
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Object version.
+ *
+ * @param int row index
+ * @return mixed object if row found; empty array if not
+ */
+ public function row_object($n = 0)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+ /* Logic here is exactly the same as in row_array,
+ * except we have to cast row_data[$n] to an object.
+ *
+ * If we already have result_object though - we can
+ * directly return from it.
+ */
+ if (isset($this->result_object[$n]))
+ {
+ $this->current_row = $n;
+ // Set this, if not already done.
+ if ( ! is_int($this->num_rows))
+ {
+ $this->num_rows = count($this->result_object);
+ }
+
+ return $this->result_object[$n];
+ }
+
+ $row = $this->row_array($n);
+ // Cast only if the row exists
+ if (count($row) > 0)
+ {
+ $this->current_row = $n;
+ return (object) $row;
+ }
+
+ return NULL;
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Custom object version.
+ *
+ * @param int row index
+ * @param string custom class name
+ * @return mixed custom object if row found; empty array otherwise
+ */
+ public function custom_row_object($n = 0, $class_name)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+
+ if (array_key_exists($class_name, $this->custom_result_object))
+ {
+ /* We already have a the whole result set with this class_name,
+ * return the specified row if it exists, and an empty array if
+ * it doesn't.
+ */
+ if (isset($this->custom_result_object[$class_name][$n]))
+ {
+ $this->current_row = $n;
+ return $this->custom_result_object[$class_name][$n];
+ }
+ else
+ {
+ return NULL;
+ }
+ }
+ elseif ( ! class_exists($class_name)) // No such class exists
+ {
+ return NULL;
+ }
+
+ $row = $this->row_array($n);
+ // A non-array would mean that the row doesn't exist
+ if ( ! is_array($row))
+ {
+ return NULL;
+ }
+
+ // Convert to the desired class and return
+ $row_object = new $class_name();
+ foreach ($row as $key => $value)
+ {
+ $row_object->$key = $value;
+ }
+
+ $this->current_row = $n;
+ return $row_object;
+ }
+
+ // --------------------------------------------------------------------
+
+ /* First row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function first_row($type = 'object')
+ {
+ return $this->row(0, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Last row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function last_row($type = 'object')
+ {
+ $result = &$this->result($type);
+ if ( ! isset($this->num_rows))
+ {
+ $this->num_rows = count($result);
+ }
+ $this->current_row = $this->num_rows - 1;
+ return $result[$this->current_row];
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Next row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function next_row($type = 'object')
+ {
+ if (is_array($this->row_data))
+ {
+ $count = count($this->row_data);
+ if ($this->current_row > $count OR ($this->current_row === 0 && $count === 0))
+ {
+ $n = $count;
+ }
+ else
+ {
+ $n = $this->current_row + 1;
+ }
+ }
+ else
+ {
+ $n = 0;
+ }
+
+ return $this->row($n, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Previous row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function previous_row($type = 'object')
+ {
+ $n = ($this->current_row !== 0) ? $this->current_row - 1 : 0;
+ return $this->row($n, $type);
}
// --------------------------------------------------------------------
@@ -213,13 +644,54 @@ class CI_DB_oci8_result extends CI_DB_result {
*
* Moves the internal pointer to the desired offset. We call
* this internally before fetching results to make sure the
- * result set starts at zero
+ * result set starts at zero.
*
- * @return array
+ * Oracle's PHP extension doesn't have an easy way of doing this
+ * and the only workaround is to (re)execute the statement or cursor
+ * in order to go to the first (zero) index of the result set.
+ * Then, we would need to "dummy" fetch ($n - 1) rows to get to the
+ * right one.
+ *
+ * This is as ridiculous as it sounds and it's the reason why every
+ * other method that is fetching data tries to use an already "cached"
+ * result set. Keeping this just in case it becomes needed at
+ * some point in the future, but it will only work for resetting the
+ * pointer to zero.
+ *
+ * @return bool
*/
- protected function _data_seek($n = 0)
+ protected function _data_seek()
{
- return FALSE; // Not needed
+ /* The PHP manual says that if OCI_NO_AUTO_COMMIT mode
+ * is used, and oci_rollback() and/or oci_commit() are
+ * not subsequently called - this will cause an unnecessary
+ * rollback to be triggered at the end of the script execution.
+ *
+ * Therefore we'll try to avoid using that mode flag
+ * if we're not currently in the middle of a transaction.
+ */
+ if ($this->commit_mode !== OCI_COMMIT_ON_SUCCESS)
+ {
+ $result = @oci_execute($this->stmt_id, $this->commit_mode);
+ }
+ else
+ {
+ $result = @oci_execute($this->stmt_id);
+ }
+
+ if ($result && $this->curs_id)
+ {
+ if ($this->commit_mode !== OCI_COMMIT_ON_SUCCESS)
+ {
+ return @oci_execute($this->curs_id, $this->commit_mode);
+ }
+ else
+ {
+ return @oci_execute($this->curs_id);
+ }
+ }
+
+ return $result;
}
}
diff --git a/system/database/drivers/oci8/oci8_utility.php b/system/database/drivers/oci8/oci8_utility.php
index e303fb6cb..0183eda26 100644
--- a/system/database/drivers/oci8/oci8_utility.php
+++ b/system/database/drivers/oci8/oci8_utility.php
@@ -34,47 +34,7 @@
*/
class CI_DB_oci8_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return bool
- */
- public function _list_databases()
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- return FALSE; // Is this supported in Oracle?
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- return FALSE; // Is this supported in Oracle?
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = 'SELECT username FROM dba_users'; // Schemas are actual usernames
/**
* Oracle Export
@@ -82,7 +42,7 @@ class CI_DB_oci8_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/odbc/odbc_driver.php b/system/database/drivers/odbc/odbc_driver.php
index ad773117f..222c311c0 100644
--- a/system/database/drivers/odbc/odbc_driver.php
+++ b/system/database/drivers/odbc/odbc_driver.php
@@ -29,7 +29,7 @@
* ODBC Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -64,7 +64,7 @@ class CI_DB_odbc_driver extends CI_DB {
$this->_random_keyword = ' RND('.time().')'; // database specific random keyword
// Legacy support for DSN in the hostname field
- if ($this->dsn == '')
+ if (empty($this->dsn))
{
$this->dsn = $this->hostname;
}
@@ -95,19 +95,6 @@ class CI_DB_odbc_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- // Not needed for ODBC
- return TRUE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Execute the query
*
* @param string an SQL query
@@ -127,13 +114,8 @@ class CI_DB_odbc_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -141,7 +123,7 @@ class CI_DB_odbc_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
+ $this->_trans_failure = ($test_mode === TRUE);
return odbc_autocommit($this->conn_id, FALSE);
}
@@ -155,13 +137,8 @@ class CI_DB_odbc_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -180,13 +157,8 @@ class CI_DB_odbc_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -217,7 +189,6 @@ class CI_DB_odbc_driver extends CI_DB {
return $str;
}
- // ODBC doesn't require escaping
$str = remove_invisible_characters($str);
// escape LIKE condition wildcards
@@ -258,36 +229,6 @@ class CI_DB_odbc_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string . $this->protect_identifiers('numrows') . " FROM " . $this->protect_identifiers($table, TRUE, NULL, FALSE));
-
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Show table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -297,9 +238,9 @@ class CI_DB_odbc_driver extends CI_DB {
*/
protected function _list_tables($prefix_limit = FALSE)
{
- $sql = "SHOW TABLES FROM `".$this->database."`";
+ $sql = 'SHOW TABLES FROM '.$this->database;
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
//$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
return FALSE; // not currently supported
@@ -320,7 +261,7 @@ class CI_DB_odbc_driver extends CI_DB {
*/
protected function _list_columns($table = '')
{
- return "SHOW COLUMNS FROM ".$table;
+ return 'SHOW COLUMNS FROM '.$table;
}
// --------------------------------------------------------------------
@@ -335,7 +276,7 @@ class CI_DB_odbc_driver extends CI_DB {
*/
protected function _field_data($table)
{
- return "SELECT TOP 1 FROM ".$table;
+ return 'SELECT TOP 1 FROM '.$table;
}
// --------------------------------------------------------------------
@@ -356,47 +297,6 @@ class CI_DB_odbc_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
@@ -407,114 +307,25 @@ class CI_DB_odbc_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key." = ".$val;
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
-
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
-
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
-
- $sql .= $orderby.$limit;
-
- return $sql;
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
-
// --------------------------------------------------------------------
/**
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
- *
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return $this->_delete($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
*
- * Generates a platform-specific delete string from the supplied data
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
- * @param array the where clause
- * @param string the limit clause
* @return string
*/
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
+ protected function _truncate($table)
{
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- return "DELETE FROM ".$table.$conditions.$limit;
+ return 'DELETE FROM '.$table;
}
// --------------------------------------------------------------------
@@ -531,8 +342,7 @@ class CI_DB_odbc_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- // Does ODBC doesn't use the LIMIT clause?
- return $sql;
+ return $sql.($offset == 0 ? '' : $offset.', ').$limit;
}
// --------------------------------------------------------------------
@@ -540,12 +350,11 @@ class CI_DB_odbc_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @odbc_close($conn_id);
+ @odbc_close($this->conn_id);
}
}
diff --git a/system/database/drivers/odbc/odbc_forge.php b/system/database/drivers/odbc/odbc_forge.php
index 486a8dd7f..b074c5884 100644
--- a/system/database/drivers/odbc/odbc_forge.php
+++ b/system/database/drivers/odbc/odbc_forge.php
@@ -34,43 +34,8 @@
*/
class CI_DB_odbc_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return bool
- */
- public function _create_database()
- {
- // ODBC has no "create database" command since it's
- // designed to connect to an existing database
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- // ODBC has no "drop database" command since it's
- // designed to connect to an existing database
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_drop_database = 'DROP DATABASE %s';
+ protected $_drop_table = 'DROP TABLE %s';
/**
* Create Table
@@ -82,7 +47,7 @@ class CI_DB_odbc_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -91,7 +56,7 @@ class CI_DB_odbc_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= $this->db->_escape_identifiers($table)." (";
+ $sql .= $this->db->escape_identifiers($table).' (';
$current_field_count = 0;
foreach ($fields as $field => $attributes)
@@ -101,41 +66,30 @@ class CI_DB_odbc_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field);
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- $sql .= ' '.$attributes['TYPE'];
+ empty($attributes['CONSTRAINT']) OR $sql .= '('.$attributes['CONSTRAINT'].')';
- if (array_key_exists('CONSTRAINT', $attributes))
- {
- $sql .= '('.$attributes['CONSTRAINT'].')';
- }
-
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -150,47 +104,22 @@ class CI_DB_odbc_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tFOREIGN KEY (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return bool
- */
- public function _drop_table($table)
- {
- // Not a supported ODBC feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -210,56 +139,20 @@ class CI_DB_odbc_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name);
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name);
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ if ($alter_type === 'DROP')
{
return $sql;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ return $sql.' '.$column_definition
+ .($default_value != '' ? ' DEFAULT "'.$default_value.'"' : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field != '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/odbc/odbc_result.php b/system/database/drivers/odbc/odbc_result.php
index 30cc979ce..227fe4fac 100644
--- a/system/database/drivers/odbc/odbc_result.php
+++ b/system/database/drivers/odbc/odbc_result.php
@@ -59,8 +59,6 @@ class CI_DB_odbc_result extends CI_DB_result {
return $this->num_rows;
}
- // --------------------------------------------------------------------
-
/**
* Number of fields in the result set
*
@@ -140,22 +138,6 @@ class CI_DB_odbc_result extends CI_DB_result {
// --------------------------------------------------------------------
/**
- * Data Seek
- *
- * Moves the internal pointer to the desired offset. We call
- * this internally before fetching results to make sure the
- * result set starts at zero
- *
- * @return bool
- */
- protected function _data_seek($n = 0)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Result - associative array
*
* Returns the result set as an array
@@ -164,14 +146,9 @@ class CI_DB_odbc_result extends CI_DB_result {
*/
protected function _fetch_assoc()
{
- if (function_exists('odbc_fetch_array'))
- {
- return odbc_fetch_array($this->result_id);
- }
- else
- {
- return $this->_odbc_fetch_array($this->result_id);
- }
+ return function_exists('odbc_fetch_array')
+ ? odbc_fetch_array($this->result_id)
+ : $this->_odbc_fetch_array($this->result_id);
}
// --------------------------------------------------------------------
@@ -185,14 +162,9 @@ class CI_DB_odbc_result extends CI_DB_result {
*/
protected function _fetch_object()
{
- if (function_exists('odbc_fetch_object'))
- {
- return odbc_fetch_object($this->result_id);
- }
- else
- {
- return $this->_odbc_fetch_object($this->result_id);
- }
+ return function_exists('odbc_fetch_object')
+ ? odbc_fetch_object($this->result_id)
+ : $this->_odbc_fetch_object($this->result_id);
}
// --------------------------------------------------------------------
@@ -208,15 +180,18 @@ class CI_DB_odbc_result extends CI_DB_result {
protected function _odbc_fetch_object(& $odbc_result)
{
$rs = array();
- $rs_obj = FALSE;
- if (odbc_fetch_into($odbc_result, $rs))
+ if ( ! odbc_fetch_into($odbc_result, $rs))
{
- foreach ($rs as $k => $v)
- {
- $field_name = odbc_field_name($odbc_result, $k+1);
- $rs_obj->$field_name = $v;
- }
+ return FALSE;
+ }
+
+ $rs_obj = new stdClass();
+ foreach ($rs as $k => $v)
+ {
+ $field_name = odbc_field_name($odbc_result, $k+1);
+ $rs_obj->$field_name = $v;
}
+
return $rs_obj;
}
@@ -233,16 +208,18 @@ class CI_DB_odbc_result extends CI_DB_result {
protected function _odbc_fetch_array(& $odbc_result)
{
$rs = array();
- $rs_assoc = FALSE;
- if (odbc_fetch_into($odbc_result, $rs))
+ if ( ! odbc_fetch_into($odbc_result, $rs))
{
- $rs_assoc = array();
- foreach ($rs as $k => $v)
- {
- $field_name = odbc_field_name($odbc_result, $k+1);
- $rs_assoc[$field_name] = $v;
- }
+ return FALSE;
}
+
+ $rs_assoc = array();
+ foreach ($rs as $k => $v)
+ {
+ $field_name = odbc_field_name($odbc_result, $k+1);
+ $rs_assoc[$field_name] = $v;
+ }
+
return $rs_assoc;
}
diff --git a/system/database/drivers/odbc/odbc_utility.php b/system/database/drivers/odbc/odbc_utility.php
index 65445e96c..224d48d2b 100644
--- a/system/database/drivers/odbc/odbc_utility.php
+++ b/system/database/drivers/odbc/odbc_utility.php
@@ -34,62 +34,7 @@
*/
class CI_DB_odbc_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return bool
- */
- public function _list_databases()
- {
- // Not sure if ODBC lets you list all databases...
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- // Not a supported ODBC feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- // Not a supported ODBC feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = FALSE;
/**
* ODBC Export
@@ -97,7 +42,7 @@ class CI_DB_odbc_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/pdo/pdo_driver.php b/system/database/drivers/pdo/pdo_driver.php
index f336eb0ab..e25013a52 100644
--- a/system/database/drivers/pdo/pdo_driver.php
+++ b/system/database/drivers/pdo/pdo_driver.php
@@ -29,7 +29,7 @@
* PDO Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -46,8 +46,8 @@ class CI_DB_pdo_driver extends CI_DB {
protected $_escape_char = '';
// clause and character used for LIKE escape sequences
- protected $_like_escape_str;
- protected $_like_escape_chr;
+ protected $_like_escape_str = " ESCAPE '%s' ";
+ protected $_like_escape_chr = '!';
/**
* The syntax to count rows is slightly different across different
@@ -65,7 +65,7 @@ class CI_DB_pdo_driver extends CI_DB {
{
parent::__construct($params);
- if (preg_match('/([^;]+):/', $this->dsn, $match) && count($match) == 2)
+ if (preg_match('/([^;]+):/', $this->dsn, $match) && count($match) === 2)
{
// If there is a minimum valid dsn string pattern found, we're done
// This is for general PDO users, who tend to have a full DSN string.
@@ -79,20 +79,19 @@ class CI_DB_pdo_driver extends CI_DB {
// clause and character used for LIKE escape sequences
// this one depends on the driver being used
- if ($this->pdodriver == 'mysql')
+ if ($this->pdodriver === 'mysql')
{
+ $this->_escape_char = '`';
$this->_like_escape_str = '';
- $this->_like_escape_chr = '';
+ $this->_like_escape_chr = '\\';
}
- elseif ($this->pdodriver == 'odbc')
+ elseif ($this->pdodriver === 'odbc')
{
$this->_like_escape_str = " {escape '%s'} ";
- $this->_like_escape_chr = '!';
}
- else
+ elseif ( ! in_array($this->pdodriver, array('sqlsrv', 'mssql', 'dblib', 'sybase')))
{
- $this->_like_escape_str = " ESCAPE '%s' ";
- $this->_like_escape_chr = '!';
+ $this->_escape_char = '"';
}
$this->trans_enabled = FALSE;
@@ -184,6 +183,8 @@ class CI_DB_pdo_driver extends CI_DB {
}
}
+ // --------------------------------------------------------------------
+
/**
* Non-persistent database connection
*
@@ -191,9 +192,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function db_connect()
{
- $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
-
- return $this->pdo_connect();
+ return $this->_pdo_connect();
}
// --------------------------------------------------------------------
@@ -205,10 +204,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function db_pconnect()
{
- $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
- $this->options[PDO::ATTR_PERSISTENT] = TRUE;
-
- return $this->pdo_connect();
+ return $this->_pdo_connect(TRUE);
}
// --------------------------------------------------------------------
@@ -216,20 +212,29 @@ class CI_DB_pdo_driver extends CI_DB {
/**
* PDO connection
*
+ * @param bool
* @return object
*/
- public function pdo_connect()
+ protected function _pdo_connect($persistent = FALSE)
{
- // Refer : http://php.net/manual/en/ref.pdo-mysql.connection.php
- if ($this->pdodriver === 'mysql' && ! is_php('5.3.6'))
+ $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
+ $persistent === FALSE OR $this->options[PDO::ATTR_PERSISTENT] = TRUE;
+
+ /* Prior to PHP 5.3.6, even if the charset was supplied in the DSN
+ * on connect - it was ignored. This is a work-around for the issue.
+ *
+ * Reference: http://www.php.net/manual/en/ref.pdo-mysql.connection.php
+ */
+ if ($this->pdodriver === 'mysql' && ! is_php('5.3.6') && ! empty($this->char_set))
{
- $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES $this->char_set COLLATE '$this->dbcollat'";
+ $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$this->char_set
+ .( ! empty($this->db_collat) ? " COLLATE '".$this->dbcollat."'" : '');
}
// Connecting...
try
{
- $db = new PDO($this->dsn, $this->username, $this->password, $this->options);
+ return new PDO($this->dsn, $this->username, $this->password, $this->options);
}
catch (PDOException $e)
{
@@ -240,21 +245,6 @@ class CI_DB_pdo_driver extends CI_DB {
return FALSE;
}
-
- return $db;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- // Not needed for PDO
- return TRUE;
}
// --------------------------------------------------------------------
@@ -281,46 +271,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
protected function _execute($sql)
{
- $sql = $this->_prep_query($sql);
-
- $result_id = $this->conn_id->query($sql);
-
- if (is_object($result_id))
- {
- $this->affect_rows = $result_id->rowCount();
- }
- else
- {
- $this->affect_rows = 0;
- }
-
- return $result_id;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Prep the query
- *
- * If needed, each database adapter can prep the query string
- *
- * @param string an SQL query
- * @return string
- */
- protected function _prep_query($sql)
- {
- if ($this->pdodriver === 'pgsql')
- {
- // Change the backtick(s) for Postgre
- $sql = str_replace('`', '"', $sql);
- }
- elseif ($this->pdodriver === 'sqlite')
- {
- // Change the backtick(s) for SQLite
- $sql = str_replace('`', '', $sql);
- }
-
- return $sql;
+ return $this->conn_id->query($sql);
}
// --------------------------------------------------------------------
@@ -332,13 +283,8 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -346,7 +292,7 @@ class CI_DB_pdo_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = (bool) ($test_mode === TRUE);
+ $this->_trans_failure = ($test_mode === TRUE);
return $this->conn_id->beginTransaction();
}
@@ -360,20 +306,13 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
- $ret = $this->conn->commit();
-
- return $ret;
+ return $this->conn_id->commit();
}
// --------------------------------------------------------------------
@@ -385,20 +324,13 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
- $ret = $this->conn_id->rollBack();
-
- return $ret;
+ return $this->conn_id->rollBack();
}
// --------------------------------------------------------------------
@@ -422,10 +354,10 @@ class CI_DB_pdo_driver extends CI_DB {
return $str;
}
- //Escape the string
+ // Escape the string
$str = $this->conn_id->quote($str);
- //If there are duplicated quotes, trim them away
+ // If there are duplicated quotes, trim them away
if (strpos($str, "'") === 0)
{
$str = substr($str, 1, -1);
@@ -451,7 +383,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
public function affected_rows()
{
- return $this->affect_rows;
+ return is_object($this->result_id) ? $this->result_id->rowCount() : 0;
}
// --------------------------------------------------------------------
@@ -459,6 +391,7 @@ class CI_DB_pdo_driver extends CI_DB {
/**
* Insert ID
*
+ * @param string
* @return int
*/
public function insert_id($name = NULL)
@@ -476,38 +409,6 @@ class CI_DB_pdo_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $sql = $this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE);
- $query = $this->query($sql);
-
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
-
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Show table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -517,22 +418,22 @@ class CI_DB_pdo_driver extends CI_DB {
*/
protected function _list_tables($prefix_limit = FALSE)
{
- if ($this->pdodriver == 'pgsql')
+ if ($this->pdodriver === 'pgsql')
{
// Analog function to show all tables in postgre
$sql = "SELECT * FROM information_schema.tables WHERE table_schema = 'public'";
}
- elseif ($this->pdodriver == 'sqlite')
+ elseif ($this->pdodriver === 'sqlite')
{
// Analog function to show all tables in sqlite
$sql = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
}
else
{
- $sql = "SHOW TABLES FROM `".$this->database."`";
+ $sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database);
}
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE AND $this->dbprefix !== '')
{
return FALSE;
}
@@ -552,7 +453,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
protected function _list_columns($table = '')
{
- return 'SHOW COLUMNS FROM '.$this->_from_tables($table);
+ return 'SHOW COLUMNS FROM '.$this->escape_identifiers($table);
}
// --------------------------------------------------------------------
@@ -567,23 +468,23 @@ class CI_DB_pdo_driver extends CI_DB {
*/
protected function _field_data($table)
{
- if ($this->pdodriver == 'mysql' or $this->pdodriver == 'pgsql')
+ if ($this->pdodriver === 'mysql' or $this->pdodriver === 'pgsql')
{
// Analog function for mysql and postgre
- return 'SELECT * FROM '.$this->_from_tables($table).' LIMIT 1';
+ return 'SELECT * FROM '.$this->escape_identifiers($table).' LIMIT 1';
}
- elseif ($this->pdodriver == 'oci')
+ elseif ($this->pdodriver === 'oci')
{
// Analog function for oci
- return 'SELECT * FROM '.$this->_from_tables($table).' WHERE ROWNUM <= 1';
+ return 'SELECT * FROM '.$this->escape_identifiers($table).' WHERE ROWNUM <= 1';
}
- elseif ($this->pdodriver == 'sqlite')
+ elseif ($this->pdodriver === 'sqlite')
{
// Analog function for sqlite
- return 'PRAGMA table_info('.$this->_from_tables($table).')';
+ return 'PRAGMA table_info('.$this->escape_identifiers($table).')';
}
- return 'SELECT TOP 1 FROM '.$this->_from_tables($table);
+ return 'SELECT TOP 1 FROM '.$this->escape_identifiers($table);
}
// --------------------------------------------------------------------
@@ -618,134 +519,6 @@ class CI_DB_pdo_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item);
- $str .= $this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * From Tables
- *
- * This function implicitly groups FROM tables so there is no confusion
- * about operator precedence in harmony with SQL standards
- *
- * @param array
- * @return string
- */
- protected function _from_tables($tables)
- {
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return (count($tables) == 1) ? '`'.$tables[0].'`' : '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return 'INSERT INTO '.$this->_from_tables($table).' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert_batch statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert_batch($table, $keys, $values)
- {
- return 'INSERT INTO '.$this->_from_tables($table).' ('.implode(', ', $keys).') VALUES '.implode(', ', $values);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key." = ".$val;
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
- $orderby = (count($orderby) >= 1) ? ' ORDER BY '.implode(', ', $orderby) : '';
-
- $sql = 'UPDATE '.$this->_from_tables($table).' SET '.implode(', ', $valstr);
- $sql .= ($where != '' && count($where) >= 1) ? ' WHERE '.implode(' ', $where) : '';
- $sql .= $orderby.$limit;
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Update_Batch statement
*
* Generates a platform-specific batch update string from the supplied data
@@ -758,7 +531,7 @@ class CI_DB_pdo_driver extends CI_DB {
protected function _update_batch($table, $values, $index, $where = NULL)
{
$ids = array();
- $where = ($where != '' && count($where) >=1) ? implode(" ", $where).' AND ' : '';
+ $where = ($where !== '' && count($where) >=1) ? implode(" ", $where).' AND ' : '';
foreach ($values as $key => $val)
{
@@ -766,14 +539,14 @@ class CI_DB_pdo_driver extends CI_DB {
foreach (array_keys($val) as $field)
{
- if ($field != $index)
+ if ($field !== $index)
{
$final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field];
}
}
}
- $sql = 'UPDATE '.$this->_from_tables($table).' SET ';
+ $sql = 'UPDATE '.$table.' SET ';
$cases = '';
foreach ($final as $k => $v)
@@ -800,49 +573,16 @@ class CI_DB_pdo_driver extends CI_DB {
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
*
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return $this->_delete($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
- *
- * Generates a platform-specific delete string from the supplied data
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
- * @param array the where clause
- * @param string the limit clause
* @return string
*/
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
+ protected function _truncate($table)
{
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
-
- $conditions .= implode("\n", $like);
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- return 'DELETE FROM '.$this->_from_tables($table).$conditions.$limit;
+ return 'DELETE FROM '.$table;
}
// --------------------------------------------------------------------
@@ -859,7 +599,7 @@ class CI_DB_pdo_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- if ($this->pdodriver == 'cubrid' OR $this->pdodriver == 'sqlite')
+ if ($this->pdodriver === 'cubrid' OR $this->pdodriver === 'sqlite')
{
$offset = ($offset == 0) ? '' : $offset.', ';
@@ -874,19 +614,6 @@ class CI_DB_pdo_driver extends CI_DB {
}
}
- // --------------------------------------------------------------------
-
- /**
- * Close DB Connection
- *
- * @param resource
- * @return void
- */
- protected function _close($conn_id)
- {
- $this->conn_id = null;
- }
-
}
/* End of file pdo_driver.php */
diff --git a/system/database/drivers/pdo/pdo_forge.php b/system/database/drivers/pdo/pdo_forge.php
index 6bff3542f..02ceb74fe 100644
--- a/system/database/drivers/pdo/pdo_forge.php
+++ b/system/database/drivers/pdo/pdo_forge.php
@@ -34,43 +34,8 @@
*/
class CI_DB_pdo_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return bool
- */
- public function _create_database()
- {
- // PDO has no "create database" command since it's
- // designed to connect to an existing database
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- // PDO has no "drop database" command since it's
- // designed to connect to an existing database
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_drop_database = 'DROP DATABASE %s';
+ protected $_drop_table = 'DROP TABLE %s';
/**
* Create Table
@@ -82,7 +47,7 @@ class CI_DB_pdo_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -91,56 +56,48 @@ class CI_DB_pdo_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= '`'.$this->db->_escape_identifiers($table).'` (';
+ $sql .= $this->db->escape_identifiers($table).' (';
$current_field_count = 0;
- foreach ($fields as $field=>$attributes)
+ foreach ($fields as $field => $attributes)
{
// Numeric field names aren't allowed in databases, so if the key is
// numeric, we know it was assigned by PHP and the developer manually
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $numeric = array('SERIAL', 'INTEGER');
+ $numeric = array('SERIAL', 'INTEGER');
- $sql .= "\n\t".$this->db->protect_identifiers($field);
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- $sql .= ' '.$attributes['TYPE'];
-
- if (array_key_exists('CONSTRAINT', $attributes))
+ if ( ! empty($attributes['CONSTRAINT']))
{
// Exception for Postgre numeric which not too happy with constraint within those type
- if ( ! ($this->db->pdodriver == 'pgsql' && in_array($attributes['TYPE'], $numeric)))
+ if ( ! ($this->db->pdodriver === 'pgsql' && in_array($attributes['TYPE'], $numeric)))
{
$sql .= '('.$attributes['CONSTRAINT'].')';
}
}
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -155,47 +112,22 @@ class CI_DB_pdo_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tFOREIGN KEY (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return bool
- */
- public function _drop_table($table)
- {
- // Not a supported PDO feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -215,56 +147,20 @@ class CI_DB_pdo_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE `'.$this->db->protect_identifiers($table).'` '.$alter_type.' '.$this->db->protect_identifiers($column_name);
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name);
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ if ($alter_type === 'DROP')
{
return $sql;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ return $sql .' '.$column_definition
+ .($default_value !== '' ? " DEFAULT '".$default_value."'" : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/pdo/pdo_result.php b/system/database/drivers/pdo/pdo_result.php
index 5bbd85d75..0b8937cc5 100644
--- a/system/database/drivers/pdo/pdo_result.php
+++ b/system/database/drivers/pdo/pdo_result.php
@@ -84,20 +84,14 @@ class CI_DB_pdo_result extends CI_DB_result {
// Define the output
$output = array('assoc', 'object');
+ // Initial value
+ $this->result_assoc = array() and $this->result_object = array();
+
// Fetch the result
- foreach ($output as $type)
+ while ($row = $this->_fetch_assoc())
{
- // Define the method and handler
- $res_method = '_fetch_'.$type;
- $res_handler = 'result_'.$type;
-
- $this->$res_handler = array();
- $this->_data_seek(0);
-
- while ($row = $this->$res_method())
- {
- $this->{$res_handler}[] = $row;
- }
+ $this->result_assoc[] = $row;
+ $this->result_object[] = (object) $row;
}
// Save this as buffer and marked the fetch flag
@@ -228,22 +222,6 @@ class CI_DB_pdo_result extends CI_DB_result {
// --------------------------------------------------------------------
/**
- * Data Seek
- *
- * Moves the internal pointer to the desired offset. We call
- * this internally before fetching results to make sure the
- * result set starts at zero
- *
- * @return bool
- */
- protected function _data_seek($n = 0)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Result - associative array
*
* Returns the result set as an array
@@ -266,7 +244,7 @@ class CI_DB_pdo_result extends CI_DB_result {
*/
protected function _fetch_object()
{
- return $this->result_id->fetchObject();
+ return $this->result_id->fetch(PDO::FETCH_OBJ);
}
}
diff --git a/system/database/drivers/pdo/pdo_utility.php b/system/database/drivers/pdo/pdo_utility.php
index 86c798397..930842118 100644
--- a/system/database/drivers/pdo/pdo_utility.php
+++ b/system/database/drivers/pdo/pdo_utility.php
@@ -34,62 +34,7 @@
*/
class CI_DB_pdo_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return bool
- */
- public function _list_databases()
- {
- // Not sure if PDO lets you list all databases...
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- // Not a supported PDO feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- // Not a supported PDO feature
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = FALSE;
/**
* PDO Export
@@ -97,7 +42,7 @@ class CI_DB_pdo_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/postgre/postgre_driver.php b/system/database/drivers/postgre/postgre_driver.php
index 3e2d05ce8..7375fbf71 100644
--- a/system/database/drivers/postgre/postgre_driver.php
+++ b/system/database/drivers/postgre/postgre_driver.php
@@ -29,7 +29,7 @@
* Postgre Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -80,16 +80,16 @@ class CI_DB_postgre_driver extends CI_DB {
$this->port = '';
}
- $this->hostname === '' OR $this->dsn = 'host='.$this->hostname;
+ $this->hostname === '' OR $this->dsn = 'host='.$this->hostname.' ';
if ( ! empty($this->port) && ctype_digit($this->port))
{
- $this->dsn .= 'host='.$this->port.' ';
+ $this->dsn .= 'port='.$this->port.' ';
}
if ($this->username !== '')
{
- $this->dsn .= 'username='.$this->username.' ';
+ $this->dsn .= 'user='.$this->username.' ';
/* An empty password is valid!
*
@@ -162,23 +162,10 @@ class CI_DB_postgre_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- // Not needed for Postgre so we'll return TRUE
- return TRUE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Set client character set
*
- * @param string
- * @return bool
+ * @param string
+ * @return bool
*/
protected function _db_set_charset($charset)
{
@@ -232,6 +219,7 @@ class CI_DB_postgre_driver extends CI_DB {
/**
* Begin Transaction
*
+ * @param bool
* @return bool
*/
public function trans_begin($test_mode = FALSE)
@@ -247,7 +235,7 @@ class CI_DB_postgre_driver extends CI_DB {
// even if the queries produce a successful result.
$this->_trans_failure = ($test_mode === TRUE);
- return @pg_query($this->conn_id, 'BEGIN');
+ return (bool) @pg_query($this->conn_id, 'BEGIN');
}
// --------------------------------------------------------------------
@@ -265,7 +253,7 @@ class CI_DB_postgre_driver extends CI_DB {
return TRUE;
}
- return @pg_query($this->conn_id, 'COMMIT');
+ return (bool) @pg_query($this->conn_id, 'COMMIT');
}
// --------------------------------------------------------------------
@@ -283,7 +271,7 @@ class CI_DB_postgre_driver extends CI_DB {
return TRUE;
}
- return @pg_query($this->conn_id, 'ROLLBACK');
+ return (bool) @pg_query($this->conn_id, 'ROLLBACK');
}
// --------------------------------------------------------------------
@@ -323,6 +311,27 @@ class CI_DB_postgre_driver extends CI_DB {
// --------------------------------------------------------------------
/**
+ * "Smart" Escape String
+ *
+ * Escapes data based on type
+ * Sets boolean and null types
+ *
+ * @param string
+ * @return mixed
+ */
+ public function escape($str)
+ {
+ if (is_bool($str))
+ {
+ return ($str) ? 'TRUE' : 'FALSE';
+ }
+
+ return parent::escape($str);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Affected Rows
*
* @return int
@@ -341,63 +350,41 @@ class CI_DB_postgre_driver extends CI_DB {
*/
public function insert_id()
{
- $v = $this->version();
+ $v = pg_version($this->conn_id);
+ $v = isset($v['server']) ? $v['server'] : 0; // 'server' key is only available since PosgreSQL 7.4
- $table = func_num_args() > 0 ? func_get_arg(0) : NULL;
- $column = func_num_args() > 1 ? func_get_arg(1) : NULL;
+ $table = (func_num_args() > 0) ? func_get_arg(0) : NULL;
+ $column = (func_num_args() > 1) ? func_get_arg(1) : NULL;
- if ($table == NULL && $v >= '8.1')
+ if ($table === NULL && $v >= '8.1')
{
- $sql='SELECT LASTVAL() as ins_id';
+ $sql = 'SELECT LASTVAL() AS ins_id';
}
- elseif ($table != NULL && $column != NULL && $v >= '8.0')
+ elseif ($table !== NULL)
{
- $sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column);
- $query = $this->query($sql);
- $row = $query->row();
- $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq);
- }
- elseif ($table != NULL)
- {
- // seq_name passed in table parameter
- $sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table);
+ if ($column !== NULL && $v >= '8.0')
+ {
+ $sql = 'SELECT pg_get_serial_sequence(\''.$table."', '".$column."') AS seq";
+ $query = $this->query($sql);
+ $query = $query->row();
+ $seq = $query->seq;
+ }
+ else
+ {
+ // seq_name passed in table parameter
+ $seq = $table;
+ }
+
+ $sql = 'SELECT CURRVAL(\''.$seq."') AS ins_id";
}
else
{
return pg_last_oid($this->result_id);
}
- $query = $this->query($sql);
- $row = $query->row();
- return $row->ins_id;
- }
- // --------------------------------------------------------------------
-
- /**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
+ $query = $this->query($sql);
+ $query = $query->row();
+ return (int) $query->ins_id;
}
// --------------------------------------------------------------------
@@ -414,9 +401,9 @@ class CI_DB_postgre_driver extends CI_DB {
{
$sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'";
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix !== '')
{
- $sql .= " AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
+ return $sql." AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
return $sql;
@@ -434,7 +421,7 @@ class CI_DB_postgre_driver extends CI_DB {
*/
protected function _list_columns($table = '')
{
- return "SELECT column_name FROM information_schema.columns WHERE table_name ='".$table."'";
+ return "SELECT column_name FROM information_schema.columns WHERE table_name = '".$table."'";
}
// --------------------------------------------------------------------
@@ -445,11 +432,11 @@ class CI_DB_postgre_driver extends CI_DB {
* Generates a platform-specific query so that the column data can be retrieved
*
* @param string the table name
- * @return object
+ * @return string
*/
protected function _field_data($table)
{
- return "SELECT * FROM ".$table." LIMIT 1";
+ return 'SELECT * FROM '.$table.' LIMIT 1';
}
// --------------------------------------------------------------------
@@ -470,47 +457,6 @@ class CI_DB_postgre_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
@@ -521,46 +467,7 @@ class CI_DB_postgre_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return implode(', ', $tables);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert_batch statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert_batch($table, $keys, $values)
- {
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values);
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
// --------------------------------------------------------------------
@@ -573,39 +480,67 @@ class CI_DB_postgre_driver extends CI_DB {
* @param string the table name
* @param array the update data
* @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
+ * @param array the orderby clause (ignored)
+ * @param array the limit clause (ignored)
+ * @param array the like clause
* @return string
*/
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
+ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
{
foreach ($values as $key => $val)
{
- $valstr[] = $key." = ".$val;
+ $valstr[] = $key.' = '.$val;
}
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
+ $where = empty($where) ? '' : ' WHERE '.implode(' ', $where);
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
+ if ( ! empty($like))
+ {
+ $where .= ($where === '' ? ' WHERE ' : ' AND ').implode(' ', $like);
+ }
- return $sql;
+ return 'UPDATE '.$table.' SET '.implode(', ', $valstr).$where;
}
// --------------------------------------------------------------------
/**
- * Truncate statement
+ * Update_Batch statement
*
- * Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
+ * Generates a platform-specific batch update string from the supplied data
*
* @param string the table name
+ * @param array the update data
+ * @param array the where clause
* @return string
*/
- protected function _truncate($table)
+ protected function _update_batch($table, $values, $index, $where = NULL)
{
- return "TRUNCATE ".$table;
+ $ids = array();
+ foreach ($values as $key => $val)
+ {
+ $ids[] = $val[$index];
+
+ foreach (array_keys($val) as $field)
+ {
+ if ($field !== $index)
+ {
+ $final[$field][] = 'WHEN '.$val[$index].' THEN '.$val[$field];
+ }
+ }
+ }
+
+ $cases = '';
+ foreach ($final as $k => $v)
+ {
+ $cases .= $k.' = (CASE '.$k."\n"
+ .implode("\n", $v)."\n"
+ .'ELSE '.$k.' END), ';
+ }
+
+ return 'UPDATE '.$table.' SET '.substr($cases, 0, -2)
+ .' WHERE '.(($where !== '' && count($where) > 0) ? implode(' ', $where).' AND ' : '')
+ .$index.' IN('.implode(',', $ids).')';
}
// --------------------------------------------------------------------
@@ -617,29 +552,22 @@ class CI_DB_postgre_driver extends CI_DB {
*
* @param string the table name
* @param array the where clause
- * @param string the limit clause
+ * @param array the like clause
+ * @param string the limit clause (ignored)
* @return string
*/
protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
+ $conditions = array();
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
- }
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
- return "DELETE FROM ".$table.$conditions;
+ return 'DELETE FROM '.$table.(count($conditions) > 0 ? ' WHERE '.implode(' AND ', $conditions) : '');
}
// --------------------------------------------------------------------
+
/**
* Limit string
*
@@ -652,14 +580,79 @@ class CI_DB_postgre_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- $sql .= "LIMIT ".$limit;
+ return $sql.' LIMIT '.$limit.($offset == 0 ? '' : ' OFFSET '.$offset);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Where
+ *
+ * Called by where() or or_where()
+ *
+ * @param mixed
+ * @param mixed
+ * @param string
+ * @return object
+ *
+ */
+ protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL)
+ {
+ $type = $this->_group_get_type($type);
- if ($offset > 0)
+ if ( ! is_array($key))
{
- $sql .= " OFFSET ".$offset;
+ $key = array($key => $value);
}
- return $sql;
+ // If the escape value was not set will will base it on the global setting
+ if ( ! is_bool($escape))
+ {
+ $escape = $this->_protect_identifiers;
+ }
+
+ foreach ($key as $k => $v)
+ {
+ $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type;
+
+ if (is_null($v) && ! $this->_has_operator($k))
+ {
+ // value appears not to have been set, assign the test to IS NULL
+ $k .= ' IS NULL';
+ }
+
+ if ( ! is_null($v))
+ {
+ if ($escape === TRUE)
+ {
+ $k = $this->protect_identifiers($k, FALSE, $escape);
+ $v = ' '.$this->escape($v);
+ }
+ elseif (is_bool($v))
+ {
+ $v = ($v ? ' TRUE' : ' FALSE');
+ }
+
+ if ( ! $this->_has_operator($k))
+ {
+ $k .= ' = ';
+ }
+ }
+ else
+ {
+ $k = $this->protect_identifiers($k, FALSE, $escape);
+ }
+
+ $this->qb_where[] = $prefix.$k.$v;
+ if ($this->qb_caching === TRUE)
+ {
+ $this->qb_cache_where[] = $prefix.$k.$v;
+ $this->qb_cache_exists[] = 'where';
+ }
+
+ }
+
+ return $this;
}
// --------------------------------------------------------------------
@@ -667,12 +660,11 @@ class CI_DB_postgre_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @pg_close($conn_id);
+ @pg_close($this->conn_id);
}
}
diff --git a/system/database/drivers/postgre/postgre_forge.php b/system/database/drivers/postgre/postgre_forge.php
index a72449820..c434e9510 100644
--- a/system/database/drivers/postgre/postgre_forge.php
+++ b/system/database/drivers/postgre/postgre_forge.php
@@ -34,31 +34,7 @@
*/
class CI_DB_postgre_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return bool
- */
- public function _create_database($name)
- {
- return "CREATE DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- return "DROP DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
+ protected $_drop_table = 'DROP TABLE IF EXISTS %s CASCADE';
/**
* Process Fields
@@ -66,7 +42,7 @@ class CI_DB_postgre_forge extends CI_DB_forge {
* @param mixed the fields
* @return string
*/
- protected function _process_fields($fields, $primary_keys=array())
+ protected function _process_fields($fields, $primary_keys = array())
{
$sql = '';
$current_field_count = 0;
@@ -78,15 +54,14 @@ class CI_DB_postgre_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
- $attributes = array_change_key_case($attributes, CASE_UPPER);
-
- $sql .= "\n\t".$this->db->protect_identifiers($field);
+ $sql .= "\n\t".$this->db->escape_identifiers($field);
- $is_unsigned = (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE);
+ $attributes = array_change_key_case($attributes, CASE_UPPER);
+ $is_unsigned = ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE);
// Convert datatypes to be PostgreSQL-compatible
switch (strtoupper($attributes['TYPE']))
@@ -118,41 +93,30 @@ class CI_DB_postgre_forge extends CI_DB_forge {
case 'BLOB':
$attributes['TYPE'] = 'BYTEA';
break;
+ default:
+ break;
}
// If this is an auto-incrementing primary key, use the serial data type instead
- if (in_array($field, $primary_keys) && array_key_exists('AUTO_INCREMENT', $attributes)
- && $attributes['AUTO_INCREMENT'] === TRUE)
- {
- $sql .= ' SERIAL';
- }
- else
- {
- $sql .= ' '.$attributes['TYPE'];
- }
+ $sql .= (in_array($field, $primary_keys) && ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
+ ? ' SERIAL' : ' '.$attributes['TYPE'];
// Modified to prevent constraints with integer data types
- if (array_key_exists('CONSTRAINT', $attributes) && strpos($attributes['TYPE'], 'INT') === false)
+ if ( ! empty($attributes['CONSTRAINT']) && strpos($attributes['TYPE'], 'INT') === FALSE)
{
$sql .= '('.$attributes['CONSTRAINT'].')';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- // Added new attribute to create unqite fields. Also works with MySQL
- if (array_key_exists('UNIQUE', $attributes) && $attributes['UNIQUE'] === TRUE)
+ // Added new attribute to create unique fields. Also works with MySQL
+ if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE)
{
$sql .= ' UNIQUE';
}
@@ -180,31 +144,21 @@ class CI_DB_postgre_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
- if ($if_not_exists === TRUE)
+ // PostgreSQL doesn't support IF NOT EXISTS syntax so we check if table exists manually
+ if ($if_not_exists === TRUE && $this->db->table_exists($table))
{
- // PostgreSQL doesn't support IF NOT EXISTS syntax so we check if table exists manually
- if ($this->db->table_exists($table))
- {
- return TRUE;
- }
+ return TRUE;
}
- $sql .= $this->db->_escape_identifiers($table)." (";
- $sql .= $this->_process_fields($fields, $primary_keys);
+ $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields, $primary_keys);
if (count($primary_keys) > 0)
{
- // Something seems to break when passing an array to protect_identifiers()
- foreach ($primary_keys as $index => $key)
- {
- $primary_keys[$index] = $this->db->protect_identifiers($key);
- }
-
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
$sql .= "\n);";
@@ -213,18 +167,14 @@ class CI_DB_postgre_forge extends CI_DB_forge {
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
foreach ($key as $field)
{
- $sql .= "CREATE INDEX " . $table . "_" . str_replace(array('"', "'"), '', $field) . "_index ON $table ($field); ";
+ $sql .= "\nCREATE INDEX ".$this->db->escape_identifiers($table.'_'.str_replace(array('"', "'"), '', $field).'_index')
+ .' ON '.$this->db->escape_identifiers($table).' ('.$this->db->escape_identifiers($field).');';
}
}
}
@@ -235,18 +185,6 @@ class CI_DB_postgre_forge extends CI_DB_forge {
// --------------------------------------------------------------------
/**
- * Drop Table
- *
- * @return string
- */
- public function _drop_table($table)
- {
- return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table)." CASCADE";
- }
-
- // --------------------------------------------------------------------
-
- /**
* Alter table query
*
* Generates a platform-specific query so that a table can be altered
@@ -257,45 +195,24 @@ class CI_DB_postgre_forge extends CI_DB_forge {
* @param string the table name
* @param string the column definition
* @param string the default value
- * @param boolean should 'NOT NULL' be added
+ * @param bool should 'NOT NULL' be added
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $fields, $after_field = '')
+ protected function _alter_table($alter_type, $table, $fields, $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' ';
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' ';
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
- {
- return $sql.$this->db->protect_identifiers($fields);
- }
-
- $sql .= $this->_process_fields($fields);
-
- if ($after_field != '')
+ if ($alter_type === 'DROP')
{
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
+ return $sql.$this->db->escape_identifiers($fields);
}
- return $sql;
+ return $sql.$this->_process_fields($fields)
+ .($after_field !== '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
- }
}
/* End of file postgre_forge.php */
diff --git a/system/database/drivers/postgre/postgre_result.php b/system/database/drivers/postgre/postgre_result.php
index 8b22564b3..f913bc9eb 100644
--- a/system/database/drivers/postgre/postgre_result.php
+++ b/system/database/drivers/postgre/postgre_result.php
@@ -70,7 +70,7 @@ class CI_DB_postgre_result extends CI_DB_result {
public function list_fields()
{
$field_names = array();
- for ($i = 0; $i < $this->num_fields(); $i++)
+ for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
$field_names[] = pg_field_name($this->result_id, $i);
}
@@ -90,16 +90,14 @@ class CI_DB_postgre_result extends CI_DB_result {
public function field_data()
{
$retval = array();
- for ($i = 0; $i < $this->num_fields(); $i++)
+ for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
- $F = new stdClass();
- $F->name = pg_field_name($this->result_id, $i);
- $F->type = pg_field_type($this->result_id, $i);
- $F->max_length = pg_field_size($this->result_id, $i);
- $F->primary_key = 0;
- $F->default = '';
-
- $retval[] = $F;
+ $retval[$i] = new stdClass();
+ $retval[$i]->name = pg_field_name($this->result_id, $i);
+ $retval[$i]->type = pg_field_type($this->result_id, $i);
+ $retval[$i]->max_length = pg_field_size($this->result_id, $i);
+ $retval[$i]->primary_key = 0;
+ $retval[$i]->default = '';
}
return $retval;
@@ -130,7 +128,7 @@ class CI_DB_postgre_result extends CI_DB_result {
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
diff --git a/system/database/drivers/postgre/postgre_utility.php b/system/database/drivers/postgre/postgre_utility.php
index cf29201ff..c95e6df0c 100644
--- a/system/database/drivers/postgre/postgre_utility.php
+++ b/system/database/drivers/postgre/postgre_utility.php
@@ -34,43 +34,8 @@
*/
class CI_DB_postgre_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return string
- */
- public function _list_databases()
- {
- return 'SELECT datname FROM pg_database';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * @param string the table name
- * @return string
- */
- public function _optimize_table($table)
- {
- return 'REINDEX TABLE '.$this->db->protect_identifiers($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = 'SELECT datname FROM pg_database';
+ protected $_optimize_table = 'REINDEX TABLE %s';
/**
* Postgre Export
@@ -78,7 +43,7 @@ class CI_DB_postgre_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/sqlite/sqlite_driver.php b/system/database/drivers/sqlite/sqlite_driver.php
index 102c79bb3..3305f6030 100644
--- a/system/database/drivers/sqlite/sqlite_driver.php
+++ b/system/database/drivers/sqlite/sqlite_driver.php
@@ -29,7 +29,7 @@
* SQLite Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -43,7 +43,7 @@ class CI_DB_sqlite_driver extends CI_DB {
public $dbdriver = 'sqlite';
// The character used to escape with - not needed for SQLite
- protected $_escape_char = '';
+ protected $_escape_char = '"';
// clause and character used for LIKE escape sequences
protected $_like_escape_str = " ESCAPE '%s' ";
@@ -106,18 +106,6 @@ class CI_DB_sqlite_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Select the database
- *
- * @return resource
- */
- public function db_select()
- {
- return TRUE;
- }
-
- // --------------------------------------------------------------------
-
- /**
* Database version number
*
* @return string
@@ -139,7 +127,9 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
protected function _execute($sql)
{
- return @sqlite_query($this->conn_id, $sql);
+ return $this->is_write_type($sql)
+ ? @sqlite_exec($this->conn_id, $sql)
+ : @sqlite_query($this->conn_id, $sql);
}
// --------------------------------------------------------------------
@@ -151,13 +141,8 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -165,7 +150,7 @@ class CI_DB_sqlite_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
+ $this->_trans_failure = ($test_mode === TRUE);
$this->simple_query('BEGIN TRANSACTION');
return TRUE;
@@ -180,13 +165,8 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -204,13 +184,8 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -280,35 +255,6 @@ class CI_DB_sqlite_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return string
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query($this->_count_string.$this->protect_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -318,12 +264,13 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
protected function _list_tables($prefix_limit = FALSE)
{
- $sql = "SELECT name from sqlite_master WHERE type='table'";
+ $sql = "SELECT name FROM sqlite_master WHERE type='table'";
- if ($prefix_limit !== FALSE AND $this->dbprefix != '')
+ if ($prefix_limit !== FALSE && $this->dbprefix != '')
{
- $sql .= " AND 'name' LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
+ return $sql." AND 'name' LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr);
}
+
return $sql;
}
@@ -355,7 +302,7 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
protected function _field_data($table)
{
- return "SELECT * FROM ".$table." LIMIT 1";
+ return 'SELECT * FROM '.$this->escape_identifiers($table).' LIMIT 1';
}
// --------------------------------------------------------------------
@@ -378,165 +325,36 @@ class CI_DB_sqlite_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- if ($this->_escape_char == '')
- {
- return $item;
- }
-
- foreach ($this->_reserved_identifiers as $id)
- {
- if (strpos($item, '.'.$id) !== FALSE)
- {
- $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item);
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
- }
-
- if (strpos($item, '.') !== FALSE)
- {
- $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char;
- }
- else
- {
- $str = $this->_escape_char.$item.$this->_escape_char;
- }
-
- // remove duplicates if the user already included the escape
- return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * From Tables
- *
- * This function implicitly groups FROM tables so there is no confusion
- * about operator precedence in harmony with SQL standards
- *
- * @param array
- * @return string
- */
- protected function _from_tables($tables)
- {
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return '('.implode(', ', $tables).')';
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
+ * Replace statement
*
- * Generates a platform-specific insert string from the supplied data
+ * Generates a platform-specific replace string from the supplied data
*
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
- protected function _insert($table, $keys, $values)
+ protected function _replace($table, $keys, $values)
{
- return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update statement
- *
- * Generates a platform-specific update string from the supplied data
- *
- * @param string the table name
- * @param array the update data
- * @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
- * @return string
- */
- protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
- {
- foreach ($values as $key => $val)
- {
- $valstr[] = $key." = ".$val;
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):'';
-
- $sql = "UPDATE ".$table." SET ".implode(', ', $valstr);
-
- $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : '';
-
- $sql .= $orderby.$limit;
-
- return $sql;
+ return 'INSERT OR '.parent::_replace($table, $keys, $values);
}
-
// --------------------------------------------------------------------
/**
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
*
- * @param string the table name
- * @return string
- */
- protected function _truncate($table)
- {
- return $this->_delete($table);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Delete statement
- *
- * Generates a platform-specific delete string from the supplied data
+ * If the database does not support the truncate() command,
+ * then this function maps to 'DELETE FROM table'
*
* @param string the table name
- * @param array the where clause
- * @param string the limit clause
* @return string
*/
- protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
+ protected function _truncate($table)
{
- $conditions = '';
-
- if (count($where) > 0 OR count($like) > 0)
- {
- $conditions = "\nWHERE ";
- $conditions .= implode("\n", $this->ar_where);
-
- if (count($where) > 0 && count($like) > 0)
- {
- $conditions .= " AND ";
- }
- $conditions .= implode("\n", $like);
- }
-
- $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;
-
- return "DELETE FROM ".$table.$conditions.$limit;
+ return 'DELETE FROM '.$table;
}
// --------------------------------------------------------------------
@@ -553,16 +371,7 @@ class CI_DB_sqlite_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- if ($offset == 0)
- {
- $offset = '';
- }
- else
- {
- $offset .= ", ";
- }
-
- return $sql."LIMIT ".$offset.$limit;
+ return $sql.'LIMIT '.($offset == 0 ? '' : $offset.', ').$limit;
}
// --------------------------------------------------------------------
@@ -570,12 +379,11 @@ class CI_DB_sqlite_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @sqlite_close($conn_id);
+ @sqlite_close($this->conn_id);
}
}
diff --git a/system/database/drivers/sqlite/sqlite_forge.php b/system/database/drivers/sqlite/sqlite_forge.php
index 068a556ed..71eed7df4 100644
--- a/system/database/drivers/sqlite/sqlite_forge.php
+++ b/system/database/drivers/sqlite/sqlite_forge.php
@@ -40,7 +40,7 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
* @param string the database name
* @return bool
*/
- public function _create_database()
+ public function create_database($db_name = '')
{
// In SQLite, a database is created when you connect to the database.
// We'll return TRUE so that an error isn't generated
@@ -52,19 +52,16 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
/**
* Drop database
*
- * @param string the database name
+ * @param string the database name (ignored)
* @return bool
*/
- public function _drop_database($name)
+ public function drop_database($db_name = '')
{
if ( ! @file_exists($this->db->database) OR ! @unlink($this->db->database))
{
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unable_to_drop');
- }
- return FALSE;
+ return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
}
+
return TRUE;
}
@@ -80,7 +77,7 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
* @param bool should 'IF NOT EXISTS' be added to the SQL
* @return bool
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
$sql = 'CREATE TABLE ';
@@ -90,51 +87,41 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
$sql .= 'IF NOT EXISTS ';
}
- $sql .= $this->db->_escape_identifiers($table)."(";
+ $sql .= $this->db->escape_identifiers($table).' (';
$current_field_count = 0;
- foreach ($fields as $field=>$attributes)
+ foreach ($fields as $field => $attributes)
{
// Numeric field names aren't allowed in databases, so if the key is
// numeric, we know it was assigned by PHP and the developer manually
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field);
-
- $sql .= ' '.$attributes['TYPE'];
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- if (array_key_exists('CONSTRAINT', $attributes))
- {
- $sql .= '('.$attributes['CONSTRAINT'].')';
- }
+ empty($attributes['CONSTRAINT']) OR $sql .= '('.$attributes['CONSTRAINT'].')';
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
+
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -149,46 +136,22 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
- $sql .= ",\n\tUNIQUE (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tUNIQUE (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return bool
- */
- public function _drop_table($table)
- {
- if ($this->db->db_debug)
- {
- return $this->db->display_error('db_unsuported_feature');
- }
- return array();
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -208,58 +171,23 @@ class CI_DB_sqlite_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name);
-
- // DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ /* SQLite only supports adding new columns and it does
+ * NOT support the AFTER statement. Each new column will
+ * be added as the last one in the table.
+ */
+ if ($alter_type !== 'ADD COLUMN')
{
- // SQLite does not support dropping columns
- // http://www.sqlite.org/omitted.html
- // http://www.sqlite.org/faq.html#q11
+ // Not supported
return FALSE;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ return 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name)
+ .' '.$column_definition
+ .($default_value != '' ? " DEFAULT '".$default_value."'" : '')
+ // If NOT NULL is specified, the field must have a DEFAULT value other than NULL
+ .(($null !== NULL && $default_value !== 'NULL') ? ' NOT NULL' : ' NULL');
}
}
diff --git a/system/database/drivers/sqlite/sqlite_result.php b/system/database/drivers/sqlite/sqlite_result.php
index b002aeff1..741dc9d8d 100644
--- a/system/database/drivers/sqlite/sqlite_result.php
+++ b/system/database/drivers/sqlite/sqlite_result.php
@@ -70,9 +70,9 @@ class CI_DB_sqlite_result extends CI_DB_result {
public function list_fields()
{
$field_names = array();
- for ($i = 0; $i < $this->num_fields(); $i++)
+ for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
- $field_names[] = sqlite_field_name($this->result_id, $i);
+ $field_names[$i] = sqlite_field_name($this->result_id, $i);
}
return $field_names;
@@ -90,16 +90,14 @@ class CI_DB_sqlite_result extends CI_DB_result {
public function field_data()
{
$retval = array();
- for ($i = 0; $i < $this->num_fields(); $i++)
+ for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
- $F = new stdClass();
- $F->name = sqlite_field_name($this->result_id, $i);
- $F->type = 'varchar';
- $F->max_length = 0;
- $F->primary_key = 0;
- $F->default = '';
-
- $retval[] = $F;
+ $retval[$i] = new stdClass();
+ $retval[$i]->name = sqlite_field_name($this->result_id, $i);
+ $retval[$i]->type = 'varchar';
+ $retval[$i]->max_length = 0;
+ $retval[$i]->primary_key = 0;
+ $retval[$i]->default = '';
}
return $retval;
@@ -108,25 +106,13 @@ class CI_DB_sqlite_result extends CI_DB_result {
// --------------------------------------------------------------------
/**
- * Free the result
- *
- * @return void
- */
- public function free_result()
- {
- // Not implemented in SQLite
- }
-
- // --------------------------------------------------------------------
-
- /**
* Data Seek
*
* Moves the internal pointer to the desired offset. We call
* this internally before fetching results to make sure the
* result set starts at zero
*
- * @return array
+ * @return bool
*/
protected function _data_seek($n = 0)
{
@@ -162,17 +148,9 @@ class CI_DB_sqlite_result extends CI_DB_result {
{
return sqlite_fetch_object($this->result_id);
}
- else
- {
- $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC);
- if (is_array($arr))
- {
- $obj = (object) $arr;
- return $obj;
- } else {
- return NULL;
- }
- }
+
+ $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC);
+ return is_array($arr) ? (object) $arr : FALSE;
}
}
diff --git a/system/database/drivers/sqlite/sqlite_utility.php b/system/database/drivers/sqlite/sqlite_utility.php
index c07004c54..1bcb42d9f 100644
--- a/system/database/drivers/sqlite/sqlite_utility.php
+++ b/system/database/drivers/sqlite/sqlite_utility.php
@@ -34,50 +34,7 @@
*/
class CI_DB_sqlite_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * I don't believe you can do a database listing with SQLite
- * since each database is its own file. I suppose we could
- * try reading a directory looking for SQLite files, but
- * that doesn't seem like a terribly good idea
- *
- * @return bool
- */
- public function _list_databases()
- {
- return ($this->db_debug) ? $this->db->display_error('db_unsuported_feature') : FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Optimize table query
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- // Not supported
- return FALSE;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- // Not supported
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = FALSE;
/**
* SQLite Export
@@ -85,7 +42,7 @@ class CI_DB_sqlite_utility extends CI_DB_utility {
* @param array Preferences
* @return mixed
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
diff --git a/system/database/drivers/sqlite3/index.html b/system/database/drivers/sqlite3/index.html
new file mode 100644
index 000000000..c942a79ce
--- /dev/null
+++ b/system/database/drivers/sqlite3/index.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+ <title>403 Forbidden</title>
+</head>
+<body>
+
+<p>Directory access is forbidden.</p>
+
+</body>
+</html> \ No newline at end of file
diff --git a/system/database/drivers/sqlite3/sqlite3_driver.php b/system/database/drivers/sqlite3/sqlite3_driver.php
new file mode 100644
index 000000000..bed61891b
--- /dev/null
+++ b/system/database/drivers/sqlite3/sqlite3_driver.php
@@ -0,0 +1,385 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 1.0
+ * @filesource
+ */
+
+/**
+ * SQLite3 Database Adapter Class
+ *
+ * Note: _DB is an extender class that the app controller
+ * creates dynamically based on whether the query builder
+ * class is being used or not.
+ *
+ * @package CodeIgniter
+ * @subpackage Drivers
+ * @category Database
+ * @author Andrey Andreev
+ * @link http://codeigniter.com/user_guide/database/
+ * @since Version 3.0
+ */
+class CI_DB_sqlite3_driver extends CI_DB {
+
+ public $dbdriver = 'sqlite3';
+
+ // The character used for escaping
+ protected $_escape_char = '"';
+
+ // clause and character used for LIKE escape sequences
+ protected $_like_escape_str = ' ESCAPE \'%s\' ';
+ protected $_like_escape_chr = '!';
+
+ /**
+ * The syntax to count rows is slightly different across different
+ * database engines, so this string appears in each driver and is
+ * used for the count_all() and count_all_results() functions.
+ */
+ protected $_count_string = 'SELECT COUNT(*) AS ';
+ protected $_random_keyword = ' RANDOM()';
+
+ /**
+ * Non-persistent database connection
+ *
+ * @return object type SQLite3
+ */
+ public function db_connect()
+ {
+ try
+ {
+ return ( ! $this->password)
+ ? new SQLite3($this->database)
+ : new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password);
+ }
+ catch (Exception $e)
+ {
+ return FALSE;
+ }
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Persistent database connection
+ *
+ * @return object type SQLite3
+ */
+ public function db_pconnect()
+ {
+ log_message('debug', 'SQLite3 doesn\'t support persistent connections');
+ return $this->db_connect();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Database version number
+ *
+ * @return string
+ */
+ public function version()
+ {
+ if (isset($this->data_cache['version']))
+ {
+ return $this->data_cache['version'];
+ }
+
+ $version = SQLite3::version();
+ return $this->data_cache['version'] = $version['versionString'];
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Execute the query
+ *
+ * @param string an SQL query
+ * @return mixed SQLite3Result object or bool
+ */
+ protected function _execute($sql)
+ {
+ // TODO: Implement use of SQLite3::querySingle(), if needed
+
+ return $this->is_write_type($sql)
+ ? $this->conn_id->exec($sql)
+ : $this->conn_id->query($sql);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Begin Transaction
+ *
+ * @return bool
+ */
+ public function trans_begin($test_mode = FALSE)
+ {
+ // When transactions are nested we only begin/commit/rollback the outermost ones
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
+ {
+ return TRUE;
+ }
+
+ // Reset the transaction failure flag.
+ // If the $test_mode flag is set to TRUE transactions will be rolled back
+ // even if the queries produce a successful result.
+ $this->_trans_failure = ($test_mode === TRUE);
+
+ return $this->conn_id->exec('BEGIN TRANSACTION');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Commit Transaction
+ *
+ * @return bool
+ */
+ public function trans_commit()
+ {
+ // When transactions are nested we only begin/commit/rollback the outermost ones
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
+ {
+ return TRUE;
+ }
+
+ return $this->conn_id->exec('END TRANSACTION');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Rollback Transaction
+ *
+ * @return bool
+ */
+ public function trans_rollback()
+ {
+ // When transactions are nested we only begin/commit/rollback the outermost ones
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
+ {
+ return TRUE;
+ }
+
+ return $this->conn_id->exec('ROLLBACK');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Escape String
+ *
+ * @param string
+ * @param bool whether or not the string will be used in a LIKE condition
+ * @return string
+ */
+ public function escape_str($str, $like = FALSE)
+ {
+ if (is_array($str))
+ {
+ foreach ($str as $key => $val)
+ {
+ $str[$key] = $this->escape_str($val, $like);
+ }
+
+ return $str;
+ }
+
+ $str = $this->conn_id->escapeString(remove_invisible_characters($str));
+
+ // escape LIKE condition wildcards
+ if ($like === TRUE)
+ {
+ return str_replace(array($this->_like_escape_chr, '%', '_'),
+ array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
+ $str);
+ }
+
+ return $str;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Affected Rows
+ *
+ * @return int
+ */
+ public function affected_rows()
+ {
+ return $this->conn_id->changes();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Insert ID
+ *
+ * @return int
+ */
+ public function insert_id()
+ {
+ return $this->conn_id->lastInsertRowID();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Show table query
+ *
+ * Generates a platform-specific query string so that the table names can be fetched
+ *
+ * @param bool
+ * @return string
+ */
+ protected function _list_tables($prefix_limit = FALSE)
+ {
+ return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
+ .(($prefix_limit !== FALSE && $this->dbprefix != '')
+ ? ' AND "NAME" LIKE \''.$this->escape_like_str($this->dbprefix).'%\' '.sprintf($this->_like_escape_str, $this->_like_escape_chr)
+ : '');
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Show column query
+ *
+ * Generates a platform-specific query string so that the column names can be fetched
+ *
+ * @param string the table name
+ * @return string
+ */
+ protected function _list_columns($table = '')
+ {
+ // Not supported
+ return FALSE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Field data query
+ *
+ * Generates a platform-specific query so that the column data can be retrieved
+ *
+ * @param string the table name
+ * @return string
+ */
+ protected function _field_data($table)
+ {
+ return 'SELECT * FROM '.$table.' LIMIT 0,1';
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * The error message string
+ *
+ * @return string
+ */
+ protected function _error_message()
+ {
+ return $this->conn_id->lastErrorMsg();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * The error message number
+ *
+ * @return int
+ */
+ protected function _error_number()
+ {
+ return $this->conn_id->lastErrorCode();
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Replace statement
+ *
+ * Generates a platform-specific replace string from the supplied data
+ *
+ * @param string the table name
+ * @param array the insert keys
+ * @param array the insert values
+ * @return string
+ */
+ protected function _replace($table, $keys, $values)
+ {
+ return 'INSERT OR '.parent::_replace($table, $keys, $values);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Truncate statement
+ *
+ * Generates a platform-specific truncate string from the supplied data
+ *
+ * If the database does not support the truncate() command, then,
+ * then this method maps to 'DELETE FROM table'
+ *
+ * @param string the table name
+ * @return string
+ */
+ protected function _truncate($table)
+ {
+ return 'DELETE FROM '.$table;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Limit string
+ *
+ * Generates a platform-specific LIMIT clause
+ *
+ * @param string the sql query string
+ * @param int the number of rows to limit the query to
+ * @param int the offset value
+ * @return string
+ */
+ protected function _limit($sql, $limit, $offset)
+ {
+ return $sql.' LIMIT '.($offset ? $offset.',' : '').$limit;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Close DB Connection
+ *
+ * @return void
+ */
+ protected function _close()
+ {
+ $this->conn_id->close();
+ }
+
+}
+
+/* End of file sqlite3_driver.php */
+/* Location: ./system/database/drivers/sqlite3/sqlite3_driver.php */ \ No newline at end of file
diff --git a/system/database/drivers/sqlite3/sqlite3_forge.php b/system/database/drivers/sqlite3/sqlite3_forge.php
new file mode 100644
index 000000000..f8bd11656
--- /dev/null
+++ b/system/database/drivers/sqlite3/sqlite3_forge.php
@@ -0,0 +1,203 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.1.6 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 1.0
+ * @filesource
+ */
+
+/**
+ * SQLite3 Forge Class
+ *
+ * @category Database
+ * @author Andrey Andreev
+ * @link http://codeigniter.com/user_guide/database/
+ */
+class CI_DB_sqlite3_forge extends CI_DB_forge {
+
+ /**
+ * Create database
+ *
+ * @param string the database name
+ * @return bool
+ */
+ public function create_database($db_name = '')
+ {
+ // In SQLite, a database is created when you connect to the database.
+ // We'll return TRUE so that an error isn't generated
+ return TRUE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Drop database
+ *
+ * @param string the database name (ignored)
+ * @return bool
+ */
+ public function drop_database($db_name = '')
+ {
+ // In SQLite, a database is dropped when we delete a file
+ if (@file_exists($this->db->database))
+ {
+ // We need to close the pseudo-connection first
+ $this->db->close();
+ if ( ! @unlink($this->db->database))
+ {
+ return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE;
+ }
+
+ return TRUE;
+ }
+
+ return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Create Table
+ *
+ * @param string the table name
+ * @param array the fields
+ * @param mixed primary key(s)
+ * @param mixed key(s)
+ * @param bool should 'IF NOT EXISTS' be added to the SQL
+ * @return bool
+ */
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ {
+ $sql = 'CREATE TABLE ';
+
+ // IF NOT EXISTS added to SQLite in 3.3.0
+ if ($if_not_exists === TRUE && version_compare($this->db->version(), '3.3.0', '>=') === TRUE)
+ {
+ $sql .= 'IF NOT EXISTS ';
+ }
+
+ $sql .= $this->db->escape_identifiers($table).' (';
+ $current_field_count = 0;
+
+ foreach ($fields as $field => $attributes)
+ {
+ // Numeric field names aren't allowed in databases, so if the key is
+ // numeric, we know it was assigned by PHP and the developer manually
+ // entered the field information, so we'll simply add it to the list
+ if (is_numeric($field))
+ {
+ $sql .= "\n\t".$attributes;
+ }
+ else
+ {
+ $attributes = array_change_key_case($attributes, CASE_UPPER);
+
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
+
+ empty($attributes['CONSTRAINT']) OR $sql .= '('.$attributes['CONSTRAINT'].')';
+
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
+ {
+ $sql .= ' UNSIGNED';
+ }
+
+ if (isset($attributes['DEFAULT']))
+ {
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
+ }
+
+ $sql .= ( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
+
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
+ {
+ $sql .= ' AUTO_INCREMENT';
+ }
+ }
+
+ // don't add a comma on the end of the last field
+ if (++$current_field_count < count($fields))
+ {
+ $sql .= ',';
+ }
+ }
+
+ if (count($primary_keys) > 0)
+ {
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
+ }
+
+ if (is_array($keys) && count($keys) > 0)
+ {
+ foreach ($keys as $key)
+ {
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->db->escape_identifiers($key));
+
+ $sql .= ",\n\tUNIQUE (".implode(', ', $key).')';
+ }
+ }
+
+ return $sql."\n)";
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Alter table query
+ *
+ * Generates a platform-specific query so that a table can be altered
+ * Called by add_column(), drop_column(), and column_alter(),
+ *
+ * @param string the ALTER type (ADD, DROP, CHANGE)
+ * @param string the column name
+ * @param string the table name
+ * @param string the column definition
+ * @param string the default value
+ * @param bool should 'NOT NULL' be added
+ * @param string the field after which we should add the new field
+ * @return string
+ */
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ {
+ /* SQLite only supports adding new columns and it does
+ * NOT support the AFTER statement. Each new column will
+ * be added as the last one in the table.
+ */
+ if ($alter_type !== 'ADD COLUMN')
+ {
+ // Not supported
+ return FALSE;
+ }
+
+ return 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name)
+ .' '.$column_definition
+ .($default_value !== '' ? ' DEFAULT '.$default_value : '')
+ // If NOT NULL is specified, the field must have a DEFAULT value other than NULL
+ .(($null !== NULL && $default_value !== 'NULL') ? ' NOT NULL' : ' NULL');
+ }
+
+}
+
+/* End of file sqlite3_forge.php */
+/* Location: ./system/database/drivers/sqlite3/sqlite3_forge.php */ \ No newline at end of file
diff --git a/system/database/drivers/sqlite3/sqlite3_result.php b/system/database/drivers/sqlite3/sqlite3_result.php
new file mode 100644
index 000000000..946b36557
--- /dev/null
+++ b/system/database/drivers/sqlite3/sqlite3_result.php
@@ -0,0 +1,615 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.1.6 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 1.0
+ * @filesource
+ */
+
+/**
+ * SQLite Result Class
+ *
+ * This class extends the parent result class: CI_DB_result
+ *
+ * @category Database
+ * @author Andrey Andreev
+ * @link http://codeigniter.com/user_guide/database/
+ */
+class CI_DB_sqlite3_result extends CI_DB_result {
+
+ // Overwriting the parent here, so we have a way to know if it's already set
+ public $num_rows;
+
+ // num_fields() might be called multiple times, so we'll use this one to cache it's result
+ protected $_num_fields;
+
+ /**
+ * Number of rows in the result set
+ *
+ * @return int
+ */
+ public function num_rows()
+ {
+ /* The SQLite3 driver doesn't have a graceful way to do this,
+ * so we'll have to do it on our own.
+ */
+ return is_int($this->num_rows)
+ ? $this->num_rows
+ : $this->num_rows = count($this->result_array());
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Number of fields in the result set
+ *
+ * @return int
+ */
+ public function num_fields()
+ {
+ return ( ! is_int($this->_num_fields))
+ ? $this->_num_fields = $this->result_id->numColumns()
+ : $this->_num_fields;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Fetch Field Names
+ *
+ * Generates an array of column names
+ *
+ * @return array
+ */
+ public function list_fields()
+ {
+ $field_names = array();
+ for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
+ {
+ $field_names[] = $this->result_id->columnName($i);
+ }
+
+ return $field_names;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Field data
+ *
+ * Generates an array of objects containing field meta-data
+ *
+ * @return array
+ */
+ public function field_data()
+ {
+ $retval = array();
+ for ($i = 0, $c = $this->num_fields(); $i < $this->num_fields(); $i++)
+ {
+ $retval[$i] = new stdClass();
+ $retval[$i]->name = $this->result_id->columnName($i);
+ $retval[$i]->type = 'varchar';
+ $retval[$i]->max_length = 0;
+ $retval[$i]->primary_key = 0;
+ $retval[$i]->default = '';
+ }
+
+ return $retval;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Free the result
+ *
+ * @return void
+ */
+ public function free_result()
+ {
+ if (is_object($this->result_id))
+ {
+ $this->result_id->finalize();
+ $this->result_id = NULL;
+ }
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Result - associative array
+ *
+ * Returns the result set as an array
+ *
+ * @return array
+ */
+ protected function _fetch_assoc()
+ {
+ return $this->result_id->fetchArray(SQLITE3_ASSOC);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Result - object
+ *
+ * Returns the result set as an object
+ *
+ * @return object
+ */
+ protected function _fetch_object()
+ {
+ // No native support for fetching as an object
+ $row = $this->_fetch_assoc();
+ return ($row !== FALSE) ? (object) $row : FALSE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Query result. "array" version.
+ *
+ * return array
+ */
+ public function result_array()
+ {
+ if (count($this->result_array) > 0)
+ {
+ return $this->result_array;
+ }
+ elseif (is_array($this->row_data))
+ {
+ if (count($this->row_data) === 0)
+ {
+ return $this->result_array;
+ }
+ else
+ {
+ $row_index = count($this->row_data);
+ }
+ }
+ else
+ {
+ $row_index = 0;
+ $this->row_data = array();
+ }
+
+ $row = NULL;
+ while ($row = $this->_fetch_assoc())
+ {
+ $this->row_data[$row_index++] = $row;
+ }
+
+ return $this->result_array = $this->row_data;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Query result. "object" version.
+ *
+ * @return array
+ */
+ public function result_object()
+ {
+ if (count($this->result_object) > 0)
+ {
+ return $this->result_object;
+ }
+ elseif (count($this->result_array) > 0)
+ {
+ for ($i = 0, $c = count($this->result_array); $i < $c; $i++)
+ {
+ $this->result_object[] = (object) $this->result_array[$i];
+ }
+
+ return $this->result_object;
+ }
+ elseif (is_array($this->row_data))
+ {
+ if (count($this->row_data) === 0)
+ {
+ return $this->result_object;
+ }
+ else
+ {
+ $row_index = count($this->row_data);
+ for ($i = 0; $i < $row_index; $i++)
+ {
+ $this->result_object[$i] = (object) $this->row_data[$i];
+ }
+ }
+ }
+ else
+ {
+ $row_index = 0;
+ $this->row_data = array();
+ }
+
+ $row = NULL;
+ while ($row = $this->_fetch_assoc())
+ {
+ $this->row_data[$row_index] = $row;
+ $this->result_object[$row_index++] = (object) $row;
+ }
+
+ $this->result_array = $this->row_data;
+
+ /* As described for the num_rows() method - there's no easy
+ * way to get the number of rows selected. Our work-around
+ * solution (as in here as well) first checks if result_array
+ * exists and returns its count. It doesn't however check for
+ * custom_object_result, so - do it here.
+ */
+ if ( ! is_int($this->num_rows))
+ {
+ $this->num_rows = count($this->result_object);
+ }
+
+ return $this->result_object;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Query result. Custom object version.
+ *
+ * @param string class name used to instantiate rows to
+ * @return array
+ */
+ public function custom_result_object($class_name)
+ {
+ if (array_key_exists($class_name, $this->custom_result_object))
+ {
+ return $this->custom_result_object[$class_name];
+ }
+
+ if ( ! class_exists($class_name) OR ! is_object($this->result_id) OR $this->num_rows() === 0)
+ {
+ return array();
+ }
+
+ /* Even if result_array hasn't been set prior to custom_result_object being called,
+ * num_rows() has done it.
+ */
+ $data = &$this->result_array;
+
+ $result_object = array();
+ for ($i = 0, $c = count($data); $i < $c; $i++)
+ {
+ $result_object[$i] = new $class_name();
+ foreach ($data[$i] as $key => $value)
+ {
+ $result_object[$i]->$key = $value;
+ }
+ }
+
+ /* As described for the num_rows() method - there's no easy
+ * way to get the number of rows selected. Our work-around
+ * solution (as in here as well) first checks if result_array
+ * exists and returns its count. It doesn't however check for
+ * custom_object_result, so - do it here.
+ */
+ if ( ! is_int($this->num_rows))
+ {
+ $this->num_rows = count($result_object);
+ }
+
+ // Cache and return the array
+ return $this->custom_result_object[$class_name] = $result_object;
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result.
+ *
+ * Acts as a wrapper for row_object(), row_array()
+ * and custom_row_object(). Also used by first_row(), next_row()
+ * and previous_row().
+ *
+ * @param int row index
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function row($n = 0, $type = 'object')
+ {
+ if ($type === 'object')
+ {
+ return $this->row_object($n);
+ }
+ elseif ($type === 'array')
+ {
+ return $this->row_array($n);
+ }
+
+ return $this->custom_row_object($n, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Array version.
+ *
+ * @param int row index
+ * @return array
+ */
+ public function row_array($n = 0)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+
+ /* If row_data is initialized, it means that we've already tried
+ * (at least) to fetch some data, so ... check if we already have
+ * this row.
+ */
+ if (is_array($this->row_data))
+ {
+ /* If we already have row_data[$n] - return it.
+ *
+ * If we enter the elseif, there's a number of reasons to
+ * return an empty array:
+ *
+ * - count($this->row_data) === 0 means there are no results
+ * - num_rows being set or result_array having count() > 0 means
+ * that we've already fetched all data and $n is greater than
+ * our highest row index available
+ * - $n < $this->current_row means that if such row existed,
+ * we would've already returned it, therefore $n is an
+ * invalid index
+ */
+ if (isset($this->row_data[$n])) // We already have this row
+ {
+ $this->current_row = $n;
+ return $this->row_data[$n];
+ }
+ elseif (count($this->row_data) === 0 OR is_int($this->num_rows)
+ OR count($this->result_array) > 0 OR $n < $this->current_row)
+ {
+ // No such row exists
+ return NULL;
+ }
+
+ // Get the next row index that would actually need to be fetched
+ $current_row = ($this->current_row < count($this->row_data)) ? count($this->row_data) : $this->current_row + 1;
+ }
+ else
+ {
+ $current_row = $this->current_row = 0;
+ $this->row_data = array();
+ }
+
+ /* Fetch more data, if available
+ *
+ * NOTE: Operator precedence is important here, if you change
+ * 'AND' with '&&' - it WILL BREAK the results, as
+ * $row will be assigned the scalar value of both
+ * expressions!
+ */
+ while ($row = $this->_fetch_assoc() AND $current_row <= $n)
+ {
+ $this->row_data[$current_row++] = $row;
+ }
+
+ // This would mean that there's no (more) data to fetch
+ if ( ! is_array($this->row_data) OR ! isset($this->row_data[$n]))
+ {
+ // Cache what we already have
+ if (is_array($this->row_data))
+ {
+ $this->num_rows = count($this->row_data);
+ /* Usually, row_data could have less elements than result_array,
+ * but at this point - they should be exactly the same.
+ */
+ $this->result_array = $this->row_data;
+ }
+ else
+ {
+ $this->num_rows = 0;
+ }
+
+ return NULL;
+ }
+
+ $this->current_row = $n;
+ return $this->row_data[$n];
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Object version.
+ *
+ * @param int row index
+ * @return mixed object if row found; empty array if not
+ */
+ public function row_object($n = 0)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+
+ /* Logic here is exactly the same as in row_array,
+ * except we have to cast row_data[$n] to an object.
+ *
+ * If we already have result_object though - we can
+ * directly return from it.
+ */
+ if (isset($this->result_object[$n]))
+ {
+ $this->current_row = $n;
+ return $this->result_object[$n];
+ }
+
+ $row = $this->row_array($n);
+ // Cast only if the row exists
+ if (count($row) > 0)
+ {
+ $this->current_row = $n;
+ return (object) $row;
+ }
+
+ return NULL;
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Single row result. Custom object version.
+ *
+ * @param int row index
+ * @param string custom class name
+ * @return mixed custom object if row found; empty array otherwise
+ */
+ public function custom_row_object($n = 0, $class_name)
+ {
+ // Make sure $n is not a string
+ if ( ! is_int($n))
+ {
+ $n = (int) $n;
+ }
+
+ if (array_key_exists($class_name, $this->custom_result_object))
+ {
+ /* We already have a the whole result set with this class_name,
+ * return the specified row if it exists, and an empty array if
+ * it doesn't.
+ */
+ if (isset($this->custom_result_object[$class_name][$n]))
+ {
+ $this->current_row = $n;
+ return $this->custom_result_object[$class_name][$n];
+ }
+ else
+ {
+ return NULL;
+ }
+ }
+ elseif ( ! class_exists($class_name)) // No such class exists
+ {
+ return NULL;
+ }
+
+ $row = $this->row_array($n);
+ // A non-array would mean that the row doesn't exist
+ if ( ! is_array($row))
+ {
+ return NULL;
+ }
+
+ // Convert to the desired class and return
+ $row_object = new $class_name();
+ foreach ($row as $key => $value)
+ {
+ $row_object->$key = $value;
+ }
+
+ $this->current_row = $n;
+ return $row_object;
+ }
+
+ // --------------------------------------------------------------------
+
+ /* First row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function first_row($type = 'object')
+ {
+ return $this->row(0, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Last row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function last_row($type = 'object')
+ {
+ $result = &$this->result($type);
+ if ( ! isset($this->num_rows))
+ {
+ $this->num_rows = count($result);
+ }
+ $this->current_row = $this->num_rows - 1;
+ return $result[$this->current_row];
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Next row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function next_row($type = 'object')
+ {
+ if (is_array($this->row_data))
+ {
+ $count = count($this->row_data);
+ $n = ($this->current_row > $count OR ($this->current_row === 0 && $count === 0)) ? $count : $this->current_row + 1;
+ }
+ else
+ {
+ $n = 0;
+ }
+
+ return $this->row($n, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /* Previous row result.
+ *
+ * @param string ('object', 'array' or a custom class name)
+ * @return mixed whatever was passed to the second parameter
+ */
+ public function previous_row($type = 'object')
+ {
+ $n = ($this->current_row !== 0) ? $this->current_row - 1 : 0;
+ return $this->row($n, $type);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Data Seek
+ *
+ * Moves the internal pointer to the desired offset. We call
+ * this internally before fetching results to make sure the
+ * result set starts at zero
+ *
+ * @return array
+ */
+ protected function _data_seek($n = 0)
+ {
+ // Only resetting to the start of the result set is supported
+ return $this->result_id->reset();
+ }
+
+}
+
+/* End of file sqlite3_result.php */
+/* Location: ./system/database/drivers/sqlite3/sqlite3_result.php */ \ No newline at end of file
diff --git a/system/database/drivers/sqlite3/sqlite3_utility.php b/system/database/drivers/sqlite3/sqlite3_utility.php
new file mode 100644
index 000000000..965c838e5
--- /dev/null
+++ b/system/database/drivers/sqlite3/sqlite3_utility.php
@@ -0,0 +1,54 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.1.6 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 1.0
+ * @filesource
+ */
+
+/**
+ * SQLite3 Utility Class
+ *
+ * @category Database
+ * @author Andrey Andreev
+ * @link http://codeigniter.com/user_guide/database/
+ */
+class CI_DB_sqlite3_utility extends CI_DB_utility {
+
+ protected $_list_databases = FALSE;
+
+ /**
+ * SQLite Export
+ *
+ * @param array Preferences
+ * @return mixed
+ */
+ protected function _backup($params = array())
+ {
+ // Not supported
+ return $this->db->display_error('db_unsuported_feature');
+ }
+
+}
+
+/* End of file sqlite3_utility.php */
+/* Location: ./system/database/drivers/sqlite3/sqlite3_utility.php */ \ No newline at end of file
diff --git a/system/database/drivers/sqlsrv/sqlsrv_driver.php b/system/database/drivers/sqlsrv/sqlsrv_driver.php
index 9f2f88699..655a9e90b 100644
--- a/system/database/drivers/sqlsrv/sqlsrv_driver.php
+++ b/system/database/drivers/sqlsrv/sqlsrv_driver.php
@@ -29,7 +29,7 @@
* SQLSRV Database Adapter Class
*
* Note: _DB is an extender class that the app controller
- * creates dynamically based on whether the active record
+ * creates dynamically based on whether the query builder
* class is being used or not.
*
* @package CodeIgniter
@@ -43,7 +43,7 @@ class CI_DB_sqlsrv_driver extends CI_DB {
public $dbdriver = 'sqlsrv';
// The character used for escaping
- protected $_escape_char = '';
+ protected $_escape_char = '"';
// clause and character used for LIKE escape sequences
protected $_like_escape_str = " ESCAPE '%s' ";
@@ -55,7 +55,10 @@ class CI_DB_sqlsrv_driver extends CI_DB {
* used for the count_all() and count_all_results() functions.
*/
protected $_count_string = 'SELECT COUNT(*) AS ';
- protected $_random_keyword = ' ASC'; // not currently supported
+ protected $_random_keyword = ' NEWID()';
+
+ // SQLSRV-specific properties
+ protected $_quoted_identifier = TRUE;
/**
* Non-persistent database connection
@@ -68,12 +71,12 @@ class CI_DB_sqlsrv_driver extends CI_DB {
$character_set = (0 === strcasecmp('utf8', $this->char_set)) ? 'UTF-8' : $this->char_set;
$connection = array(
- 'UID' => empty($this->username) ? '' : $this->username,
- 'PWD' => empty($this->password) ? '' : $this->password,
- 'Database' => $this->database,
- 'ConnectionPooling' => $pooling ? 1 : 0,
+ 'UID' => empty($this->username) ? '' : $this->username,
+ 'PWD' => empty($this->password) ? '' : $this->password,
+ 'Database' => $this->database,
+ 'ConnectionPooling' => $pooling ? 1 : 0,
'CharacterSet' => $character_set,
- 'ReturnDatesAsStrings' => 1
+ 'ReturnDatesAsStrings' => 1
);
// If the username and password are both empty, assume this is a
@@ -83,7 +86,15 @@ class CI_DB_sqlsrv_driver extends CI_DB {
unset($connection['UID'], $connection['PWD']);
}
- return sqlsrv_connect($this->hostname, $connection);
+ $conn_id = sqlsrv_connect($this->hostname, $connection);
+
+ // Determine how identifiers are escaped
+ $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
+ $query = $query->row_array();
+ $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query->qi;
+ $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
+
+ return $conn_id;
}
// --------------------------------------------------------------------
@@ -132,11 +143,9 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
protected function _execute($sql)
{
- return sqlsrv_query($this->conn_id,
- $sql,
- NULL,
- array('Scrollable'=> SQLSRV_CURSOR_STATIC, 'SendStreamParamsAtExec' => TRUE)
- );
+ return (is_write_type($sql) && stripos($sql, 'INSERT') === FALSE)
+ ? sqlsrv_query($this->conn_id, $sql)
+ : sqlsrv_query($this->conn_id, $sql, NULL, array('Scrollable' => SQLSRV_CURSOR_STATIC));
}
// --------------------------------------------------------------------
@@ -148,13 +157,8 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
public function trans_begin($test_mode = FALSE)
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -162,7 +166,7 @@ class CI_DB_sqlsrv_driver extends CI_DB {
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
- $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE;
+ $this->_trans_failure = ($test_mode === TRUE);
return sqlsrv_begin_transaction($this->conn_id);
}
@@ -176,13 +180,8 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
public function trans_commit()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -199,13 +198,8 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
public function trans_rollback()
{
- if ( ! $this->trans_enabled)
- {
- return TRUE;
- }
-
// When transactions are nested we only begin/commit/rollback the outermost ones
- if ($this->_trans_depth > 0)
+ if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
{
return TRUE;
}
@@ -237,7 +231,7 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
public function affected_rows()
{
- return @sqlrv_rows_affected($this->conn_id);
+ return sqlrv_rows_affected($this->result_id);
}
// --------------------------------------------------------------------
@@ -259,23 +253,6 @@ class CI_DB_sqlsrv_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Parse major version
- *
- * Grabs the major version number from the
- * database server version string passed in.
- *
- * @param string $version
- * @return int major version number
- */
- protected function _parse_major_version($version)
- {
- preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $version, $ver_info);
- return $ver_info[1]; // return the major version b/c that's all we're interested in.
- }
-
- // --------------------------------------------------------------------
-
- /**
* Database version number
*
* @return string
@@ -298,35 +275,6 @@ class CI_DB_sqlsrv_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * "Count All" query
- *
- * Generates a platform-specific query string that counts all records in
- * the specified database
- *
- * @param string
- * @return int
- */
- public function count_all($table = '')
- {
- if ($table == '')
- {
- return 0;
- }
-
- $query = $this->query("SELECT COUNT(*) AS numrows FROM " . $this->dbprefix . $table);
- if ($query->num_rows() == 0)
- {
- return 0;
- }
-
- $row = $query->row();
- $this->_reset_select();
- return (int) $row->numrows;
- }
-
- // --------------------------------------------------------------------
-
- /**
* List table query
*
* Generates a platform-specific query string so that the table names can be fetched
@@ -410,21 +358,6 @@ class CI_DB_sqlsrv_driver extends CI_DB {
// --------------------------------------------------------------------
/**
- * Escape the SQL Identifiers
- *
- * This function escapes column and table names
- *
- * @param string
- * @return string
- */
- public function _escape_identifiers($item)
- {
- return $item;
- }
-
- // --------------------------------------------------------------------
-
- /**
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
@@ -435,29 +368,7 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
protected function _from_tables($tables)
{
- if ( ! is_array($tables))
- {
- $tables = array($tables);
- }
-
- return implode(', ', $tables);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Insert statement
- *
- * Generates a platform-specific insert string from the supplied data
- *
- * @param string the table name
- * @param array the insert keys
- * @param array the insert values
- * @return string
- */
- protected function _insert($table, $keys, $values)
- {
- return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
+ return is_array($tables) ? implode(', ', $tables) : $tables;
}
// --------------------------------------------------------------------
@@ -470,18 +381,26 @@ class CI_DB_sqlsrv_driver extends CI_DB {
* @param string the table name
* @param array the update data
* @param array the where clause
- * @param array the orderby clause
- * @param array the limit clause
+ * @param array the orderby clause (ignored)
+ * @param array the limit clause (ignored)
+ * @param array the like clause
* @return string
*/
- protected function _update($table, $values, $where)
+ protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE, $like = array())
{
- foreach($values as $key => $val)
+ foreach ($values as $key => $val)
+ {
+ $valstr[] = $key.' = '.$val;
+ }
+
+ $where = empty($where) ? '' : ' WHERE '.implode(' ', $where);
+
+ if ( ! empty($like))
{
- $valstr[] = $key." = ".$val;
+ $where .= ($where === '' ? ' WHERE ' : ' AND ').implode(' ', $like);
}
- return 'UPDATE '.$table.' SET '.implode(', ', $valstr).' WHERE '.implode(' ', $where);
+ return 'UPDATE '.$table.' SET '.implode(', ', $valstr).$where;
}
// --------------------------------------------------------------------
@@ -490,15 +409,16 @@ class CI_DB_sqlsrv_driver extends CI_DB {
* Truncate statement
*
* Generates a platform-specific truncate string from the supplied data
- * If the database does not support the truncate() command
- * This function maps to "DELETE FROM table"
+ *
+ * If the database does not support the truncate() command,
+ * then this method maps to 'DELETE FROM table'
*
* @param string the table name
* @return string
*/
protected function _truncate($table)
{
- return "TRUNCATE ".$table;
+ return 'TRUNCATE TABLE '.$table;
}
// --------------------------------------------------------------------
@@ -510,12 +430,22 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*
* @param string the table name
* @param array the where clause
+ * @param array the like clause
* @param string the limit clause
* @return string
*/
- protected function _delete($table, $where)
+ protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
- return 'DELETE FROM '.$table.' WHERE '.implode(' ', $where);
+ $conditions = array();
+
+ empty($where) OR $conditions[] = implode(' ', $where);
+ empty($like) OR $conditions[] = implode(' ', $like);
+
+ $conditions = (count($conditions) > 0) ? ' WHERE '.implode(' AND ', $conditions) : '';
+
+ return ($limit)
+ ? 'WITH ci_delete AS (SELECT TOP '.$limit.' * FROM '.$table.$conditions.') DELETE FROM ci_delete'
+ : 'DELETE FROM '.$table.$conditions;
}
// --------------------------------------------------------------------
@@ -532,7 +462,10 @@ class CI_DB_sqlsrv_driver extends CI_DB {
*/
protected function _limit($sql, $limit, $offset)
{
- return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.($limit + $offset).' ', $sql);
+ // As of SQL Server 2012 (11.0.*) OFFSET is supported
+ return version_compare($this->version(), '11', '>=')
+ ? $sql.' OFFSET '.(int) $offset.' ROWS FETCH NEXT '.(int) $limit.' ROWS ONLY'
+ : preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.($limit + $offset).' ', $sql);
}
// --------------------------------------------------------------------
@@ -540,12 +473,11 @@ class CI_DB_sqlsrv_driver extends CI_DB {
/**
* Close DB Connection
*
- * @param resource
* @return void
*/
- protected function _close($conn_id)
+ protected function _close()
{
- @sqlsrv_close($conn_id);
+ @sqlsrv_close($this->conn_id);
}
}
diff --git a/system/database/drivers/sqlsrv/sqlsrv_forge.php b/system/database/drivers/sqlsrv/sqlsrv_forge.php
index 0dc7b5242..e6f7e1ac1 100644
--- a/system/database/drivers/sqlsrv/sqlsrv_forge.php
+++ b/system/database/drivers/sqlsrv/sqlsrv_forge.php
@@ -34,43 +34,7 @@
*/
class CI_DB_sqlsrv_forge extends CI_DB_forge {
- /**
- * Create database
- *
- * @param string the database name
- * @return string
- */
- public function _create_database($name)
- {
- return "CREATE DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop database
- *
- * @param string the database name
- * @return bool
- */
- public function _drop_database($name)
- {
- return "DROP DATABASE ".$name;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Drop Table
- *
- * @return bool
- */
- public function _drop_table($table)
- {
- return "DROP TABLE ".$this->db->_escape_identifiers($table);
- }
-
- // --------------------------------------------------------------------
+ protected $_drop_table = 'DROP TABLE %s';
/**
* Create Table
@@ -80,20 +44,17 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge {
* @param mixed primary key(s)
* @param mixed key(s)
* @param bool should 'IF NOT EXISTS' be added to the SQL
- * @return bool
+ * @return string
*/
- public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
+ protected function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists)
{
- $sql = 'CREATE TABLE ';
+ $sql = ($if_not_exists === TRUE)
+ ? "IF NOT EXISTS (SELECT * FROM sysobjects WHERE ID = object_id(N'".$table."') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)\n"
+ : '';
- if ($if_not_exists === TRUE)
- {
- $sql .= 'IF NOT EXISTS ';
- }
+ $sql .= 'CREATE TABLE '.$this->db->escape_identifiers($table).' (';
- $sql .= $this->db->_escape_identifiers($table)." (";
$current_field_count = 0;
-
foreach ($fields as $field => $attributes)
{
// Numeric field names aren't allowed in databases, so if the key is
@@ -101,41 +62,33 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge {
// entered the field information, so we'll simply add it to the list
if (is_numeric($field))
{
- $sql .= "\n\t$attributes";
+ $sql .= "\n\t".$attributes;
}
else
{
$attributes = array_change_key_case($attributes, CASE_UPPER);
- $sql .= "\n\t".$this->db->protect_identifiers($field);
+ $sql .= "\n\t".$this->db->escape_identifiers($field).' '.$attributes['TYPE'];
- $sql .= ' '.$attributes['TYPE'];
-
- if (array_key_exists('CONSTRAINT', $attributes))
+ if (stripos($attributes['TYPE'], 'INT') === FALSE && ! empty($attributes['CONSTRAINT']))
{
$sql .= '('.$attributes['CONSTRAINT'].')';
}
- if (array_key_exists('UNSIGNED', $attributes) && $attributes['UNSIGNED'] === TRUE)
+ if ( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE)
{
$sql .= ' UNSIGNED';
}
- if (array_key_exists('DEFAULT', $attributes))
+ if (isset($attributes['DEFAULT']))
{
- $sql .= ' DEFAULT \''.$attributes['DEFAULT'].'\'';
+ $sql .= " DEFAULT '".$attributes['DEFAULT']."'";
}
- if (array_key_exists('NULL', $attributes) && $attributes['NULL'] === TRUE)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
+ $sql .= ( ! empty($attributes['NULL']) && $attribues['NULL'] === TRUE)
+ ? ' NULL' : ' NOT NULL';
- if (array_key_exists('AUTO_INCREMENT', $attributes) && $attributes['AUTO_INCREMENT'] === TRUE)
+ if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE)
{
$sql .= ' AUTO_INCREMENT';
}
@@ -150,30 +103,22 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge {
if (count($primary_keys) > 0)
{
- $primary_keys = $this->db->protect_identifiers($primary_keys);
- $sql .= ",\n\tPRIMARY KEY (" . implode(', ', $primary_keys) . ")";
+ $sql .= ",\n\tPRIMARY KEY (".implode(', ', $this->db->escape_identifiers($primary_keys)).')';
}
if (is_array($keys) && count($keys) > 0)
{
foreach ($keys as $key)
{
- if (is_array($key))
- {
- $key = $this->db->protect_identifiers($key);
- }
- else
- {
- $key = array($this->db->protect_identifiers($key));
- }
+ $key = is_array($key)
+ ? $this->db->escape_identifiers($key)
+ : array($this->escape_identifiers($key));
- $sql .= ",\n\tFOREIGN KEY (" . implode(', ', $key) . ")";
+ $sql .= ",\n\tFOREIGN KEY (".implode(', ', $key).')';
}
}
- $sql .= "\n)";
-
- return $sql;
+ return $sql."\n)";
}
// --------------------------------------------------------------------
@@ -193,56 +138,20 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge {
* @param string the field after which we should add the new field
* @return string
*/
- public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
+ protected function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '')
{
- $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name);
+ $sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' '.$alter_type.' '.$this->db->escape_identifiers($column_name);
// DROP has everything it needs now.
- if ($alter_type == 'DROP')
+ if ($alter_type === 'DROP')
{
return $sql;
}
- $sql .= " $column_definition";
-
- if ($default_value != '')
- {
- $sql .= " DEFAULT \"$default_value\"";
- }
-
- if ($null === NULL)
- {
- $sql .= ' NULL';
- }
- else
- {
- $sql .= ' NOT NULL';
- }
-
- if ($after_field != '')
- {
- return $sql.' AFTER '.$this->db->protect_identifiers($after_field);
- }
-
- return $sql;
-
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Rename a table
- *
- * Generates a platform-specific query so that a table can be renamed
- *
- * @param string the old table name
- * @param string the new table name
- * @return string
- */
- public function _rename_table($table_name, $new_table_name)
- {
- // I think this syntax will work, but can find little documentation on renaming tables in MSSQL
- return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name);
+ return $sql.' '.$column_definition
+ .($default_value != '' ? ' DEFAULT "'.$default_value.'"' : '')
+ .($null === NULL ? ' NULL' : ' NOT NULL')
+ .($after_field != '' ? ' AFTER '.$this->db->escape_identifiers($after_field) : '');
}
}
diff --git a/system/database/drivers/sqlsrv/sqlsrv_result.php b/system/database/drivers/sqlsrv/sqlsrv_result.php
index 10d790e4b..f802383d2 100644
--- a/system/database/drivers/sqlsrv/sqlsrv_result.php
+++ b/system/database/drivers/sqlsrv/sqlsrv_result.php
@@ -92,12 +92,12 @@ class CI_DB_sqlsrv_result extends CI_DB_result {
$retval = array();
foreach (sqlsrv_field_metadata($this->result_id) as $offset => $field)
{
- $F = new stdClass();
- $F->name = $field['Name'];
- $F->type = $field['Type'];
+ $F = new stdClass();
+ $F->name = $field['Name'];
+ $F->type = $field['Type'];
$F->max_length = $field['Size'];
$F->primary_key = 0;
- $F->default = '';
+ $F->default = '';
$retval[] = $F;
}
@@ -124,22 +124,6 @@ class CI_DB_sqlsrv_result extends CI_DB_result {
// --------------------------------------------------------------------
/**
- * Data Seek
- *
- * Moves the internal pointer to the desired offset. We call
- * this internally before fetching results to make sure the
- * result set starts at zero
- *
- * @return void
- */
- protected function _data_seek($n = 0)
- {
- // Not implemented
- }
-
- // --------------------------------------------------------------------
-
- /**
* Result - associative array
*
* Returns the result set as an array
diff --git a/system/database/drivers/sqlsrv/sqlsrv_utility.php b/system/database/drivers/sqlsrv/sqlsrv_utility.php
index 5830c62de..5a71b1628 100644
--- a/system/database/drivers/sqlsrv/sqlsrv_utility.php
+++ b/system/database/drivers/sqlsrv/sqlsrv_utility.php
@@ -34,55 +34,16 @@
*/
class CI_DB_sqlsrv_utility extends CI_DB_utility {
- /**
- * List databases
- *
- * @return string
- */
- public function _list_databases()
- {
- return "EXEC sp_helpdb"; // Can also be: EXEC sp_databases
- }
-
- // --------------------------------------------------------------------
+ protected $_list_databases = 'EXEC sp_helpdb'; // Can also be: EXEC sp_databases
+ protected $_optimize_table = 'ALTER INDEX all ON %s REORGANIZE';
/**
- * Optimize table query
- *
- * Generates a platform-specific query so that a table can be optimized
- *
- * @param string the table name
- * @return bool
- */
- public function _optimize_table($table)
- {
- return FALSE; // Is this supported in MS SQL?
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Repair table query
- *
- * Generates a platform-specific query so that a table can be repaired
- *
- * @param string the table name
- * @return bool
- */
- public function _repair_table($table)
- {
- return FALSE; // Is this supported in MS SQL?
- }
-
- // --------------------------------------------------------------------
-
- /**
- * MSSQL Export
+ * SQLSRV Export
*
* @param array Preferences
- * @return mixed
+ * @return bool
*/
- public function _backup($params = array())
+ protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');