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

@ -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', '>=');