From 90cfbf5ce698c15f588b7264a04057eb7380b124 Mon Sep 17 00:00:00 2001 From: Natan Felles Date: Sat, 10 Nov 2018 01:11:55 -0200 Subject: [PATCH 1/2] Simplify how to get indexData from mysql/mariadb --- system/Database/MySQLi/Connection.php | 217 ++++++++++++++------------ 1 file changed, 114 insertions(+), 103 deletions(-) diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index df2b81690b59..0605889552e5 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use \CodeIgniter\Database\Exceptions\DatabaseException; @@ -44,14 +45,12 @@ */ class Connection extends BaseConnection implements ConnectionInterface { - /** * Database driver * - * @var string + * @var string */ public $DBDriver = 'MySQLi'; - /** * DELETE hack flag * @@ -59,21 +58,17 @@ class Connection extends BaseConnection implements ConnectionInterface * of affected rows to be shown. Uses a preg_replace when enabled, * adding a bit more processing to all queries. * - * @var bool + * @var boolean */ public $deleteHack = true; - // -------------------------------------------------------------------- - /** * Identifier escape character * - * @var string + * @var string */ public $escapeChar = '`'; - // -------------------------------------------------------------------- - /** * MySQLi object * @@ -82,13 +77,12 @@ class Connection extends BaseConnection implements ConnectionInterface * @var \MySQLi */ public $mysqli; - //-------------------------------------------------------------------- /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -99,14 +93,14 @@ public function connect($persistent = false) if ($this->hostname[0] === '/') { $hostname = null; - $port = null; - $socket = $this->hostname; + $port = null; + $socket = $this->hostname; } else { $hostname = ($persistent === true) ? 'p:' . $this->hostname : $this->hostname; - $port = empty($this->port) ? null : $this->port; - $socket = null; + $port = empty($this->port) ? null : $this->port; + $socket = null; } $client_flags = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0; @@ -120,7 +114,8 @@ public function connect($persistent = false) { if ($this->strictOn) { - $this->mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); + $this->mysqli->options(MYSQLI_INIT_COMMAND, + 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); } else { @@ -139,21 +134,21 @@ public function connect($persistent = false) if (is_array($this->encrypt)) { - $ssl = []; - empty($this->encrypt['ssl_key']) || $ssl['key'] = $this->encrypt['ssl_key']; - empty($this->encrypt['ssl_cert']) || $ssl['cert'] = $this->encrypt['ssl_cert']; - empty($this->encrypt['ssl_ca']) || $ssl['ca'] = $this->encrypt['ssl_ca']; + $ssl = []; + empty($this->encrypt['ssl_key']) || $ssl['key'] = $this->encrypt['ssl_key']; + empty($this->encrypt['ssl_cert']) || $ssl['cert'] = $this->encrypt['ssl_cert']; + empty($this->encrypt['ssl_ca']) || $ssl['ca'] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) || $ssl['capath'] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) || $ssl['cipher'] = $this->encrypt['ssl_cipher']; - if ( ! empty($ssl)) + if (! empty($ssl)) { if (isset($this->encrypt['ssl_verify'])) { if ($this->encrypt['ssl_verify']) { defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && - $this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true); + $this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true); } // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another @@ -169,18 +164,20 @@ public function connect($persistent = false) $client_flags |= MYSQLI_CLIENT_SSL; $this->mysqli->ssl_set( - $ssl['key'] ?? null, $ssl['cert'] ?? null, $ssl['ca'] ?? null, $ssl['capath'] ?? null, $ssl['cipher'] ?? null + $ssl['key'] ?? null, $ssl['cert'] ?? null, $ssl['ca'] ?? null, + $ssl['capath'] ?? null, $ssl['cipher'] ?? null ); } } - if ($this->mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags) + if ($this->mysqli->real_connect($hostname, $this->username, $this->password, + $this->database, $port, $socket, $client_flags) ) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails - if ( - ($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'") - ->fetch_object()->Value) + if (($client_flags & MYSQLI_CLIENT_SSL) && version_compare($this->mysqli->client_info, + '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'") + ->fetch_object()->Value) ) { $this->mysqli->close(); @@ -191,18 +188,21 @@ public function connect($persistent = false) { throw new DatabaseException($message); } + return false; } - if ( ! $this->mysqli->set_charset($this->charset)) + if (! $this->mysqli->set_charset($this->charset)) { - log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}')."); + log_message('error', + "Database: Unable to set the configured connection charset ('{$this->charset}')."); $this->mysqli->close(); if ($this->db->debug) { throw new DatabaseException('Unable to set client connection character set: ' . $this->charset); } + return false; } @@ -300,10 +300,10 @@ public function getVersion() */ public function execute($sql) { - while($this->connID->more_results()) + while ($this->connID->more_results()) { $this->connID->next_result(); - if($res = $this->connID->store_result()) + if ($res = $this->connID->store_result()) { $res->free(); } @@ -319,9 +319,9 @@ public function execute($sql) * * If needed, each database adapter can prep the query string * - * @param string $sql an SQL query + * @param string $sql an SQL query * - * @return string + * @return string */ protected function prepQuery($sql) { @@ -352,8 +352,9 @@ public function affectedRows(): int /** * Platform-dependant string escape * - * @param string $str - * @return string + * @param string $str + * + * @return string */ protected function _escapeString(string $str): string { @@ -375,7 +376,7 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ @@ -383,7 +384,7 @@ protected function _listTables($prefixLimit = false): string { $sql = 'SHOW TABLES FROM ' . $this->escapeIdentifiers($this->database); - if ($prefixLimit !== FALSE && $this->DBPrefix !== '') + if ($prefixLimit !== false && $this->DBPrefix !== '') { return $sql . " LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%'"; } @@ -402,7 +403,7 @@ protected function _listTables($prefixLimit = false): string */ protected function _listColumns(string $table = ''): string { - return 'SHOW COLUMNS FROM ' . $this->protectIdentifiers($table, TRUE, NULL, FALSE); + return 'SHOW COLUMNS FROM ' . $this->protectIdentifiers($table, true, null, false); } //-------------------------------------------------------------------- @@ -410,30 +411,31 @@ protected function _listColumns(string $table = ''): string /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array { - $table = $this->protectIdentifiers($table, TRUE, NULL, FALSE); + $table = $this->protectIdentifiers($table, true, null, false); - if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === FALSE) + if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === false) { throw new DatabaseException(lang('Database.failGetFieldData')); } $query = $query->getResultObject(); $retval = []; - for ($i = 0, $c = count($query); $i < $c; $i ++ ) + for ($i = 0, $c = count($query); $i < $c; $i++) { - $retval[$i] = new \stdClass(); + $retval[$i] = new \stdClass(); $retval[$i]->name = $query[$i]->Field; sscanf($query[$i]->Type, '%[a-z](%d)', $retval[$i]->type, $retval[$i]->max_length); - $retval[$i]->default = $query[$i]->Default; - $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI'); + $retval[$i]->default = $query[$i]->Default; + $retval[$i]->primary_key = (int)($query[$i]->Key === 'PRI'); } return $retval; @@ -444,62 +446,66 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * + * @return \stdClass[] * @throws DatabaseException * @throws \LogicException */ public function _indexData(string $table): array { - $table = $this->protectIdentifiers($table, TRUE, NULL, FALSE); + $table = $this->protectIdentifiers($table, true, null, false); - if (($query = $this->query('SHOW CREATE TABLE ' . $table)) === FALSE) + if (($query = $this->query('SHOW INDEX FROM ' . $table)) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); } - if (! $row = $query->getRowArray()) + if (! $indexes = $query->getResultArray()) { return []; } - $retval = []; - foreach (explode("\n", $row['Create Table']) as $line) + $keys = []; + + foreach ($indexes as $index) { - $line = trim($line); - if (strpos($line, 'PRIMARY KEY') === 0) + if (empty($keys[$index['Key_name']])) { - $obj = new \stdClass(); - $obj->name = 'PRIMARY KEY'; - $_fields = explode(',', preg_replace('/^.*\((.+)\).*$/', '$1', $line)); - $obj->fields = array_map(function($v) { - return trim($v, '`'); - }, $_fields); - $obj->type = 'PRIMARY'; - - $retval[] = $obj; - } - elseif (($unique = strpos($line, 'UNIQUE KEY') === 0) || strpos($line, 'KEY') === 0) - { - if (preg_match('/KEY `([^`]+)` \((.+)\)/', $line, $matches)) + $keys[$index['Key_name']] = new \stdClass(); + $keys[$index['Key_name']]->name = $index['Key_name']; + + if ($index['Key_name'] === 'PRIMARY') + { + $type = 'PRIMARY'; + } + elseif ($index['Index_type'] === 'FULLTEXT') { - $obj = new \stdClass(); - $obj->name = $matches[1]; - $obj->fields = array_map(function($v) { - return trim($v, '`'); - }, explode(',', $matches[2])); - $obj->type = $unique ? 'UNIQUE' : 'INDEX'; - - $retval[] = $obj; + $type = 'FULLTEXT'; + } + elseif ($index['Non_unique']) + { + if ($index['Index_type'] === 'SPATIAL') + { + $type = 'SPATIAL'; + } + else + { + $type = 'INDEX'; + } } else { - throw new \LogicException(lang('Database.parseStringFail')); + $type = 'UNIQUE'; } + + $keys[$index['Key_name']]->type = $type; } + + $keys[$index['Key_name']]->fields[] = $index['Column_name']; } - return $retval; + return $keys; } //-------------------------------------------------------------------- @@ -507,8 +513,9 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * + * @return \stdClass[] * @throws DatabaseException */ public function _foreignKeyData(string $table): array @@ -522,9 +529,9 @@ public function _foreignKeyData(string $table): array INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS AS rc ON tc.CONSTRAINT_NAME = rc.CONSTRAINT_NAME WHERE - tc.CONSTRAINT_TYPE = '.$this->escape('FOREIGN KEY').' AND - tc.TABLE_SCHEMA = '.$this->escape($this->database).' AND - tc.TABLE_NAME = '.$this->escape($table); + tc.CONSTRAINT_TYPE = ' . $this->escape('FOREIGN KEY') . ' AND + tc.TABLE_SCHEMA = ' . $this->escape($this->database) . ' AND + tc.TABLE_NAME = ' . $this->escape($table); if (($query = $this->query($sql)) === false) { @@ -535,10 +542,10 @@ public function _foreignKeyData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->CONSTRAINT_NAME; - $obj->table_name = $row->TABLE_NAME; - $obj->foreign_table_name = $row->REFERENCED_TABLE_NAME; + $obj = new \stdClass(); + $obj->constraint_name = $row->CONSTRAINT_NAME; + $obj->table_name = $row->TABLE_NAME; + $obj->foreign_table_name = $row->REFERENCED_TABLE_NAME; $retval[] = $obj; } @@ -555,19 +562,22 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error() { - if ( ! empty($this->mysqli->connect_errno)) + if (! empty($this->mysqli->connect_errno)) { return [ - 'code' => $this->mysqli->connect_errno, - 'message' => $this->mysqli->connect_error + 'code' => $this->mysqli->connect_errno, + 'message' => $this->mysqli->connect_error, ]; } - return ['code' => $this->connID->errno, 'message' => $this->connID->error]; + return [ + 'code' => $this->connID->errno, + 'message' => $this->connID->error, + ]; } //-------------------------------------------------------------------- @@ -575,7 +585,7 @@ public function error() /** * Insert ID * - * @return int + * @return integer */ public function insertID() { @@ -587,7 +597,7 @@ public function insertID() /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -601,13 +611,14 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { if ($this->connID->commit()) { $this->connID->autocommit(true); + return true; } @@ -619,18 +630,18 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { if ($this->connID->rollback()) { $this->connID->autocommit(true); + return true; } return false; } - //-------------------------------------------------------------------- } From 6c07a683dd7f0c089cbc1e661f362ee6ecb83932 Mon Sep 17 00:00:00 2001 From: Natan Felles Date: Mon, 12 Nov 2018 14:29:30 -0200 Subject: [PATCH 2/2] Update return keys --- system/Database/Forge.php | 323 ++++++++++++----------- system/Database/Postgre/Connection.php | 101 +++---- system/Database/SQLite3/Connection.php | 103 ++++---- tests/system/Database/Live/ForgeTest.php | 74 +++--- 4 files changed, 307 insertions(+), 294 deletions(-) diff --git a/system/Database/Forge.php b/system/Database/Forge.php index 8c170a5c49c9..747ec0b0abf0 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use \CodeIgniter\Database\Exceptions\DatabaseException; /** @@ -66,6 +67,7 @@ class Forge /** * List of unique keys. + * * @var array */ protected $uniqueKeys = []; @@ -80,7 +82,7 @@ class Forge /** * List of foreign keys. * - * @var type + * @var array */ protected $foreignKeys = []; @@ -96,28 +98,28 @@ class Forge /** * CREATE DATABASE statement * - * @var string + * @var string */ protected $createDatabaseStr = 'CREATE DATABASE %s'; /** * DROP DATABASE statement * - * @var string + * @var string */ protected $dropDatabaseStr = 'DROP DATABASE %s'; /** * CREATE TABLE statement * - * @var string + * @var string */ protected $createTableStr = "%s %s (%s\n)"; /** * CREATE TABLE IF statement * - * @var string + * @var string */ protected $createTableIfStr = 'CREATE TABLE IF NOT EXISTS'; @@ -127,42 +129,42 @@ class Forge * Whether table keys are created from within the * CREATE TABLE statement. * - * @var bool + * @var boolean */ protected $createTableKeys = false; /** * DROP TABLE IF EXISTS statement * - * @var string + * @var string */ protected $dropTableIfStr = 'DROP TABLE IF EXISTS'; /** * RENAME TABLE statement * - * @var string + * @var string */ protected $renameTableStr = 'ALTER TABLE %s RENAME TO %s;'; /** * UNSIGNED support * - * @var bool|array + * @var boolean|array */ protected $unsigned = true; /** * NULL value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $null = ''; /** * DEFAULT value representation in CREATE/ALTER TABLE statements * - * @var string + * @var string */ protected $default = ' DEFAULT '; @@ -195,9 +197,9 @@ public function getConnection() /** * Create database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function createDatabase($db_name) @@ -235,9 +237,9 @@ public function createDatabase($db_name) /** * Drop database * - * @param string $db_name + * @param string $db_name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropDatabase($db_name) @@ -278,11 +280,11 @@ public function dropDatabase($db_name) /** * Add Key * - * @param string|array $key - * @param bool $primary - * @param bool $unique + * @param string|array $key + * @param boolean $primary + * @param boolean $unique * - * @return Forge + * @return Forge */ public function addKey($key, bool $primary = false, bool $unique = false) { @@ -321,7 +323,6 @@ public function addPrimaryKey($key) //-------------------------------------------------------------------- - /** * Add Unique Key * @@ -339,9 +340,9 @@ public function addUniqueKey($key) /** * Add Field * - * @param array $field + * @param array|string $field * - * @return Forge + * @return Forge */ public function addField($field) { @@ -382,11 +383,11 @@ public function addField($field) /** * Add Foreign Key * - * @param string $fieldName - * @param string $tableName - * @param string $tableField - * @param bool $onUpdate - * @param bool $onDelete + * @param string $fieldName + * @param string $tableName + * @param string $tableField + * @param boolean $onUpdate + * @param boolean $onDelete * * @return \CodeIgniter\Database\Forge * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -405,7 +406,6 @@ public function addForeignKey($fieldName = '', $tableName = '', $tableField = '' 'onUpdate' => strtoupper($onUpdate), ]; - return $this; } @@ -414,16 +414,16 @@ public function addForeignKey($fieldName = '', $tableName = '', $tableField = '' /** * Foreign Key Drop * - * @param string $table Table name - * @param string $foreign_name Foreign name + * @param string $table Table name + * @param string $foreign_name Foreign name * - * @return bool|\CodeIgniter\Database\BaseResult|\CodeIgniter\Database\Query|false|mixed + * @return boolean|\CodeIgniter\Database\BaseResult|\CodeIgniter\Database\Query|false|mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropForeignKey($table, $foreign_name) { - $sql = sprintf($this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix.$table), - $this->db->escapeIdentifiers($this->db->DBPrefix.$foreign_name)); + $sql = sprintf($this->dropConstraintStr, $this->db->escapeIdentifiers($this->db->DBPrefix . $table), + $this->db->escapeIdentifiers($this->db->DBPrefix . $foreign_name)); if ($sql === false) { @@ -443,11 +443,11 @@ public function dropForeignKey($table, $foreign_name) /** * Create Table * - * @param string $table Table name - * @param bool $if_not_exists Whether to add IF NOT EXISTS condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $if_not_exists Whether to add IF NOT EXISTS condition + * @param array $attributes Associative array of table attributes * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function createTable($table, $if_not_exists = false, array $attributes = []) @@ -504,11 +504,11 @@ public function createTable($table, $if_not_exists = false, array $attributes = /** * Create Table * - * @param string $table Table name - * @param bool $if_not_exists Whether to add 'IF NOT EXISTS' condition - * @param array $attributes Associative array of table attributes + * @param string $table Table name + * @param boolean $if_not_exists Whether to add 'IF NOT EXISTS' condition + * @param array $attributes Associative array of table attributes * - * @return mixed + * @return mixed */ protected function _createTable($table, $if_not_exists, $attributes) { @@ -529,8 +529,8 @@ protected function _createTable($table, $if_not_exists, $attributes) $columns = $this->_processFields(true); for ($i = 0, $c = count($columns); $i < $c; $i++) { - $columns[$i] = ($columns[$i]['_literal'] !== false) ? "\n\t".$columns[$i]['_literal'] - : "\n\t".$this->_processColumn($columns[$i]); + $columns[$i] = ($columns[$i]['_literal'] !== false) ? "\n\t" . $columns[$i]['_literal'] + : "\n\t" . $this->_processColumn($columns[$i]); } $columns = implode(',', $columns); @@ -545,7 +545,7 @@ protected function _createTable($table, $if_not_exists, $attributes) } // createTableStr will usually have the following format: "%s %s (%s\n)" - $sql = sprintf($this->createTableStr.'%s', $sql, $this->db->escapeIdentifiers($table), $columns, + $sql = sprintf($this->createTableStr . '%s', $sql, $this->db->escapeIdentifiers($table), $columns, $this->_createTableAttributes($attributes)); return $sql; @@ -556,9 +556,9 @@ protected function _createTable($table, $if_not_exists, $attributes) /** * CREATE TABLE attributes * - * @param array $attributes Associative array of table attributes + * @param array $attributes Associative array of table attributes * - * @return string + * @return string */ protected function _createTableAttributes($attributes) { @@ -580,9 +580,9 @@ protected function _createTableAttributes($attributes) /** * Drop Table * - * @param string $table_name Table name - * @param bool $if_exists Whether to add an IF EXISTS condition - * @param bool $cascade Whether to add an CASCADE condition + * @param string $table_name Table name + * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param boolean $cascade Whether to add an CASCADE condition * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException @@ -599,14 +599,13 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) return false; } - // If the prefix is already starting the table name, remove it... if (! empty($this->db->DBPrefix) && strpos($table_name, $this->db->DBPrefix) === 0) { $table_name = substr($table_name, strlen($this->db->DBPrefix)); } - if (($query = $this->_dropTable($this->db->DBPrefix.$table_name, $if_exists, $cascade)) === true) + if (($query = $this->_dropTable($this->db->DBPrefix . $table_name, $if_exists, $cascade)) === true) { return true; } @@ -616,7 +615,7 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) // Update table list cache if ($query && ! empty($this->db->dataCache['table_names'])) { - $key = array_search(strtolower($this->db->DBPrefix.$table_name), + $key = array_search(strtolower($this->db->DBPrefix . $table_name), array_map('strtolower', $this->db->dataCache['table_names']), true); if ($key !== false) { @@ -634,11 +633,11 @@ public function dropTable($table_name, $if_exists = false, $cascade = false) * * Generates a platform-specific DROP TABLE string * - * @param string $table Table name - * @param bool $if_exists Whether to add an IF EXISTS condition - * @param bool $cascade Whether to add an CASCADE condition + * @param string $table Table name + * @param boolean $if_exists Whether to add an IF EXISTS condition + * @param boolean $cascade Whether to add an CASCADE condition * - * @return string + * @return string */ protected function _dropTable($table, $if_exists, $cascade) { @@ -659,7 +658,7 @@ protected function _dropTable($table, $if_exists, $cascade) } } - $sql = $sql.' '.$this->db->escapeIdentifiers($table); + $sql = $sql . ' ' . $this->db->escapeIdentifiers($table); return $sql; } @@ -669,10 +668,10 @@ protected function _dropTable($table, $if_exists, $cascade) /** * Rename Table * - * @param string $table_name Old table name - * @param string $new_table_name New table name + * @param string $table_name Old table name + * @param string $new_table_name New table name * - * @return mixed + * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function renameTable($table_name, $new_table_name) @@ -692,17 +691,17 @@ public function renameTable($table_name, $new_table_name) } $result = $this->db->query(sprintf($this->renameTableStr, - $this->db->escapeIdentifiers($this->db->DBPrefix.$table_name), - $this->db->escapeIdentifiers($this->db->DBPrefix.$new_table_name)) + $this->db->escapeIdentifiers($this->db->DBPrefix . $table_name), + $this->db->escapeIdentifiers($this->db->DBPrefix . $new_table_name)) ); if ($result && ! empty($this->db->dataCache['table_names'])) { - $key = array_search(strtolower($this->db->DBPrefix.$table_name), + $key = array_search(strtolower($this->db->DBPrefix . $table_name), array_map('strtolower', $this->db->dataCache['table_names']), true); if ($key !== false) { - $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix.$new_table_name; + $this->db->dataCache['table_names'][$key] = $this->db->DBPrefix . $new_table_name; } } @@ -714,10 +713,10 @@ public function renameTable($table_name, $new_table_name) /** * Column Add * - * @param string $table Table name - * @param array $field Column definition + * @param string $table Table name + * @param array $field Column definition * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function addColumn($table, $field) @@ -730,7 +729,7 @@ public function addColumn($table, $field) $this->addField([$k => $field[$k]]); } - $sqls = $this->_alterTable('ADD', $this->db->DBPrefix.$table, $this->_processFields()); + $sqls = $this->_alterTable('ADD', $this->db->DBPrefix . $table, $this->_processFields()); $this->_reset(); if ($sqls === false) { @@ -758,15 +757,15 @@ public function addColumn($table, $field) /** * Column Drop * - * @param string $table Table name - * @param string $column_name Column name + * @param string $table Table name + * @param string $column_name Column name * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function dropColumn($table, $column_name) { - $sql = $this->_alterTable('DROP', $this->db->DBPrefix.$table, $column_name); + $sql = $this->_alterTable('DROP', $this->db->DBPrefix . $table, $column_name); if ($sql === false) { if ($this->db->DBDebug) @@ -785,10 +784,10 @@ public function dropColumn($table, $column_name) /** * Column Modify * - * @param string $table Table name - * @param string $field Column definition + * @param string $table Table name + * @param string $field Column definition * - * @return bool + * @return boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function modifyColumn($table, $field) @@ -806,7 +805,7 @@ public function modifyColumn($table, $field) throw new \RuntimeException('Field information is required'); } - $sqls = $this->_alterTable('CHANGE', $this->db->DBPrefix.$table, $this->_processFields()); + $sqls = $this->_alterTable('CHANGE', $this->db->DBPrefix . $table, $this->_processFields()); $this->_reset(); if ($sqls === false) { @@ -834,29 +833,29 @@ public function modifyColumn($table, $field) /** * ALTER TABLE * - * @param string $alter_type ALTER type - * @param string $table Table name - * @param mixed $field Column definition + * @param string $alter_type ALTER type + * @param string $table Table name + * @param mixed $field Column definition * - * @return string|string[] + * @return string|string[] */ protected function _alterTable($alter_type, $table, $field) { - $sql = 'ALTER TABLE '.$this->db->escapeIdentifiers($table).' '; + $sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . ' '; // DROP has everything it needs now. if ($alter_type === 'DROP') { - return $sql.'DROP COLUMN '.$this->db->escapeIdentifiers($field); + return $sql . 'DROP COLUMN ' . $this->db->escapeIdentifiers($field); } - $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type.' COLUMN '; + $sql .= ($alter_type === 'ADD') ? 'ADD ' : $alter_type . ' COLUMN '; $sqls = []; for ($i = 0, $c = count($field); $i < $c; $i++) { $sqls[] = $sql - .($field[$i]['_literal'] !== false ? $field[$i]['_literal'] : $this->_processColumn($field[$i])); + . ($field[$i]['_literal'] !== false ? $field[$i]['_literal'] : $this->_processColumn($field[$i])); } return $sqls; @@ -867,9 +866,9 @@ protected function _alterTable($alter_type, $table, $field) /** * Process fields * - * @param bool $create_table + * @param boolean $create_table * - * @return array + * @return array */ protected function _processFields($create_table = false) { @@ -925,7 +924,7 @@ protected function _processFields($create_table = false) { if ($attributes['NULL'] === true) { - $field['null'] = empty($this->null) ? '' : ' '.$this->null; + $field['null'] = empty($this->null) ? '' : ' ' . $this->null; } else { @@ -952,12 +951,12 @@ protected function _processFields($create_table = false) case 'ENUM': case 'SET': $attributes['CONSTRAINT'] = $this->db->escapeString($attributes['CONSTRAINT']); - $field['length'] = is_array($attributes['CONSTRAINT']) ? "('".implode("','", - $attributes['CONSTRAINT'])."')" : '('.$attributes['CONSTRAINT'].')'; + $field['length'] = is_array($attributes['CONSTRAINT']) ? "('" . implode("','", + $attributes['CONSTRAINT']) . "')" : '(' . $attributes['CONSTRAINT'] . ')'; break; default: - $field['length'] = is_array($attributes['CONSTRAINT']) ? '('.implode(',', - $attributes['CONSTRAINT']).')' : '('.$attributes['CONSTRAINT'].')'; + $field['length'] = is_array($attributes['CONSTRAINT']) ? '(' . implode(',', + $attributes['CONSTRAINT']) . ')' : '(' . $attributes['CONSTRAINT'] . ')'; break; } } @@ -973,19 +972,19 @@ protected function _processFields($create_table = false) /** * Process column * - * @param array $field + * @param array $field * - * @return string + * @return string */ protected function _processColumn($field) { return $this->db->escapeIdentifiers($field['name']) - .' '.$field['type'].$field['length'] - .$field['unsigned'] - .$field['default'] - .$field['null'] - .$field['auto_increment'] - .$field['unique']; + . ' ' . $field['type'] . $field['length'] + . $field['unsigned'] + . $field['default'] + . $field['null'] + . $field['auto_increment'] + . $field['unique']; } //-------------------------------------------------------------------- @@ -995,9 +994,9 @@ protected function _processColumn($field) * * Performs a data type mapping between different databases. * - * @param array &$attributes + * @param array &$attributes * - * @return void + * @return void */ protected function _attributeType(&$attributes) { @@ -1018,10 +1017,10 @@ protected function _attributeType(&$attributes) * - array(TYPE => UTYPE) will change $field['type'], * from TYPE to UTYPE in case of a match * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeUnsigned(&$attributes, &$field) { @@ -1062,10 +1061,10 @@ protected function _attributeUnsigned(&$attributes, &$field) /** * Field attribute DEFAULT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeDefault(&$attributes, &$field) { @@ -1078,15 +1077,15 @@ protected function _attributeDefault(&$attributes, &$field) { if ($attributes['DEFAULT'] === null) { - $field['default'] = empty($this->null) ? '' : $this->default.$this->null; + $field['default'] = empty($this->null) ? '' : $this->default . $this->null; // Override the NULL attribute if that's our default $attributes['NULL'] = true; - $field['null'] = empty($this->null) ? '' : ' '.$this->null; + $field['null'] = empty($this->null) ? '' : ' ' . $this->null; } else { - $field['default'] = $this->default.$this->db->escape($attributes['DEFAULT']); + $field['default'] = $this->default . $this->db->escape($attributes['DEFAULT']); } } } @@ -1096,10 +1095,10 @@ protected function _attributeDefault(&$attributes, &$field) /** * Field attribute UNIQUE * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeUnique(&$attributes, &$field) { @@ -1114,15 +1113,15 @@ protected function _attributeUnique(&$attributes, &$field) /** * Field attribute AUTO_INCREMENT * - * @param array &$attributes - * @param array &$field + * @param array &$attributes + * @param array &$field * - * @return void + * @return void */ protected function _attributeAutoIncrement(&$attributes, &$field) { if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true - && stripos($field['type'], 'int') !== false + && stripos($field['type'], 'int') !== false ) { $field['auto_increment'] = ' AUTO_INCREMENT'; @@ -1134,9 +1133,9 @@ protected function _attributeAutoIncrement(&$attributes, &$field) /** * Process primary keys * - * @param string $table Table name + * @param string $table Table name * - * @return string + * @return string */ protected function _processPrimaryKeys($table) { @@ -1152,8 +1151,8 @@ protected function _processPrimaryKeys($table) if (count($this->primaryKeys) > 0) { - $sql .= ",\n\tCONSTRAINT ".$this->db->escapeIdentifiers('pk_'.$table) - .' PRIMARY KEY('.implode(', ', $this->db->escapeIdentifiers($this->primaryKeys)).')'; + $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers('pk_' . $table) + . ' PRIMARY KEY(' . implode(', ', $this->db->escapeIdentifiers($this->primaryKeys)) . ')'; } return $sql; @@ -1164,9 +1163,9 @@ protected function _processPrimaryKeys($table) /** * Process indexes * - * @param string $table + * @param string $table * - * @return array + * @return array */ protected function _processIndexes($table) { @@ -1190,15 +1189,15 @@ protected function _processIndexes($table) if (in_array($i, $this->uniqueKeys)) { - $sqls[] = 'ALTER TABLE '.$this->db->escapeIdentifiers($table) - .' ADD CONSTRAINT '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' UNIQUE ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) + . ' ADD CONSTRAINT ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' UNIQUE (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; continue; } - $sqls[] = 'CREATE INDEX '.$this->db->escapeIdentifiers($table.'_'.implode('_', $this->keys[$i])) - .' ON '.$this->db->escapeIdentifiers($table) - .' ('.implode(', ', $this->db->escapeIdentifiers($this->keys[$i])).');'; + $sqls[] = 'CREATE INDEX ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i])) + . ' ON ' . $this->db->escapeIdentifiers($table) + . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');'; } return $sqls; @@ -1209,35 +1208,45 @@ protected function _processIndexes($table) /** * Process foreign keys * - * @param string $table Table name + * @param string $table Table name * - * @return string + * @return string */ - protected function _processForeignKeys($table) { - $sql = ''; - - $allowActions = ['CASCADE','SET NULL','NO ACTION','RESTRICT','SET DEFAULT']; + protected function _processForeignKeys($table) + { + $sql = ''; - if (count($this->foreignKeys) > 0){ - foreach ($this->foreignKeys as $field => $fkey) { - $name_index = $table.'_'.$field.'_foreign'; + $allowActions = [ + 'CASCADE', + 'SET NULL', + 'NO ACTION', + 'RESTRICT', + 'SET DEFAULT', + ]; - $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) - . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES '.$this->db->escapeIdentifiers($this->db->DBPrefix.$fkey['table']).' ('.$this->db->escapeIdentifiers($fkey['field']).')'; + if (count($this->foreignKeys) > 0) + { + foreach ($this->foreignKeys as $field => $fkey) + { + $name_index = $table . '_' . $field . '_foreign'; - if($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions)){ - $sql .= " ON DELETE ".$fkey['onDelete']; - } + $sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($name_index) + . ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')'; - if($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions)){ - $sql .= " ON UPDATE ".$fkey['onUpdate']; - } + if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions)) + { + $sql .= ' ON DELETE ' . $fkey['onDelete']; + } - } - } + if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions)) + { + $sql .= ' ON UPDATE ' . $fkey['onUpdate']; + } + } + } - return $sql; - } + return $sql; + } //-------------------------------------------------------------------- @@ -1246,7 +1255,7 @@ protected function _processForeignKeys($table) { * * Resets table creation vars * - * @return void + * @return void */ protected function _reset() { diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index cb30f5b15e15..5de091481665 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2018 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\Exceptions\DatabaseException; @@ -64,7 +65,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Identifier escape character * - * @var string + * @var string */ public $escapeChar = '"'; @@ -73,7 +74,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * @return mixed */ public function connect($persistent = false) @@ -167,7 +168,7 @@ public function getVersion() return $this->dataCache['version']; } - if ( ! $this->connID or ( $pgVersion = pg_version($this->connID)) === false) + if (! $this->connID || ( $pgVersion = pg_version($this->connID)) === false) { $this->initialize(); } @@ -235,8 +236,8 @@ public function escape($str) /** * Platform-dependant string escape * - * @param string $str - * @return string + * @param string $str + * @return string */ protected function _escapeString(string $str): string { @@ -253,7 +254,7 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ @@ -285,7 +286,7 @@ protected function _listColumns(string $table = ''): string return 'SELECT "column_name" FROM "information_schema"."columns" WHERE LOWER("table_name") = ' - . $this->escape($this->DBPrefix.strtolower($table)); + . $this->escape($this->DBPrefix . strtolower($table)); } //-------------------------------------------------------------------- @@ -293,8 +294,8 @@ protected function _listColumns(string $table = ''): string /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array @@ -311,12 +312,12 @@ public function _fieldData(string $table): array $query = $query->getResultObject(); $retval = []; - for ($i = 0, $c = count($query); $i < $c; $i ++ ) + for ($i = 0, $c = count($query); $i < $c; $i ++) { - $retval[$i] = new \stdClass(); - $retval[$i]->name = $query[$i]->column_name; - $retval[$i]->type = $query[$i]->data_type; - $retval[$i]->default = $query[$i]->column_default; + $retval[$i] = new \stdClass(); + $retval[$i]->name = $query[$i]->column_name; + $retval[$i]->type = $query[$i]->data_type; + $retval[$i]->default = $query[$i]->column_default; $retval[$i]->max_length = $query[$i]->character_maximum_length > 0 ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision; } @@ -328,8 +329,8 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _indexData(string $table): array @@ -348,10 +349,10 @@ public function _indexData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->name = $row->indexname; - $_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); - $obj->fields = array_map(function($v) { + $obj = new \stdClass(); + $obj->name = $row->indexname; + $_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef))); + $obj->fields = array_map(function ($v) { return trim($v); }, $_fields); @@ -361,11 +362,11 @@ public function _indexData(string $table): array } else { - $obj->type = (strpos($row->indexdef, 'CREATE UNIQUE') === 0) ? 'UNIQUE' :'INDEX'; + $obj->type = (strpos($row->indexdef, 'CREATE UNIQUE') === 0) ? 'UNIQUE' : 'INDEX'; } - $retval[] = $obj; - } + $retval[$obj->name] = $obj; + } return $retval; } @@ -375,8 +376,8 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _foreignKeyData(string $table): array @@ -390,8 +391,8 @@ public function _foreignKeyData(string $table): array ON tc.constraint_name = kcu.constraint_name JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name - WHERE constraint_type = '.$this->escape('FOREIGN KEY').' AND - tc.table_name = '.$this->escape($table); + WHERE constraint_type = ' . $this->escape('FOREIGN KEY') . ' AND + tc.table_name = ' . $this->escape($table); if (($query = $this->query($sql)) === false) { @@ -402,11 +403,11 @@ public function _foreignKeyData(string $table): array $retval = []; foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->constraint_name; - $obj->table_name = $row->table_name; + $obj = new \stdClass(); + $obj->constraint_name = $row->constraint_name; + $obj->table_name = $row->table_name; $obj->foreign_table_name = $row->foreign_table_name; - $retval[] = $obj; + $retval[] = $obj; } return $retval; @@ -421,13 +422,13 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error() { return [ - 'code' => '', - 'message' => pg_last_error($this->connID) + 'code' => '', + 'message' => pg_last_error($this->connID), ]; } @@ -436,7 +437,7 @@ public function error() /** * Insert ID * - * @return int + * @return integer */ public function insertID() { @@ -444,7 +445,7 @@ public function insertID() // 'server' key is only available since PostgreSQL 7.4 $v = $v['server'] ?? 0; - $table = func_num_args() > 0 ? func_get_arg(0) : 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') @@ -455,10 +456,10 @@ public function insertID() { if ($column !== null && $v >= '8.0') { - $sql = "SELECT pg_get_serial_sequence('{$table}', '{$column}') AS seq"; + $sql = "SELECT pg_get_serial_sequence('{$table}', '{$column}') AS seq"; $query = $this->query($sql); $query = $query->getRow(); - $seq = $query->seq; + $seq = $query->seq; } else { @@ -497,7 +498,7 @@ protected function buildDSN() $this->hostname === '' || $this->DSN = "host={$this->hostname} "; - if ( ! empty($this->port) && ctype_digit($this->port)) + if (! empty($this->port) && ctype_digit($this->port)) { $this->DSN .= "port={$this->port} "; } @@ -535,8 +536,8 @@ protected function buildDSN() /** * Set client encoding * - * @param string $charset The client encoding to which the data will be converted. - * @return bool + * @param string $charset The client encoding to which the data will be converted. + * @return boolean */ protected function setClientEncoding($charset) { @@ -548,7 +549,7 @@ protected function setClientEncoding($charset) /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -560,7 +561,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { @@ -572,7 +573,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { diff --git a/system/Database/SQLite3/Connection.php b/system/Database/SQLite3/Connection.php index 4c2cd9bccc5a..367945d171ee 100644 --- a/system/Database/SQLite3/Connection.php +++ b/system/Database/SQLite3/Connection.php @@ -27,14 +27,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author CodeIgniter Dev Team - * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 3.0.0 + * @package CodeIgniter + * @author CodeIgniter Dev Team + * @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 3.0.0 * @filesource */ + use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\Exceptions\DatabaseException; @@ -48,7 +49,7 @@ class Connection extends BaseConnection implements ConnectionInterface /** * Database driver * - * @var string + * @var string */ public $DBDriver = 'SQLite3'; @@ -57,23 +58,26 @@ class Connection extends BaseConnection implements ConnectionInterface /** * ORDER BY random keyword * - * @var array + * @var array */ - protected $_random_keyword = ['RANDOM()', 'RANDOM()']; + protected $_random_keyword = [ + 'RANDOM()', + 'RANDOM()', + ]; //-------------------------------------------------------------------- /** * Connect to the database. * - * @param bool $persistent + * @param boolean $persistent * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function connect($persistent = false) { - if ($persistent and $this->db->DBDebug) + if ($persistent && $this->db->DBDebug) { throw new DatabaseException('SQLite3 doesn\'t support persistent connections.'); } @@ -82,9 +86,10 @@ public function connect($persistent = false) return (! $this->password) ? new \SQLite3($this->database) : new \SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password); - } catch (\Exception $e) + } + catch (\Exception $e) { - throw new DatabaseException('SQLite3 error: '.$e->getMessage()); + throw new DatabaseException('SQLite3 error: ' . $e->getMessage()); } } @@ -149,13 +154,12 @@ public function getVersion() //-------------------------------------------------------------------- - /** * Execute the query * - * @param string $sql + * @param string $sql * - * @return mixed \SQLite3Result object or bool + * @return mixed \SQLite3Result object or bool */ public function execute($sql) { @@ -181,9 +185,9 @@ public function affectedRows(): int /** * Platform-dependant string escape * - * @param string $str + * @param string $str * - * @return string + * @return string */ protected function _escapeString(string $str): string { @@ -195,15 +199,15 @@ protected function _escapeString(string $str): string /** * Generates the SQL for listing tables in a platform-dependent manner. * - * @param bool $prefixLimit + * @param boolean $prefixLimit * * @return string */ protected function _listTables($prefixLimit = false): string { return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\'' - .(($prefixLimit !== false && $this->DBPrefix != '') - ? ' AND "NAME" LIKE \''.$this->escapeLikeString($this->DBPrefix).'%\' '.sprintf($this->likeEscapeStr, + . (($prefixLimit !== false && $this->DBPrefix !== '') + ? ' AND "NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . '%\' ' . sprintf($this->likeEscapeStr, $this->likeEscapeChar) : ''); } @@ -219,14 +223,13 @@ protected function _listTables($prefixLimit = false): string */ protected function _listColumns(string $table = ''): string { - return 'PRAGMA TABLE_INFO('.$this->protectIdentifiers($table, true, null, false).')'; + return 'PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')'; } - /** * Fetch Field Names * - * @param string $table Table name + * @param string $table Table name * * @return array|false * @throws DatabaseException @@ -254,7 +257,7 @@ public function getFieldNames($table) return false; } - $query = $this->query($sql); + $query = $this->query($sql); $this->dataCache['field_names'][$table] = []; foreach ($query->getResultArray() as $row) @@ -289,18 +292,17 @@ public function getFieldNames($table) //-------------------------------------------------------------------- - /** * Returns an array of objects with field data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _fieldData(string $table): array { - if (($query = $this->query('PRAGMA TABLE_INFO('.$this->protectIdentifiers($table, true, null, - false).')')) === false) + if (($query = $this->query('PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, + false) . ')')) === false) { throw new DatabaseException(lang('Database.failGetFieldData')); } @@ -328,15 +330,15 @@ public function _fieldData(string $table): array /** * Returns an array of objects with index data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] * @throws DatabaseException */ public function _indexData(string $table): array { // Get indexes // Don't use PRAGMA index_list, so we can preserve index order - $sql = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=".$this->escape(strtolower($table)); + $sql = "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=" . $this->escape(strtolower($table)); if (($query = $this->query($sql)) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); @@ -351,7 +353,7 @@ public function _indexData(string $table): array // Get fields for index $obj->fields = []; - if (($fields = $this->query('PRAGMA index_info('.$this->escape(strtolower($row->name)).')')) === false) + if (($fields = $this->query('PRAGMA index_info(' . $this->escape(strtolower($row->name)) . ')')) === false) { throw new DatabaseException(lang('Database.failGetIndexData')); } @@ -362,7 +364,7 @@ public function _indexData(string $table): array $obj->fields[] = $field->name; } - $retval[] = $obj; + $retval[$obj->name] = $obj; } return $retval; @@ -373,8 +375,8 @@ public function _indexData(string $table): array /** * Returns an array of objects with Foreign key data * - * @param string $table - * @return \stdClass[] + * @param string $table + * @return \stdClass[] */ public function _foreignKeyData(string $table): array { @@ -398,9 +400,9 @@ public function _foreignKeyData(string $table): array foreach ($query as $row) { - $obj = new \stdClass(); - $obj->constraint_name = $row->from.' to '. $row->table.'.'.$row->to; - $obj->table_name = $table; + $obj = new \stdClass(); + $obj->constraint_name = $row->from . ' to ' . $row->table . '.' . $row->to; + $obj->table_name = $table; $obj->foreign_table_name = $row->table; $retval[] = $obj; @@ -419,11 +421,14 @@ public function _foreignKeyData(string $table): array * * return ['code' => null, 'message' => null); * - * @return array + * @return array */ public function error(): array { - return ['code' => $this->connID->lastErrorCode(), 'message' => $this->connID->lastErrorMsg()]; + return [ + 'code' => $this->connID->lastErrorCode(), + 'message' => $this->connID->lastErrorMsg(), + ]; } //-------------------------------------------------------------------- @@ -431,7 +436,7 @@ public function error(): array /** * Insert ID * - * @return int + * @return integer */ public function insertID(): int { @@ -443,7 +448,7 @@ public function insertID(): int /** * Begin Transaction * - * @return bool + * @return boolean */ protected function _transBegin(): bool { @@ -455,7 +460,7 @@ protected function _transBegin(): bool /** * Commit Transaction * - * @return bool + * @return boolean */ protected function _transCommit(): bool { @@ -467,7 +472,7 @@ protected function _transCommit(): bool /** * Rollback Transaction * - * @return bool + * @return boolean */ protected function _transRollback(): bool { @@ -479,7 +484,7 @@ protected function _transRollback(): bool /** * Determines if the statement is a write-type query or not. * - * @return bool + * @return boolean */ public function isWriteType($sql): bool { @@ -494,11 +499,11 @@ public function isWriteType($sql): bool * Checks to see if the current install supports Foreign Keys * and has them enabled. * - * @return bool + * @return boolean */ protected function supportsForeignKeys(): bool { - $result = $this->simpleQuery("PRAGMA foreign_keys"); + $result = $this->simpleQuery('PRAGMA foreign_keys'); return (bool)$result; } diff --git a/tests/system/Database/Live/ForgeTest.php b/tests/system/Database/Live/ForgeTest.php index bf289e0e9009..9fcfc5be8955 100644 --- a/tests/system/Database/Live/ForgeTest.php +++ b/tests/system/Database/Live/ForgeTest.php @@ -11,6 +11,10 @@ class ForgeTest extends CIDatabaseTestCase protected $refresh = true; protected $seed = 'Tests\Support\Database\Seeds\CITestSeeder'; + /** + * @var \CodeIgniter\Database\Forge + */ + protected $forge; public function setUp() { @@ -42,7 +46,7 @@ public function testCreateTable() public function testCreateTableWithAttributes() { - if ($this->db->DBDriver == 'SQLite3') + if ($this->db->DBDriver === 'SQLite3') { $this->markTestSkipped('SQLite3 does not support comments on tables or columns.'); } @@ -52,7 +56,7 @@ public function testCreateTableWithAttributes() $this->forge->addField('id'); $attributes = [ - 'comment' => "Forge's Test" + 'comment' => "Forge's Test", ]; $this->forge->createTable('forge_test_attributes', false, $attributes); @@ -65,7 +69,6 @@ public function testCreateTableWithAttributes() public function testAddFields() { - $this->forge->dropTable('forge_test_fields', true); $this->forge->addField([ @@ -121,7 +124,6 @@ public function testAddFields() $this->assertEquals($fieldsData[0]->primary_key, 1); $this->assertEquals($fieldsData[1]->max_length, 255); - } elseif ($this->db->DBDriver === 'Postgre') { @@ -143,17 +145,16 @@ public function testAddFields() } else { - $this->assertTrue(false, "DB Driver not supported"); + $this->assertTrue(false, 'DB Driver not supported'); } $this->forge->dropTable('forge_test_fields', true); - } public function testCompositeKey() { // SQLite3 uses auto increment different - $unique_or_auto = $this->db->DBDriver == 'SQLite3' ? 'unique' : 'auto_increment'; + $unique_or_auto = $this->db->DBDriver === 'SQLite3' ? 'unique' : 'auto_increment'; $this->forge->addField([ 'id' => [ @@ -169,7 +170,7 @@ public function testCompositeKey() 'type' => 'VARCHAR', 'constraint' => 40, ], - 'active' => [ + 'active' => [ 'type' => 'INTEGER', 'constraint' => 1, ], @@ -181,29 +182,29 @@ public function testCompositeKey() $keys = $this->db->getIndexData('forge_test_1'); - if ($this->db->DBDriver == 'MySQLi') + if ($this->db->DBDriver === 'MySQLi') { - $this->assertEquals($keys[0]->name, 'PRIMARY KEY'); - $this->assertEquals($keys[0]->fields, ['id']); - $this->assertEquals($keys[0]->type, 'PRIMARY'); - $this->assertEquals($keys[2]->name, 'code_company'); - $this->assertEquals($keys[2]->fields, ['code', 'company']); - $this->assertEquals($keys[2]->type, 'INDEX'); - $this->assertEquals($keys[1]->name, 'code_active'); - $this->assertEquals($keys[1]->fields, ['code', 'active']); - $this->assertEquals($keys[1]->type, 'UNIQUE'); + $this->assertEquals($keys['PRIMARY']->name, 'PRIMARY'); + $this->assertEquals($keys['PRIMARY']->fields, ['id']); + $this->assertEquals($keys['PRIMARY']->type, 'PRIMARY'); + $this->assertEquals($keys['code_company']->name, 'code_company'); + $this->assertEquals($keys['code_company']->fields, ['code', 'company']); + $this->assertEquals($keys['code_company']->type, 'INDEX'); + $this->assertEquals($keys['code_active']->name, 'code_active'); + $this->assertEquals($keys['code_active']->fields, ['code', 'active']); + $this->assertEquals($keys['code_active']->type, 'UNIQUE'); } - elseif($this->db->DBDriver == 'Postgre') + elseif ($this->db->DBDriver === 'Postgre') { - $this->assertEquals($keys[0]->name, 'pk_db_forge_test_1'); - $this->assertEquals($keys[0]->fields, ['id']); - $this->assertEquals($keys[0]->type, 'PRIMARY'); - $this->assertEquals($keys[1]->name, 'db_forge_test_1_code_company'); - $this->assertEquals($keys[1]->fields, ['code', 'company']); - $this->assertEquals($keys[1]->type, 'INDEX'); - $this->assertEquals($keys[2]->name, 'db_forge_test_1_code_active'); - $this->assertEquals($keys[2]->fields, ['code', 'active']); - $this->assertEquals($keys[2]->type, 'UNIQUE'); + $this->assertEquals($keys['pk_db_forge_test_1']->name, 'pk_db_forge_test_1'); + $this->assertEquals($keys['pk_db_forge_test_1']->fields, ['id']); + $this->assertEquals($keys['pk_db_forge_test_1']->type, 'PRIMARY'); + $this->assertEquals($keys['db_forge_test_1_code_company']->name, 'db_forge_test_1_code_company'); + $this->assertEquals($keys['db_forge_test_1_code_company']->fields, ['code', 'company']); + $this->assertEquals($keys['db_forge_test_1_code_company']->type, 'INDEX'); + $this->assertEquals($keys['db_forge_test_1_code_active']->name, 'db_forge_test_1_code_active'); + $this->assertEquals($keys['db_forge_test_1_code_active']->fields, ['code', 'active']); + $this->assertEquals($keys['db_forge_test_1_code_active']->type, 'UNIQUE'); } $this->forge->dropTable('forge_test_1', true); @@ -213,7 +214,7 @@ public function testForeignKey() { $attributes = []; - if ($this->db->DBDriver == 'MySQLi') + if ($this->db->DBDriver === 'MySQLi') { $attributes = ['ENGINE' => 'InnoDB']; } @@ -252,32 +253,30 @@ public function testForeignKey() $foreignKeyData = $this->db->getForeignKeyData('forge_test_invoices'); - if ($this->db->DBDriver == 'SQLite3') + if ($this->db->DBDriver === 'SQLite3') { $this->assertEquals($foreignKeyData[0]->constraint_name, 'users_id to db_forge_test_users.id'); } else { - $this->assertEquals($foreignKeyData[0]->constraint_name,$this->db->DBPrefix.'forge_test_invoices_users_id_foreign'); + $this->assertEquals($foreignKeyData[0]->constraint_name, $this->db->DBPrefix . 'forge_test_invoices_users_id_foreign'); } - $this->assertEquals($foreignKeyData[0]->table_name, $this->db->DBPrefix.'forge_test_invoices'); - $this->assertEquals($foreignKeyData[0]->foreign_table_name, $this->db->DBPrefix.'forge_test_users'); + $this->assertEquals($foreignKeyData[0]->table_name, $this->db->DBPrefix . 'forge_test_invoices'); + $this->assertEquals($foreignKeyData[0]->foreign_table_name, $this->db->DBPrefix . 'forge_test_users'); $this->forge->dropTable('forge_test_invoices', true); $this->forge->dropTable('forge_test_users', true); - } public function testDropForeignKey() { - $attributes = []; - if ($this->db->DBDriver == 'MySQLi') + if ($this->db->DBDriver === 'MySQLi') { $attributes = ['ENGINE' => 'InnoDB']; } - if ($this->db->DBDriver == 'SQLite3') + if ($this->db->DBDriver === 'SQLite3') { $this->expectException(DatabaseException::class); } @@ -322,6 +321,5 @@ public function testDropForeignKey() $this->forge->dropTable('forge_test_invoices', true); $this->forge->dropTable('forge_test_users', true); - } }