Upgrade CakePHP from 2.2.5 to 2.9.5

This commit is contained in:
Brm Ko 2017-02-26 15:29:44 +01:00
parent 5a580df460
commit 235a541597
793 changed files with 60746 additions and 23753 deletions

View file

@ -2,19 +2,18 @@
/**
* MySQL layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Model.Datasource.Database
* @since CakePHP(tm) v 0.10.5.1790
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
@ -46,13 +45,14 @@ class Mysql extends DboSource {
'login' => 'root',
'password' => '',
'database' => 'cake',
'port' => '3306'
'port' => '3306',
'flags' => array()
);
/**
* Reference to the PDO object connection
*
* @var PDO $_connection
* @var PDO
*/
protected $_connection = null;
@ -73,7 +73,7 @@ class Mysql extends DboSource {
/**
* use alias for update and delete. Set to true if version >= 4.1
*
* @var boolean
* @var bool
*/
protected $_useAlias = true;
@ -85,7 +85,13 @@ class Mysql extends DboSource {
public $fieldParameters = array(
'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault')
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault'),
'unsigned' => array(
'value' => 'UNSIGNED', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault',
'noVal' => true,
'options' => array(true),
'types' => array('integer', 'float', 'decimal', 'biginteger')
)
);
/**
@ -96,7 +102,8 @@ class Mysql extends DboSource {
public $tableParameters = array(
'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine'),
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => '=', 'column' => 'Comment'),
);
/**
@ -108,8 +115,10 @@ class Mysql extends DboSource {
'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'biginteger' => array('name' => 'bigint', 'limit' => '20'),
'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
@ -118,29 +127,55 @@ class Mysql extends DboSource {
'boolean' => array('name' => 'tinyint', 'limit' => '1')
);
/**
* Mapping of collation names to character set names
*
* @var array
*/
protected $_charsets = array();
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if the database could be connected, else false
* MySQL supports a few additional options that other drivers do not:
*
* - `unix_socket` Set to the path of the MySQL sock file. Can be used in place
* of host + port.
* - `ssl_key` SSL key file for connecting via SSL. Must be combined with `ssl_cert`.
* - `ssl_cert` The SSL certificate to use when connecting via SSL. Must be
* combined with `ssl_key`.
* - `ssl_ca` The certificate authority for SSL connections.
*
* @return bool True if the database could be connected, else false
* @throws MissingConnectionException
*/
public function connect() {
$config = $this->config;
$this->connected = false;
$flags = $config['flags'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (!empty($config['encoding'])) {
$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
}
if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
$flags[PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
$flags[PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
}
if (!empty($config['ssl_ca'])) {
$flags[PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
}
if (empty($config['unix_socket'])) {
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
} else {
$dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
}
try {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (!empty($config['encoding'])) {
$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
}
if (empty($config['unix_socket'])) {
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
} else {
$dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
}
$this->_connection = new PDO(
$dsn,
$config['login'],
@ -148,6 +183,11 @@ class Mysql extends DboSource {
$flags
);
$this->connected = true;
if (!empty($config['settings'])) {
foreach ($config['settings'] as $key => $value) {
$this->_execute("SET $key=$value");
}
}
} catch (PDOException $e) {
throw new MissingConnectionException(array(
'class' => get_class($this),
@ -155,6 +195,7 @@ class Mysql extends DboSource {
));
}
$this->_charsets = array();
$this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
return $this->connected;
@ -163,7 +204,7 @@ class Mysql extends DboSource {
/**
* Check whether the MySQL extension is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('mysql', PDO::getAvailableDrivers());
@ -172,12 +213,12 @@ class Mysql extends DboSource {
/**
* Returns an array of sources (tables) in the database.
*
* @param mixed $data
* @param mixed $data List of tables.
* @return array Array of table names in the database
*/
public function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
if ($cache) {
return $cache;
}
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
@ -185,23 +226,22 @@ class Mysql extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
/**
* Builds a map of the columns contained in a result
*
* @param PDOStatement $results
* @param PDOStatement $results The results to format.
* @return void
*/
public function resultSet($results) {
@ -211,10 +251,10 @@ class Mysql extends DboSource {
while ($numFields-- > 0) {
$column = $results->getColumnMeta($index);
if (empty($column['native_type'])) {
$type = ($column['len'] == 1) ? 'boolean' : 'string';
if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
$type = 'boolean';
} else {
$type = $column['native_type'];
$type = empty($column['native_type']) ? 'string' : $column['native_type'];
}
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
$this->map[$index++] = array($column['table'], $column['name'], $type);
@ -261,15 +301,24 @@ class Mysql extends DboSource {
* @return string Character set name
*/
public function getCharsetName($name) {
if ((bool)version_compare($this->getVersion(), "5", ">=")) {
$r = $this->_execute('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?', array($name));
$cols = $r->fetch(PDO::FETCH_ASSOC);
if (isset($cols['CHARACTER_SET_NAME'])) {
return $cols['CHARACTER_SET_NAME'];
}
if ((bool)version_compare($this->getVersion(), "5", "<")) {
return false;
}
return false;
if (isset($this->_charsets[$name])) {
return $this->_charsets[$name];
}
$r = $this->_execute(
'SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?',
array($name)
);
$cols = $r->fetch(PDO::FETCH_ASSOC);
if (isset($cols['CHARACTER_SET_NAME'])) {
$this->_charsets[$name] = $cols['CHARACTER_SET_NAME'];
} else {
$this->_charsets[$name] = false;
}
return $this->_charsets[$name];
}
/**
@ -282,7 +331,7 @@ class Mysql extends DboSource {
public function describe($model) {
$key = $this->fullTableName($model, false);
$cache = parent::describe($key);
if ($cache != null) {
if ($cache) {
return $cache;
}
$table = $this->fullTableName($model);
@ -298,8 +347,14 @@ class Mysql extends DboSource {
'type' => $this->column($column->Type),
'null' => ($column->Null === 'YES' ? true : false),
'default' => $column->Default,
'length' => $this->length($column->Type),
'length' => $this->length($column->Type)
);
if (in_array($fields[$column->Field]['type'], $this->fieldParameters['unsigned']['types'], true)) {
$fields[$column->Field]['unsigned'] = $this->_unsigned($column->Type);
}
if (in_array($fields[$column->Field]['type'], array('timestamp', 'datetime')) && strtoupper($column->Default) === 'CURRENT_TIMESTAMP') {
$fields[$column->Field]['default'] = null;
}
if (!empty($column->Key) && isset($this->index[$column->Key])) {
$fields[$column->Field]['key'] = $this->index[$column->Key];
}
@ -323,10 +378,10 @@ class Mysql extends DboSource {
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @param Model $model The model to update.
* @param array $fields The fields to update.
* @param array $values The values to set.
* @param mixed $conditions The conditions to use.
* @return array
*/
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
@ -334,7 +389,7 @@ class Mysql extends DboSource {
return parent::update($model, $fields, $values, $conditions);
}
if ($values == null) {
if (!$values) {
$combined = $fields;
} else {
$combined = array_combine($fields, $values);
@ -347,7 +402,7 @@ class Mysql extends DboSource {
if (!empty($conditions)) {
$alias = $this->name($model->alias);
if ($model->name == $model->alias) {
if ($model->name === $model->alias) {
$joins = implode(' ', $this->_getJoins($model));
}
}
@ -367,9 +422,9 @@ class Mysql extends DboSource {
/**
* Generates and executes an SQL DELETE statement for given id/conditions on given model.
*
* @param Model $model
* @param mixed $conditions
* @return boolean Success
* @param Model $model The model to delete from.
* @param mixed $conditions The conditions to use.
* @return bool Success
*/
public function delete(Model $model, $conditions = null) {
if (!$this->_useAlias) {
@ -382,13 +437,7 @@ class Mysql extends DboSource {
if (empty($conditions)) {
$alias = $joins = false;
}
$complexConditions = false;
foreach ((array)$conditions as $key => $value) {
if (strpos($key, $model->alias) === false) {
$complexConditions = true;
break;
}
}
$complexConditions = $this->_deleteNeedsComplexConditions($model, $conditions);
if (!$complexConditions) {
$joins = false;
}
@ -404,11 +453,32 @@ class Mysql extends DboSource {
return true;
}
/**
* Checks whether complex conditions are needed for a delete with the given conditions.
*
* @param Model $model The model to delete from.
* @param mixed $conditions The conditions to use.
* @return bool Whether or not complex conditions are needed
*/
protected function _deleteNeedsComplexConditions(Model $model, $conditions) {
$fields = array_keys($this->describe($model));
foreach ((array)$conditions as $key => $value) {
if (in_array(strtolower(trim($key)), $this->_sqlBoolOps, true)) {
if ($this->_deleteNeedsComplexConditions($model, $value)) {
return true;
}
} elseif (strpos($key, $model->alias) === false && !in_array($key, $fields, true)) {
return true;
}
}
return false;
}
/**
* Sets the database encoding
*
* @param string $enc Database encoding
* @return boolean
* @return bool
*/
public function setEncoding($enc) {
return $this->_execute('SET NAMES ' . $enc) !== false;
@ -425,17 +495,22 @@ class Mysql extends DboSource {
$table = $this->fullTableName($model);
$old = version_compare($this->getVersion(), '4.1', '<=');
if ($table) {
$indices = $this->_execute('SHOW INDEX FROM ' . $table);
$indexes = $this->_execute('SHOW INDEX FROM ' . $table);
// @codingStandardsIgnoreStart
// MySQL columns don't match the cakephp conventions.
while ($idx = $indices->fetch(PDO::FETCH_OBJ)) {
while ($idx = $indexes->fetch(PDO::FETCH_OBJ)) {
if ($old) {
$idx = (object)current((array)$idx);
}
if (!isset($index[$idx->Key_name]['column'])) {
$col = array();
$index[$idx->Key_name]['column'] = $idx->Column_name;
$index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
if ($idx->Index_type === 'FULLTEXT') {
$index[$idx->Key_name]['type'] = strtolower($idx->Index_type);
} else {
$index[$idx->Key_name]['unique'] = (int)($idx->Non_unique == 0);
}
} else {
if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
$col[] = $index[$idx->Key_name]['column'];
@ -451,7 +526,7 @@ class Mysql extends DboSource {
}
}
// @codingStandardsIgnoreEnd
$indices->closeCursor();
$indexes->closeCursor();
}
return $index;
}
@ -460,7 +535,7 @@ class Mysql extends DboSource {
* Generate a MySQL Alter Table syntax for the given Schema comparison
*
* @param array $compare Result of a CakeSchema::compare()
* @param string $table
* @param string $table The table name.
* @return array Array of alter statements to make.
*/
public function alterSchema($compare, $table = null) {
@ -471,7 +546,7 @@ class Mysql extends DboSource {
$colList = array();
foreach ($compare as $curTable => $types) {
$indexes = $tableParameters = $colList = array();
if (!$table || $table == $curTable) {
if (!$table || $table === $curTable) {
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
foreach ($types as $type => $column) {
if (isset($column['indexes'])) {
@ -492,21 +567,25 @@ class Mysql extends DboSource {
}
$colList[] = $alter;
}
break;
break;
case 'drop':
foreach ($column as $field => $col) {
$col['name'] = $field;
$colList[] = 'DROP ' . $this->name($field);
}
break;
break;
case 'change':
foreach ($column as $field => $col) {
if (!isset($col['name'])) {
$col['name'] = $field;
}
$colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
$alter = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
if (isset($col['after'])) {
$alter .= ' AFTER ' . $this->name($col['after']);
}
$colList[] = $alter;
}
break;
break;
}
}
$colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
@ -518,21 +597,13 @@ class Mysql extends DboSource {
}
/**
* Generate a MySQL "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table === $curTable) {
$out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
}
/**
@ -570,8 +641,11 @@ class Mysql extends DboSource {
}
$name = $this->startQuote . $name . $this->endQuote;
}
// length attribute only used for MySQL datasource, for TEXT/BLOB index columns
if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
$out .= 'FULLTEXT ';
}
$out .= 'KEY ' . $name . ' (';
if (is_array($value['column'])) {
if (isset($value['length'])) {
$vals = array();
@ -610,7 +684,7 @@ class Mysql extends DboSource {
if (isset($indexes['drop'])) {
foreach ($indexes['drop'] as $name => $value) {
$out = 'DROP ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
$out .= 'PRIMARY KEY';
} else {
$out .= 'KEY ' . $this->startQuote . $name . $this->endQuote;
@ -635,7 +709,7 @@ class Mysql extends DboSource {
* @return string Formatted length part of an index field
*/
protected function _buildIndexSubPart($lengths, $column) {
if (is_null($lengths)) {
if ($lengths === null) {
return '';
}
if (!isset($lengths[$column])) {
@ -645,7 +719,7 @@ class Mysql extends DboSource {
}
/**
* Returns an detailed array of sources (tables) in the database.
* Returns a detailed array of sources (tables) in the database.
*
* @param string $name Table name to get parameters
* @return array Array of table names in the database
@ -660,24 +734,23 @@ class Mysql extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
foreach ($result as $row) {
$tables[$row['Name']] = (array)$row;
unset($tables[$row['Name']]['queryString']);
if (!empty($row['Collation'])) {
$charset = $this->getCharsetName($row['Collation']);
if ($charset) {
$tables[$row['Name']]['charset'] = $charset;
}
}
$tables = array();
foreach ($result as $row) {
$tables[$row['Name']] = (array)$row;
unset($tables[$row['Name']]['queryString']);
if (!empty($row['Collation'])) {
$charset = $this->getCharsetName($row['Collation']);
if ($charset) {
$tables[$row['Name']]['charset'] = $charset;
}
}
$result->closeCursor();
if (is_string($name) && isset($tables[$name])) {
return $tables[$name];
}
return $tables;
}
$result->closeCursor();
if (is_string($name) && isset($tables[$name])) {
return $tables[$name];
}
return $tables;
}
/**
@ -704,9 +777,12 @@ class Mysql extends DboSource {
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
return $col;
}
if (($col === 'tinyint' && $limit == 1) || $col === 'boolean') {
if (($col === 'tinyint' && $limit === 1) || $col === 'boolean') {
return 'boolean';
}
if (strpos($col, 'bigint') !== false || $col === 'bigint') {
return 'biginteger';
}
if (strpos($col, 'int') !== false) {
return 'integer';
}
@ -719,15 +795,32 @@ class Mysql extends DboSource {
if (strpos($col, 'blob') !== false || $col === 'binary') {
return 'binary';
}
if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
return 'float';
}
if (strpos($col, 'decimal') !== false || strpos($col, 'numeric') !== false) {
return 'decimal';
}
if (strpos($col, 'enum') !== false) {
return "enum($vals)";
}
if (strpos($col, 'set') !== false) {
return "set($vals)";
}
return 'text';
}
/**
* {@inheritDoc}
*/
public function value($data, $column = null, $null = true) {
$value = parent::value($data, $column, $null);
if (is_numeric($value) && substr($column, 0, 3) === 'set') {
return $this->_connection->quote($value);
}
return $value;
}
/**
* Gets the schema name
*
@ -740,10 +833,73 @@ class Mysql extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @return bool
*/
public function nestedTransactionSupported() {
return $this->useNestedTransactions && version_compare($this->getVersion(), '4.1', '>=');
}
/**
* Check if column type is unsigned
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return bool True if column is unsigned, false otherwise
*/
protected function _unsigned($real) {
return strpos(strtolower($real), 'unsigned') !== false;
}
/**
* Inserts multiple values into a table. Uses a single query in order to insert
* multiple rows.
*
* @param string $table The table being inserted into.
* @param array $fields The array of field/column names being inserted.
* @param array $values The array of values to insert. The values should
* be an array of rows. Each row should have values keyed by the column name.
* Each row must have the values in the same order as $fields.
* @return bool
*/
public function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
$holder = implode(', ', array_fill(0, count($fields), '?'));
$fields = implode(', ', array_map(array($this, 'name'), $fields));
$pdoMap = array(
'integer' => PDO::PARAM_INT,
'float' => PDO::PARAM_STR,
'boolean' => PDO::PARAM_BOOL,
'string' => PDO::PARAM_STR,
'text' => PDO::PARAM_STR
);
$columnMap = array();
$rowHolder = "({$holder})";
$sql = "INSERT INTO {$table} ({$fields}) VALUES ";
$countRows = count($values);
for ($i = 0; $i < $countRows; $i++) {
if ($i !== 0) {
$sql .= ',';
}
$sql .= " $rowHolder";
}
$statement = $this->_connection->prepare($sql);
foreach ($values[key($values)] as $key => $val) {
$type = $this->introspectType($val);
$columnMap[$key] = $pdoMap[$type];
}
$valuesList = array();
$i = 1;
foreach ($values as $value) {
foreach ($value as $col => $val) {
$valuesList[] = $val;
$statement->bindValue($i, $val, $columnMap[$col]);
$i++;
}
}
$result = $statement->execute();
$statement->closeCursor();
if ($this->fullDebug) {
$this->logQuery($sql, $valuesList);
}
return $result;
}
}

View file

@ -1,20 +1,17 @@
<?php
/**
* PostgreSQL layer for DBO.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Model.Datasource.Database
* @since CakePHP(tm) v 0.9.1.114
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
@ -34,7 +31,7 @@ class Postgres extends DboSource {
public $description = "PostgreSQL DBO Driver";
/**
* Base driver configuration settings. Merged with user settings.
* Base driver configuration settings. Merged with user settings.
*
* @var array
*/
@ -46,7 +43,9 @@ class Postgres extends DboSource {
'database' => 'cake',
'schema' => 'public',
'port' => 5432,
'encoding' => ''
'encoding' => '',
'sslmode' => 'allow',
'flags' => array()
);
/**
@ -59,7 +58,9 @@ class Postgres extends DboSource {
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'integer', 'formatter' => 'intval'),
'biginteger' => array('name' => 'bigint', 'limit' => '20'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
@ -67,7 +68,8 @@ class Postgres extends DboSource {
'binary' => array('name' => 'bytea'),
'boolean' => array('name' => 'boolean'),
'number' => array('name' => 'numeric'),
'inet' => array('name' => 'inet')
'inet' => array('name' => 'inet'),
'uuid' => array('name' => 'uuid')
);
/**
@ -92,22 +94,31 @@ class Postgres extends DboSource {
*/
protected $_sequenceMap = array();
/**
* The set of valid SQL operations usable in a WHERE statement
*
* @var array
*/
protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', '~', '~\*', '\!~', '\!~\*', 'similar to');
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if successfully connected.
* @return bool True if successfully connected.
* @throws MissingConnectionException
*/
public function connect() {
$config = $this->config;
$this->connected = false;
$flags = $config['flags'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$this->_connection = new PDO(
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']};sslmode={$config['sslmode']}",
$config['login'],
$config['password'],
$flags
@ -118,7 +129,12 @@ class Postgres extends DboSource {
$this->setEncoding($config['encoding']);
}
if (!empty($config['schema'])) {
$this->_execute('SET search_path TO ' . $config['schema']);
$this->_execute('SET search_path TO "' . $config['schema'] . '"');
}
if (!empty($config['settings'])) {
foreach ($config['settings'] as $key => $value) {
$this->_execute("SET $key TO $value");
}
}
} catch (PDOException $e) {
throw new MissingConnectionException(array(
@ -133,7 +149,7 @@ class Postgres extends DboSource {
/**
* Check if PostgreSQL is enabled/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('pgsql', PDO::getAvailableDrivers());
@ -142,13 +158,13 @@ class Postgres extends DboSource {
/**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
*
* @param mixed $data
* @param mixed $data The sources to list.
* @return array Array of table names in the database
*/
public function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
if ($cache) {
return $cache;
}
@ -158,17 +174,17 @@ class Postgres extends DboSource {
if (!$result) {
return array();
} else {
$tables = array();
foreach ($result as $item) {
$tables[] = $item->name;
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$tables = array();
foreach ($result as $item) {
$tables[] = $item->name;
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
/**
@ -197,16 +213,17 @@ class Postgres extends DboSource {
foreach ($cols as $c) {
$type = $c->type;
if (!empty($c->oct_length) && $c->char_length === null) {
if ($c->type == 'character varying') {
if ($c->type === 'character varying') {
$length = null;
$type = 'text';
} elseif ($c->type == 'uuid') {
} elseif ($c->type === 'uuid') {
$type = 'uuid';
$length = 36;
} else {
$length = intval($c->oct_length);
$length = (int)$c->oct_length;
}
} elseif (!empty($c->char_length)) {
$length = intval($c->char_length);
$length = (int)$c->char_length;
} else {
$length = $this->length($c->type);
}
@ -215,7 +232,7 @@ class Postgres extends DboSource {
}
$fields[$c->name] = array(
'type' => $this->column($type),
'null' => ($c->null == 'NO' ? false : true),
'null' => ($c->null === 'NO' ? false : true),
'default' => preg_replace(
"/^'(.*)'$/",
"$1",
@ -224,15 +241,19 @@ class Postgres extends DboSource {
'length' => $length
);
if ($model instanceof Model) {
if ($c->name == $model->primaryKey) {
if ($c->name === $model->primaryKey) {
$fields[$c->name]['key'] = 'primary';
if ($fields[$c->name]['type'] !== 'string') {
if (
$fields[$c->name]['type'] !== 'string' &&
$fields[$c->name]['type'] !== 'uuid'
) {
$fields[$c->name]['length'] = 11;
}
}
}
if (
$fields[$c->name]['default'] == 'NULL' ||
$fields[$c->name]['default'] === 'NULL' ||
$c->default === null ||
preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq)
) {
$fields[$c->name]['default'] = null;
@ -245,7 +266,10 @@ class Postgres extends DboSource {
$this->_sequenceMap[$table][$c->name] = $sequenceName;
}
}
if ($fields[$c->name]['type'] == 'boolean' && !empty($fields[$c->name]['default'])) {
if ($fields[$c->name]['type'] === 'timestamp' && $fields[$c->name]['default'] === '') {
$fields[$c->name]['default'] = null;
}
if ($fields[$c->name]['type'] === 'boolean' && !empty($fields[$c->name]['default'])) {
$fields[$c->name]['default'] = constant($fields[$c->name]['default']);
}
}
@ -268,7 +292,7 @@ class Postgres extends DboSource {
*
* @param string $source Name of the database table
* @param string $field Name of the ID database field. Defaults to "id"
* @return integer
* @return int
*/
public function lastInsertId($source = null, $field = 'id') {
$seq = $this->getSequence($source, $field);
@ -286,20 +310,41 @@ class Postgres extends DboSource {
if (is_object($table)) {
$table = $this->fullTableName($table, false, false);
}
if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
return $this->_sequenceMap[$table][$field];
} else {
return "{$table}_{$field}_seq";
if (!isset($this->_sequenceMap[$table])) {
$this->describe($table);
}
if (isset($this->_sequenceMap[$table][$field])) {
return $this->_sequenceMap[$table][$field];
}
return "{$table}_{$field}_seq";
}
/**
* Reset a sequence based on the MAX() value of $column. Useful
* for resetting sequences after using insertMulti().
*
* @param string $table The name of the table to update.
* @param string $column The column to use when resetting the sequence value,
* the sequence name will be fetched using Postgres::getSequence();
* @return bool success.
*/
public function resetSequence($table, $column) {
$tableName = $this->fullTableName($table, false, false);
$fullTable = $this->fullTableName($table);
$sequence = $this->value($this->getSequence($tableName, $column));
$column = $this->name($column);
$this->execute("SELECT setval($sequence, (SELECT MAX($column) FROM $fullTable))");
return true;
}
/**
* Deletes all the records in a table and drops all associated auto-increment sequences
*
* @param string|Model $table A string or model class representing the table to be truncated
* @param boolean $reset true for resetting the sequence, false to leave it as is.
* @param bool $reset true for resetting the sequence, false to leave it as is.
* and if 1, sequences are not modified
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
*/
public function truncate($table, $reset = false) {
$table = $this->fullTableName($table, false, false);
@ -310,11 +355,10 @@ class Postgres extends DboSource {
$this->cacheSources = $cache;
}
if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
$schema = $this->config['schema'];
if (isset($this->_sequenceMap[$table]) && $reset != true) {
foreach ($this->_sequenceMap[$table] as $field => $sequence) {
list($schema, $sequence) = explode('.', $sequence);
$this->_execute("ALTER SEQUENCE \"{$schema}\".\"{$sequence}\" RESTART WITH 1");
foreach ($this->_sequenceMap[$table] as $sequence) {
$quoted = $this->name($sequence);
$this->_execute("ALTER SEQUENCE {$quoted} RESTART WITH 1");
}
}
return true;
@ -325,7 +369,7 @@ class Postgres extends DboSource {
/**
* Prepares field names to be quoted by parent
*
* @param string $data
* @param string $data The name to format.
* @return string SQL field
*/
public function name($data) {
@ -338,10 +382,10 @@ class Postgres extends DboSource {
/**
* Generates the fields list of an SQL query.
*
* @param Model $model
* @param string $alias Alias table name
* @param mixed $fields
* @param boolean $quote
* @param Model $model The model to get fields for.
* @param string $alias Alias table name.
* @param mixed $fields The list of fields to get.
* @param bool $quote Whether or not to quote identifiers.
* @return array
*/
public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
@ -359,7 +403,7 @@ class Postgres extends DboSource {
$result = array();
for ($i = 0; $i < $count; $i++) {
if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
if (substr($fields[$i], -1) == '*') {
if (substr($fields[$i], -1) === '*') {
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
$build = explode('.', $fields[$i]);
$AssociatedModel = $model->{$build[0]};
@ -385,7 +429,7 @@ class Postgres extends DboSource {
$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
}
} else {
$fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
$fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
}
$result[] = $fields[$i];
}
@ -473,7 +517,7 @@ class Postgres extends DboSource {
$colList = array();
foreach ($compare as $curTable => $types) {
$indexes = $colList = array();
if (!$table || $table == $curTable) {
if (!$table || $table === $curTable) {
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
foreach ($types as $type => $column) {
if (isset($column['indexes'])) {
@ -486,37 +530,59 @@ class Postgres extends DboSource {
$col['name'] = $field;
$colList[] = 'ADD COLUMN ' . $this->buildColumn($col);
}
break;
break;
case 'drop':
foreach ($column as $field => $col) {
$col['name'] = $field;
$colList[] = 'DROP COLUMN ' . $this->name($field);
}
break;
break;
case 'change':
$schema = $this->describe($curTable);
foreach ($column as $field => $col) {
if (!isset($col['name'])) {
$col['name'] = $field;
}
$original = $schema[$field];
$fieldName = $this->name($field);
$default = isset($col['default']) ? $col['default'] : null;
$nullable = isset($col['null']) ? $col['null'] : null;
$boolToInt = $original['type'] === 'boolean' && $col['type'] === 'integer';
unset($col['default'], $col['null']);
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
if ($field !== $col['name']) {
$newName = $this->name($col['name']);
$out .= "\tRENAME {$fieldName} TO {$newName};\n";
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
$fieldName = $newName;
}
if ($boolToInt) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT NULL';
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . ' USING CASE WHEN TRUE THEN 1 ELSE 0 END';
} else {
if ($original['type'] === 'text' && $col['type'] === 'integer') {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . " USING cast({$fieldName} as INTEGER)";
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
}
}
if (isset($nullable)) {
$nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
$colList[] = 'ALTER COLUMN ' . $fieldName . ' ' . $nullable;
}
if (isset($default)) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
if (!$boolToInt) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
}
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' DROP DEFAULT';
}
}
break;
break;
}
}
if (isset($indexes['drop']['PRIMARY'])) {
@ -553,7 +619,7 @@ class Postgres extends DboSource {
if (isset($indexes['drop'])) {
foreach ($indexes['drop'] as $name => $value) {
$out = 'DROP ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
} else {
$out .= 'INDEX ' . $name;
@ -564,7 +630,7 @@ class Postgres extends DboSource {
if (isset($indexes['add'])) {
foreach ($indexes['add'] as $name => $value) {
$out = 'CREATE ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
} else {
if (!empty($value['unique'])) {
@ -586,22 +652,16 @@ class Postgres extends DboSource {
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @param int $limit Limit of results returned
* @param int $offset Offset from which to start results
* @return string SQL limit/offset statement
*/
public function limit($limit, $offset = null) {
if ($limit) {
$rt = '';
if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
$rt .= ' ' . $limit;
$rt = sprintf(' LIMIT %u', $limit);
if ($offset) {
$rt .= ' OFFSET ' . $offset;
$rt .= sprintf(' OFFSET %u', $offset);
}
return $rt;
}
return null;
@ -623,14 +683,13 @@ class Postgres extends DboSource {
}
$col = str_replace(')', '', $real);
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
}
$floats = array(
'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
'float', 'float4', 'float8', 'double', 'double precision', 'real'
);
switch (true) {
@ -640,14 +699,20 @@ class Postgres extends DboSource {
return 'datetime';
case (strpos($col, 'time') === 0):
return 'time';
case (strpos($col, 'int') !== false && $col != 'interval'):
case ($col === 'bigint'):
return 'biginteger';
case (strpos($col, 'int') !== false && $col !== 'interval'):
return 'integer';
case (strpos($col, 'char') !== false || $col == 'uuid'):
case (strpos($col, 'char') !== false):
return 'string';
case (strpos($col, 'uuid') !== false):
return 'uuid';
case (strpos($col, 'text') !== false):
return 'text';
case (strpos($col, 'bytea') !== false):
return 'binary';
case ($col === 'decimal' || $col === 'numeric'):
return 'decimal';
case (in_array($col, $floats)):
return 'float';
default:
@ -659,28 +724,23 @@ class Postgres extends DboSource {
* Gets the length of a database-native column description, or null if no length
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return integer An integer representing the length of the column
* @return int An integer representing the length of the column
*/
public function length($real) {
$col = str_replace(array(')', 'unsigned'), '', $real);
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
$col = $real;
if (strpos($real, '(') !== false) {
list($col, $limit) = explode('(', $real);
}
if ($col == 'uuid') {
if ($col === 'uuid') {
return 36;
}
if ($limit != null) {
return intval($limit);
}
return null;
return parent::length($real);
}
/**
* resultSet method
*
* @param array $results
* @param array &$results The results
* @return void
*/
public function resultSet(&$results) {
@ -715,30 +775,28 @@ class Postgres extends DboSource {
switch ($type) {
case 'bool':
$resultRow[$table][$column] = is_null($row[$index]) ? null : $this->boolean($row[$index]);
break;
$resultRow[$table][$column] = $row[$index] === null ? null : $this->boolean($row[$index]);
break;
case 'binary':
case 'bytea':
$resultRow[$table][$column] = is_null($row[$index]) ? null : stream_get_contents($row[$index]);
break;
$resultRow[$table][$column] = $row[$index] === null ? null : stream_get_contents($row[$index]);
break;
default:
$resultRow[$table][$column] = $row[$index];
break;
}
}
return $resultRow;
} else {
$this->_result->closeCursor();
return false;
}
$this->_result->closeCursor();
return false;
}
/**
* Translates between PHP boolean values and PostgreSQL boolean values
*
* @param mixed $data Value to be translated
* @param boolean $quote true to quote a boolean to be used in a query, false to return the boolean value
* @return boolean Converted boolean value
* @param bool $quote true to quote a boolean to be used in a query, false to return the boolean value
* @return bool Converted boolean value
*/
public function boolean($data, $quote = false) {
switch (true) {
@ -756,7 +814,6 @@ class Postgres extends DboSource {
break;
default:
$result = (bool)$data;
break;
}
if ($quote) {
@ -769,7 +826,7 @@ class Postgres extends DboSource {
* Sets the database encoding
*
* @param mixed $enc Database encoding
* @return boolean True on success, false on failure
* @return bool True on success, false on failure
*/
public function setEncoding($enc) {
return $this->_execute('SET NAMES ' . $this->value($enc)) !== false;
@ -801,8 +858,21 @@ class Postgres extends DboSource {
if (!isset($col['length']) && !isset($col['limit'])) {
unset($column['length']);
}
$out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
$out = parent::buildColumn($column);
$out = preg_replace(
'/integer\([0-9]+\)/',
'integer',
$out
);
$out = preg_replace(
'/bigint\([0-9]+\)/',
'bigint',
$out
);
$out = str_replace('integer serial', 'serial', $out);
$out = str_replace('bigint serial', 'bigserial', $out);
if (strpos($out, 'timestamp DEFAULT')) {
if (isset($column['null']) && $column['null']) {
$out = str_replace('DEFAULT NULL', '', $out);
@ -815,7 +885,7 @@ class Postgres extends DboSource {
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
} elseif (in_array($column['type'], array('integer', 'float'))) {
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
} elseif ($column['type'] == 'boolean') {
} elseif ($column['type'] === 'boolean') {
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
}
}
@ -825,8 +895,8 @@ class Postgres extends DboSource {
/**
* Format indexes for create table
*
* @param array $indexes
* @param string $table
* @param array $indexes The index to build
* @param string $table The table name.
* @return string
*/
public function buildIndex($indexes, $table = null) {
@ -835,7 +905,7 @@ class Postgres extends DboSource {
return array();
}
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
$out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
} else {
$out = 'CREATE ';
@ -854,11 +924,22 @@ class Postgres extends DboSource {
return $join;
}
/**
* {@inheritDoc}
*/
public function value($data, $column = null, $null = true) {
$value = parent::value($data, $column, $null);
if ($column === 'uuid' && is_scalar($data) && $data === '') {
return 'NULL';
}
return $value;
}
/**
* Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
*
* @param string $type
* @param array $data
* @param string $type The query type.
* @param array $data The array of data to render.
* @return string
*/
public function renderStatement($type, $data) {
@ -898,7 +979,7 @@ class Postgres extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @return bool
*/
public function nestedTransactionSupported() {
return $this->useNestedTransactions && version_compare($this->getVersion(), '8.0', '>=');

View file

@ -2,23 +2,22 @@
/**
* SQLite layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Model.Datasource.Database
* @since CakePHP(tm) v 0.9.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
App::uses('String', 'Utility');
App::uses('CakeText', 'Utility');
/**
* DBO implementation for the SQLite3 DBMS.
@ -57,7 +56,8 @@ class Sqlite extends DboSource {
*/
protected $_baseConfig = array(
'persistent' => false,
'database' => null
'database' => null,
'flags' => array()
);
/**
@ -70,7 +70,9 @@ class Sqlite extends DboSource {
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
'biginteger' => array('name' => 'bigint', 'limit' => 20),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
@ -100,12 +102,12 @@ class Sqlite extends DboSource {
/**
* Connects to the database using config['database'] as a filename.
*
* @return boolean
* @return bool
* @throws MissingConnectionException
*/
public function connect() {
$config = $this->config;
$flags = array(
$flags = $config['flags'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
@ -124,7 +126,7 @@ class Sqlite extends DboSource {
/**
* Check whether the SQLite extension is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('sqlite', PDO::getAvailableDrivers());
@ -133,12 +135,12 @@ class Sqlite extends DboSource {
/**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
*
* @param mixed $data
* @param mixed $data Unused.
* @return array Array of table names in the database
*/
public function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
if ($cache) {
return $cache;
}
@ -146,14 +148,14 @@ class Sqlite extends DboSource {
if (!$result || empty($result)) {
return array();
} else {
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['name'];
}
parent::listSources($tables);
return $tables;
}
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['name'];
}
parent::listSources($tables);
return $tables;
}
/**
@ -165,7 +167,7 @@ class Sqlite extends DboSource {
public function describe($model) {
$table = $this->fullTableName($model, false, false);
$cache = parent::describe($table);
if ($cache != null) {
if ($cache) {
return $cache;
}
$fields = array();
@ -183,6 +185,9 @@ class Sqlite extends DboSource {
'default' => $default,
'length' => $this->length($column['type'])
);
if (in_array($fields[$column['name']]['type'], array('timestamp', 'datetime')) && strtoupper($fields[$column['name']]['default']) === 'CURRENT_TIMESTAMP') {
$fields[$column['name']]['default'] = null;
}
if ($column['pk'] == 1) {
$fields[$column['name']]['key'] = $this->index['PRI'];
$fields[$column['name']]['null'] = false;
@ -200,10 +205,10 @@ class Sqlite extends DboSource {
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @param Model $model The model instance to update.
* @param array $fields The fields to update.
* @param array $values The values to set columns to.
* @param mixed $conditions array of conditions to use.
* @return array
*/
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
@ -225,10 +230,12 @@ class Sqlite extends DboSource {
* primary key, where applicable.
*
* @param string|Model $table A string or model class representing the table to be truncated
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
*/
public function truncate($table) {
$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
if (in_array('sqlite_sequence', $this->listSources())) {
$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
}
return $this->execute('DELETE FROM ' . $this->fullTableName($table));
}
@ -248,14 +255,26 @@ class Sqlite extends DboSource {
}
$col = strtolower(str_replace(')', '', $real));
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
list($col) = explode('(', $col);
}
if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
$standard = array(
'text',
'integer',
'float',
'boolean',
'timestamp',
'date',
'datetime',
'time'
);
if (in_array($col, $standard)) {
return $col;
}
if ($col === 'bigint') {
return 'biginteger';
}
if (strpos($col, 'char') !== false) {
return 'string';
}
@ -263,7 +282,7 @@ class Sqlite extends DboSource {
return 'binary';
}
if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
return 'float';
return 'decimal';
}
return 'text';
}
@ -271,7 +290,7 @@ class Sqlite extends DboSource {
/**
* Generate ResultSet
*
* @param mixed $results
* @param mixed $results The results to modify.
* @return void
*/
public function resultSet($results) {
@ -281,14 +300,19 @@ class Sqlite extends DboSource {
$index = 0;
$j = 0;
//PDO::getColumnMeta is experimental and does not work with sqlite3,
// so try to figure it out based on the querystring
// PDO::getColumnMeta is experimental and does not work with sqlite3,
// so try to figure it out based on the querystring
$querystring = $results->queryString;
if (stripos($querystring, 'SELECT') === 0) {
$last = strripos($querystring, 'FROM');
if ($last !== false) {
$selectpart = substr($querystring, 7, $last - 8);
$selects = String::tokenize($selectpart, ',', '(', ')');
if (stripos($querystring, 'SELECT') === 0 && stripos($querystring, 'FROM') > 0) {
$selectpart = substr($querystring, 7);
$selects = array();
foreach (CakeText::tokenize($selectpart, ',', '(', ')') as $part) {
$fromPos = stripos($part, ' FROM ');
if ($fromPos !== false) {
$selects[] = trim(substr($part, 0, $fromPos));
break;
}
$selects[] = $part;
}
} elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
$selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
@ -302,8 +326,8 @@ class Sqlite extends DboSource {
$j++;
continue;
}
if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
$columnName = trim($matches[1], '"');
if (preg_match('/\bAS(?!.*\bAS\b)\s+(.*)/i', $selects[$j], $matches)) {
$columnName = trim($matches[1], '"');
} else {
$columnName = trim(str_replace('"', '', $selects[$j]));
}
@ -342,33 +366,28 @@ class Sqlite extends DboSource {
foreach ($this->map as $col => $meta) {
list($table, $column, $type) = $meta;
$resultRow[$table][$column] = $row[$col];
if ($type == 'boolean' && !is_null($row[$col])) {
if ($type === 'boolean' && $row[$col] !== null) {
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
}
}
return $resultRow;
} else {
$this->_result->closeCursor();
return false;
}
$this->_result->closeCursor();
return false;
}
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @param int $limit Limit of results returned
* @param int $offset Offset from which to start results
* @return string SQL limit/offset statement
*/
public function limit($limit, $offset = null) {
if ($limit) {
$rt = '';
if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
$rt .= ' ' . $limit;
$rt = sprintf(' LIMIT %u', $limit);
if ($offset) {
$rt .= ' OFFSET ' . $offset;
$rt .= sprintf(' OFFSET %u', $offset);
}
return $rt;
}
@ -384,7 +403,7 @@ class Sqlite extends DboSource {
*/
public function buildColumn($column) {
$name = $type = null;
$column = array_merge(array('null' => true), $column);
$column += array('null' => true);
extract($column);
if (empty($name) || empty($type)) {
@ -397,17 +416,26 @@ class Sqlite extends DboSource {
return null;
}
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
$isPrimary = (isset($column['key']) && $column['key'] === 'primary');
if ($isPrimary && $type === 'integer') {
return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
}
return parent::buildColumn($column);
$out = parent::buildColumn($column);
if ($isPrimary && $type === 'biginteger') {
$replacement = 'PRIMARY KEY';
if ($column['null'] === false) {
$replacement = 'NOT NULL ' . $replacement;
}
return str_replace($this->columns['primary_key']['name'], $replacement, $out);
}
return $out;
}
/**
* Sets the database encoding
*
* @param string $enc Database encoding
* @return boolean
* @return bool
*/
public function setEncoding($enc) {
if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
@ -428,9 +456,9 @@ class Sqlite extends DboSource {
/**
* Removes redundant primary key indexes, as they are handled in the column def of the key.
*
* @param array $indexes
* @param string $table
* @return string
* @param array $indexes The indexes to build.
* @param string $table The table name.
* @return string The completed index.
*/
public function buildIndex($indexes, $table = null) {
$join = array();
@ -441,7 +469,7 @@ class Sqlite extends DboSource {
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
}
$out = 'CREATE ';
@ -450,7 +478,7 @@ class Sqlite extends DboSource {
$out .= 'UNIQUE ';
}
if (is_array($value['column'])) {
$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
} else {
$value['column'] = $this->name($value['column']);
}
@ -489,7 +517,7 @@ class Sqlite extends DboSource {
$key['name'] = 'PRIMARY';
}
$index[$key['name']]['column'] = $keyCol[0]['name'];
$index[$key['name']]['unique'] = intval($key['unique'] == 1);
$index[$key['name']]['unique'] = (int)$key['unique'] === 1;
} else {
if (!is_array($index[$key['name']]['column'])) {
$col[] = $index[$key['name']]['column'];
@ -506,8 +534,8 @@ class Sqlite extends DboSource {
/**
* Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
*
* @param string $type
* @param array $data
* @param string $type The type of statement being rendered.
* @param array $data The data to convert to SQL.
* @return string
*/
public function renderStatement($type, $data) {
@ -515,10 +543,10 @@ class Sqlite extends DboSource {
case 'schema':
extract($data);
if (is_array($columns)) {
$columns = "\t" . join(",\n\t", array_filter($columns));
$columns = "\t" . implode(",\n\t", array_filter($columns));
}
if (is_array($indexes)) {
$indexes = "\t" . join("\n\t", array_filter($indexes));
$indexes = "\t" . implode("\n\t", array_filter($indexes));
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
default:
@ -529,28 +557,20 @@ class Sqlite extends DboSource {
/**
* PDO deals in objects, not resources, so overload accordingly.
*
* @return boolean
* @return bool
*/
public function hasResult() {
return is_object($this->_result);
}
/**
* Generate a "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
$out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
}
/**
@ -565,7 +585,7 @@ class Sqlite extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @return bool
*/
public function nestedTransactionSupported() {
return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');

View file

@ -2,28 +2,29 @@
/**
* MS SQL Server layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Model.Datasource.Database
* @since CakePHP(tm) v 0.10.5.1790
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
/**
* Dbo driver for SQLServer
* Dbo layer for Microsoft's official SQLServer driver
*
* A Dbo driver for SQLServer 2008 and higher. Requires the `sqlsrv`
* and `pdo_sqlsrv` extensions to be enabled.
* A Dbo layer for MS SQL Server 2005 and higher. Requires the
* `pdo_sqlsrv` extension to be enabled.
*
* @link http://www.php.net/manual/en/ref.pdo-sqlsrv.php
*
* @package Cake.Model.Datasource.Database
*/
@ -51,7 +52,7 @@ class Sqlserver extends DboSource {
public $endQuote = "]";
/**
* Creates a map between field aliases and numeric indexes. Workaround for the
* Creates a map between field aliases and numeric indexes. Workaround for the
* SQL Server driver's 30-character column name limitation.
*
* @var array
@ -77,6 +78,7 @@ class Sqlserver extends DboSource {
'password' => '',
'database' => 'cake',
'schema' => '',
'flags' => array()
);
/**
@ -86,41 +88,50 @@ class Sqlserver extends DboSource {
*/
public $columns = array(
'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
'string' => array('name' => 'nvarchar', 'limit' => '255'),
'text' => array('name' => 'nvarchar', 'limit' => 'MAX'),
'integer' => array('name' => 'int', 'formatter' => 'intval'),
'float' => array('name' => 'numeric', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'string' => array('name' => 'nvarchar', 'limit' => '255'),
'text' => array('name' => 'nvarchar', 'limit' => 'MAX'),
'integer' => array('name' => 'int', 'formatter' => 'intval'),
'biginteger' => array('name' => 'bigint'),
'numeric' => array('name' => 'decimal', 'formatter' => 'floatval'),
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'real' => array('name' => 'float', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
'binary' => array('name' => 'varbinary'),
'boolean' => array('name' => 'bit')
'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
'binary' => array('name' => 'varbinary'),
'boolean' => array('name' => 'bit')
);
/**
* Magic column name used to provide pagination support for SQLServer 2008
* which lacks proper limit/offset support.
*
* @var string
*/
const ROW_COUNTER = '_cake_page_rownum_';
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if the database could be connected, else false
* @return bool True if the database could be connected, else false
* @throws MissingConnectionException
*/
public function connect() {
$config = $this->config;
$this->connected = false;
$flags = $config['flags'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (!empty($config['encoding'])) {
$flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
}
try {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (!empty($config['encoding'])) {
$flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
}
$this->_connection = new PDO(
"sqlsrv:server={$config['host']};Database={$config['database']}",
$config['login'],
@ -128,6 +139,11 @@ class Sqlserver extends DboSource {
$flags
);
$this->connected = true;
if (!empty($config['settings'])) {
foreach ($config['settings'] as $key => $value) {
$this->_execute("SET $key $value");
}
}
} catch (PDOException $e) {
throw new MissingConnectionException(array(
'class' => get_class($this),
@ -141,7 +157,7 @@ class Sqlserver extends DboSource {
/**
* Check that PDO SQL Server is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('sqlsrv', PDO::getAvailableDrivers());
@ -150,7 +166,7 @@ class Sqlserver extends DboSource {
/**
* Returns an array of sources (tables) in the database.
*
* @param mixed $data
* @param mixed $data The names
* @return array Array of table names in the database
*/
public function listSources($data = null) {
@ -163,17 +179,16 @@ class Sqlserver extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
/**
@ -184,25 +199,30 @@ class Sqlserver extends DboSource {
* @throws CakeException
*/
public function describe($model) {
$table = $this->fullTableName($model, false);
$cache = parent::describe($table);
if ($cache != null) {
$table = $this->fullTableName($model, false, false);
$fulltable = $this->fullTableName($model, false, true);
$cache = parent::describe($fulltable);
if ($cache) {
return $cache;
}
$fields = array();
$table = $this->fullTableName($model, false);
$schema = is_object($model) ? $model->schemaName : false;
$cols = $this->_execute(
"SELECT
COLUMN_NAME as Field,
DATA_TYPE as Type,
COL_LENGTH('" . $table . "', COLUMN_NAME) as Length,
COL_LENGTH('" . ($schema ? $fulltable : $table) . "', COLUMN_NAME) as Length,
IS_NULLABLE As [Null],
COLUMN_DEFAULT as [Default],
COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key],
COLUMNPROPERTY(OBJECT_ID('" . ($schema ? $fulltable : $table) . "'), COLUMN_NAME, 'IsIdentity') as [Key],
NUMERIC_SCALE as Size
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '" . $table . "'"
WHERE TABLE_NAME = '" . $table . "'" . ($schema ? " AND TABLE_SCHEMA = '" . $schema . "'" : '')
);
if (!$cols) {
throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
}
@ -212,18 +232,24 @@ class Sqlserver extends DboSource {
$fields[$field] = array(
'type' => $this->column($column),
'null' => ($column->Null === 'YES' ? true : false),
'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default),
'default' => $column->Default,
'length' => $this->length($column),
'key' => ($column->Key == '1') ? 'primary' : false
);
if ($fields[$field]['default'] === 'null') {
$fields[$field]['default'] = null;
} else {
}
if ($fields[$field]['default'] !== null) {
$fields[$field]['default'] = preg_replace(
"/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/",
"$1",
$fields[$field]['default']
);
$this->value($fields[$field]['default'], $fields[$field]['type']);
}
if ($fields[$field]['key'] !== false && $fields[$field]['type'] == 'integer') {
if ($fields[$field]['key'] !== false && $fields[$field]['type'] === 'integer') {
$fields[$field]['length'] = 11;
} elseif ($fields[$field]['key'] === false) {
unset($fields[$field]['key']);
@ -231,7 +257,7 @@ class Sqlserver extends DboSource {
if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
$fields[$field]['length'] = null;
}
if ($fields[$field]['type'] == 'float' && !empty($column->Size)) {
if ($fields[$field]['type'] === 'float' && !empty($column->Size)) {
$fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size;
}
}
@ -243,10 +269,10 @@ class Sqlserver extends DboSource {
/**
* Generates the fields list of an SQL query.
*
* @param Model $model
* @param Model $model The model to get fields for.
* @param string $alias Alias table name
* @param array $fields
* @param boolean $quote
* @param array $fields The fields so far.
* @param bool $quote Whether or not to quote identfiers.
* @return array
*/
public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
@ -261,13 +287,13 @@ class Sqlserver extends DboSource {
for ($i = 0; $i < $count; $i++) {
$prepend = '';
if (strpos($fields[$i], 'DISTINCT') !== false) {
if (strpos($fields[$i], 'DISTINCT') !== false && strpos($fields[$i], 'COUNT') === false) {
$prepend = 'DISTINCT ';
$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
}
if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
if (substr($fields[$i], -1) == '*') {
if (substr($fields[$i], -1) === '*') {
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
$build = explode('.', $fields[$i]);
$AssociatedModel = $model->{$build[0]};
@ -282,7 +308,7 @@ class Sqlserver extends DboSource {
if (strpos($fields[$i], '.') === false) {
$this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i];
$fieldName = $this->name($alias . '.' . $fields[$i]);
$fieldName = $this->name($alias . '.' . $fields[$i]);
$fieldAlias = $this->name($alias . '__' . $fields[$i]);
} else {
$build = explode('.', $fields[$i]);
@ -295,7 +321,7 @@ class Sqlserver extends DboSource {
$fieldName = $this->name($name);
$fieldAlias = $this->name($alias);
}
if ($model->getColumnType($fields[$i]) == 'datetime') {
if ($model->getColumnType($fields[$i]) === 'datetime') {
$fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
}
$fields[$i] = "{$fieldName} AS {$fieldAlias}";
@ -303,9 +329,8 @@ class Sqlserver extends DboSource {
$result[] = $prepend . $fields[$i];
}
return $result;
} else {
return $fields;
}
return $fields;
}
/**
@ -313,9 +338,9 @@ class Sqlserver extends DboSource {
* Removes Identity (primary key) column from update data before returning to parent, if
* value is empty.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param Model $model The model to insert into.
* @param array $fields The fields to set.
* @param array $values The values to set.
* @return array
*/
public function create(Model $model, $fields = null, $values = null) {
@ -342,10 +367,10 @@ class Sqlserver extends DboSource {
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
* Removes Identity (primary key) column from update data before returning to parent.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @param Model $model The model to update.
* @param array $fields The fields to set.
* @param array $values The values to set.
* @param mixed $conditions The conditions to use.
* @return array
*/
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
@ -364,8 +389,8 @@ class Sqlserver extends DboSource {
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @param int $limit Limit of results returned
* @param int $offset Offset from which to start results
* @return string SQL limit/offset statement
*/
public function limit($limit, $offset = null) {
@ -374,9 +399,9 @@ class Sqlserver extends DboSource {
if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
$rt = ' TOP';
}
$rt .= ' ' . $limit;
$rt .= sprintf(' %u', $limit);
if (is_int($offset) && $offset > 0) {
$rt = ' OFFSET ' . intval($offset) . ' ROWS FETCH FIRST ' . intval($limit) . ' ROWS ONLY';
$rt = sprintf(' OFFSET %u ROWS FETCH FIRST %u ROWS ONLY', $offset, $limit);
}
return $rt;
}
@ -398,15 +423,18 @@ class Sqlserver extends DboSource {
$col = $real->Type;
}
if ($col == 'datetime2') {
if ($col === 'datetime2') {
return 'datetime';
}
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
return $col;
}
if ($col == 'bit') {
if ($col === 'bit') {
return 'boolean';
}
if (strpos($col, 'bigint') !== false) {
return 'biginteger';
}
if (strpos($col, 'int') !== false) {
return 'integer';
}
@ -419,12 +447,15 @@ class Sqlserver extends DboSource {
if (strpos($col, 'text') !== false) {
return 'text';
}
if (strpos($col, 'binary') !== false || $col == 'image') {
if (strpos($col, 'binary') !== false || $col === 'image') {
return 'binary';
}
if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
if (in_array($col, array('float', 'real'))) {
return 'float';
}
if (in_array($col, array('decimal', 'numeric'))) {
return 'decimal';
}
return 'text';
}
@ -443,6 +474,9 @@ class Sqlserver extends DboSource {
if (in_array($length->Type, array('nchar', 'nvarchar'))) {
return floor($length->Length / 2);
}
if ($length->Type === 'text') {
return null;
}
return $length->Length;
}
return parent::length($length);
@ -451,7 +485,7 @@ class Sqlserver extends DboSource {
/**
* Builds a map of the columns contained in a result
*
* @param PDOStatement $results
* @param PDOStatement $results The result to modify.
* @return void
*/
public function resultSet($results) {
@ -474,7 +508,7 @@ class Sqlserver extends DboSource {
} else {
$map = array(0, $name);
}
$map[] = ($column['sqlsrv:decl_type'] == 'bit') ? 'boolean' : $column['native_type'];
$map[] = ($column['sqlsrv:decl_type'] === 'bit') ? 'boolean' : $column['native_type'];
$this->map[$index++] = $map;
}
}
@ -506,25 +540,24 @@ class Sqlserver extends DboSource {
if (version_compare($this->getVersion(), '11', '<') && preg_match('/FETCH\sFIRST\s+([0-9]+)/i', $limit, $offset)) {
preg_match('/OFFSET\s*(\d+)\s*.*?(\d+)\s*ROWS/', $limit, $limitOffset);
$limit = 'TOP ' . intval($limitOffset[2]);
$page = intval($limitOffset[1] / $limitOffset[2]);
$offset = intval($limitOffset[2] * $page);
$limit = 'TOP ' . (int)$limitOffset[2];
$page = (int)($limitOffset[1] / $limitOffset[2]);
$offset = (int)($limitOffset[2] * $page);
$rowCounter = self::ROW_COUNTER;
return "
SELECT {$limit} * FROM (
$rowCounter = static::ROW_COUNTER;
$sql = "SELECT {$limit} * FROM (
SELECT {$fields}, ROW_NUMBER() OVER ({$order}) AS {$rowCounter}
FROM {$table} {$alias} {$joins} {$conditions} {$group}
) AS _cake_paging_
WHERE _cake_paging_.{$rowCounter} > {$offset}
ORDER BY _cake_paging_.{$rowCounter}
";
} elseif (strpos($limit, 'FETCH') !== false) {
return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
} else {
return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}";
return trim($sql);
}
break;
if (strpos($limit, 'FETCH') !== false) {
return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
}
return trim("SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}");
case "schema":
extract($data);
@ -540,7 +573,7 @@ class Sqlserver extends DboSource {
${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
}
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
return trim("CREATE TABLE {$table} (\n{$columns});\n{$indexes}");
default:
return parent::renderStatement($type, $data);
}
@ -551,12 +584,14 @@ class Sqlserver extends DboSource {
*
* @param string $data String to be prepared for use in an SQL statement
* @param string $column The column into which this data will be inserted
* @param bool $null Column allows NULL values
* @return string Quoted and escaped data
*/
public function value($data, $column = null) {
if (is_array($data) || is_object($data)) {
return parent::value($data, $column);
} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
public function value($data, $column = null, $null = true) {
if ($data === null || is_array($data) || is_object($data)) {
return parent::value($data, $column, $null);
}
if (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
return $data;
}
@ -569,7 +604,7 @@ class Sqlserver extends DboSource {
case 'text':
return 'N' . $this->_connection->quote($data, PDO::PARAM_STR);
default:
return parent::value($data, $column);
return parent::value($data, $column, $null);
}
}
@ -577,10 +612,10 @@ class Sqlserver extends DboSource {
* Returns an array of all result rows for a given SQL query.
* Returns false if no rows matched.
*
* @param Model $model
* @param array $queryData
* @param integer $recursive
* @return array Array of resultset rows, or false if no rows matched
* @param Model $model The model to read from
* @param array $queryData The query data
* @param int $recursive How many layers to go.
* @return array|false Array of resultset rows, or false if no rows matched
*/
public function read(Model $model, $queryData = array(), $recursive = null) {
$results = parent::read($model, $queryData, $recursive);
@ -599,11 +634,11 @@ class Sqlserver extends DboSource {
$resultRow = array();
foreach ($this->map as $col => $meta) {
list($table, $column, $type) = $meta;
if ($table === 0 && $column === self::ROW_COUNTER) {
if ($table === 0 && $column === static::ROW_COUNTER) {
continue;
}
$resultRow[$table][$column] = $row[$col];
if ($type === 'boolean' && !is_null($row[$col])) {
if ($type === 'boolean' && $row[$col] !== null) {
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
}
}
@ -616,14 +651,14 @@ class Sqlserver extends DboSource {
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
* @param string $table The table to insert into.
* @param string $fields The fields to set.
* @param array $values The values to set.
* @return void
*/
public function insertMulti($table, $fields, $values) {
$primaryKey = $this->_getPrimaryKey($table);
$hasPrimaryKey = $primaryKey != null && (
$hasPrimaryKey = $primaryKey && (
(is_array($fields) && in_array($primaryKey, $fields)
|| (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
);
@ -649,7 +684,7 @@ class Sqlserver extends DboSource {
*/
public function buildColumn($column) {
$result = parent::buildColumn($column);
$result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', $result);
$result = preg_replace('/(bigint|int|integer)\([0-9]+\)/i', '$1', $result);
$result = preg_replace('/(bit)\([0-9]+\)/i', '$1', $result);
if (strpos($result, 'DEFAULT NULL') !== false) {
if (isset($column['default']) && $column['default'] === '') {
@ -657,7 +692,7 @@ class Sqlserver extends DboSource {
} else {
$result = str_replace('DEFAULT NULL', 'NULL', $result);
}
} elseif (array_keys($column) == array('type', 'name')) {
} elseif (array_keys($column) === array('type', 'name')) {
$result .= ' NULL';
} elseif (strpos($result, "DEFAULT N'")) {
$result = str_replace("DEFAULT N'", "DEFAULT '", $result);
@ -668,15 +703,15 @@ class Sqlserver extends DboSource {
/**
* Format indexes for create table
*
* @param array $indexes
* @param string $table
* @param array $indexes The indexes to build
* @param string $table The table to make indexes for.
* @return string
*/
public function buildIndex($indexes, $table = null) {
$join = array();
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
$join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
} elseif (isset($value['unique']) && $value['unique']) {
$out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
@ -702,7 +737,7 @@ class Sqlserver extends DboSource {
protected function _getPrimaryKey($model) {
$schema = $this->describe($model);
foreach ($schema as $field => $props) {
if (isset($props['key']) && $props['key'] == 'primary') {
if (isset($props['key']) && $props['key'] === 'primary') {
return $field;
}
}
@ -713,8 +748,8 @@ class Sqlserver extends DboSource {
* Returns number of affected rows in previous database operation. If no previous operation exists,
* this returns false.
*
* @param mixed $source
* @return integer Number of affected rows
* @param mixed $source Unused
* @return int Number of affected rows
*/
public function lastAffected($source = null) {
$affected = parent::lastAffected();
@ -736,7 +771,8 @@ class Sqlserver extends DboSource {
*/
protected function _execute($sql, $params = array(), $prepareOptions = array()) {
$this->_lastAffected = false;
if (strncasecmp($sql, 'SELECT', 6) == 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
$sql = trim($sql);
if (strncasecmp($sql, 'SELECT', 6) === 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
$prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL);
return parent::_execute($sql, $params, $prepareOptions);
}
@ -760,21 +796,13 @@ class Sqlserver extends DboSource {
}
/**
* Generate a "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
$out .= "IF OBJECT_ID('" . $this->fullTableName($curTable, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return "IF OBJECT_ID('" . $this->fullTableName($table, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($table) . ";";
}
/**