Browse Source

...

tags/2.0.0-beta
Qiang Xue 13 years ago
parent
commit
a9439e9038
  1. 7
      docs/code_style.md
  2. 2
      framework/YiiBase.php
  3. 36
      framework/base/Application.php
  4. 51
      framework/base/Component.php
  5. 27
      framework/base/Dictionary.php
  6. 21
      framework/base/Model.php
  7. 33
      framework/base/Module.php
  8. 30
      framework/base/Object.php
  9. 33
      framework/base/Vector.php
  10. 15
      framework/console/Command.php
  11. 12
      framework/console/CommandRunner.php
  12. 6
      framework/console/HelpCommand.php
  13. 63
      framework/db/ar/ActiveRecord.php
  14. 3
      framework/db/dao/ColumnSchema.php
  15. 38
      framework/db/dao/Command.php
  16. 27
      framework/db/dao/Connection.php
  17. 6
      framework/db/dao/DataReader.php
  18. 63
      framework/db/dao/Query.php
  19. 51
      framework/db/dao/QueryBuilder.php
  20. 9
      framework/db/dao/Schema.php
  21. 6
      framework/db/dao/Transaction.php
  22. 12
      framework/db/dao/mysql/ColumnSchema.php
  23. 3
      framework/db/dao/mysql/QueryBuilder.php
  24. 9
      framework/db/dao/mysql/Schema.php
  25. 9
      framework/logging/ProfileTarget.php
  26. 3
      framework/logging/Router.php
  27. 3
      framework/logging/WebTarget.php
  28. 6
      framework/util/File.php
  29. 3
      framework/validators/CaptchaValidator.php
  30. 6
      framework/validators/CompareValidator.php
  31. 9
      framework/validators/FileValidator.php
  32. 3
      framework/validators/RangeValidator.php
  33. 3
      framework/validators/RegularExpressionValidator.php
  34. 6
      framework/validators/RequiredValidator.php
  35. 3
      framework/validators/StringValidator.php
  36. 3
      framework/validators/UniqueValidator.php
  37. 6
      framework/validators/UrlValidator.php
  38. 12
      framework/validators/Validator.php
  39. 3
      framework/yiic.php
  40. 33
      tests/unit/MysqlTestCase.php
  41. 144
      tests/unit/data/mysql.sql
  42. 99
      tests/unit/framework/db/dao/CommandTest.php
  43. 30
      tests/unit/framework/db/dao/ConnectionTest.php

7
docs/code_style.md

@ -15,12 +15,9 @@ class MyClass
{ {
public function myClassMethod() public function myClassMethod()
{ {
if($x) if($x) {
{
// do it // do it
} } else {
else
{
// some code // some code
} }
} }

2
framework/YiiBase.php

@ -386,6 +386,8 @@ class YiiBase
if ($object instanceof \yii\base\Initable) { if ($object instanceof \yii\base\Initable) {
$object->init(); $object->init();
} }
return $object;
} }
/** /**

36
framework/base/Application.php

@ -125,8 +125,7 @@ abstract class Application extends Module
if (isset($config['basePath'])) { if (isset($config['basePath'])) {
$this->setBasePath($config['basePath']); $this->setBasePath($config['basePath']);
unset($config['basePath']); unset($config['basePath']);
} } else
else
{ {
$this->setBasePath('protected'); $this->setBasePath('protected');
} }
@ -211,8 +210,7 @@ abstract class Application extends Module
{ {
if ($this->_id !== null) { if ($this->_id !== null) {
return $this->_id; return $this->_id;
} } else
else
{ {
return $this->_id = sprintf('%x', crc32($this->getBasePath() . $this->name)); return $this->_id = sprintf('%x', crc32($this->getBasePath() . $this->name));
} }
@ -258,8 +256,7 @@ abstract class Application extends Module
{ {
if ($this->_runtimePath !== null) { if ($this->_runtimePath !== null) {
return $this->_runtimePath; return $this->_runtimePath;
} } else
else
{ {
$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime'); $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
return $this->_runtimePath; return $this->_runtimePath;
@ -545,8 +542,7 @@ abstract class Application extends Module
$url = $this->createUrl($route, $params, $ampersand); $url = $this->createUrl($route, $params, $ampersand);
if (strpos($url, 'http') === 0) { if (strpos($url, 'http') === 0) {
return $url; return $url;
} } else
else
{ {
return $this->getRequest()->getHostInfo($schema) . $url; return $this->getRequest()->getHostInfo($schema) . $url;
} }
@ -573,13 +569,11 @@ abstract class Application extends Module
if ($this->_homeUrl === null) { if ($this->_homeUrl === null) {
if ($this->getUrlManager()->showScriptName) { if ($this->getUrlManager()->showScriptName) {
return $this->getRequest()->getScriptUrl(); return $this->getRequest()->getScriptUrl();
} } else
else
{ {
return $this->getRequest()->getBaseUrl() . '/'; return $this->getRequest()->getBaseUrl() . '/';
} }
} } else
else
{ {
return $this->_homeUrl; return $this->_homeUrl;
} }
@ -609,8 +603,7 @@ abstract class Application extends Module
} }
if (isset($this->_globalState[$key])) { if (isset($this->_globalState[$key])) {
return $this->_globalState[$key]; return $this->_globalState[$key];
} } else
else
{ {
return $defaultValue; return $defaultValue;
} }
@ -638,8 +631,7 @@ abstract class Application extends Module
unset($this->_globalState[$key]); unset($this->_globalState[$key]);
$this->_stateChanged = true; $this->_stateChanged = true;
} }
} } elseif (!isset($this->_globalState[$key]) || $this->_globalState[$key] !== $value)
elseif (!isset($this->_globalState[$key]) || $this->_globalState[$key] !== $value)
{ {
$this->_globalState[$key] = $value; $this->_globalState[$key] = $value;
$this->_stateChanged = true; $this->_stateChanged = true;
@ -731,8 +723,7 @@ abstract class Application extends Module
// try an error handler // try an error handler
if (($handler = $this->getErrorHandler()) !== null) { if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($event); $handler->handle($event);
} } else
else
{ {
$this->displayException($exception); $this->displayException($exception);
} }
@ -822,8 +813,7 @@ abstract class Application extends Module
// try an error handler // try an error handler
if (($handler = $this->getErrorHandler()) !== null) { if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($event); $handler->handle($event);
} } else
else
{ {
$this->displayError($code, $message, $file, $line); $this->displayError($code, $message, $file, $line);
} }
@ -922,8 +912,7 @@ abstract class Application extends Module
} }
echo '</pre>'; echo '</pre>';
} } else
else
{ {
echo "<h1>PHP Error [$code]</h1>\n"; echo "<h1>PHP Error [$code]</h1>\n";
echo "<p>$message</p>\n"; echo "<p>$message</p>\n";
@ -942,8 +931,7 @@ abstract class Application extends Module
echo '<h1>' . get_class($exception) . "</h1>\n"; echo '<h1>' . get_class($exception) . "</h1>\n";
echo '<p>' . $exception->getMessage() . ' (' . $exception->getFile() . ':' . $exception->getLine() . ')</p>'; echo '<p>' . $exception->getMessage() . ' (' . $exception->getFile() . ':' . $exception->getLine() . ')</p>';
echo '<pre>' . $exception->getTraceAsString() . '</pre>'; echo '<pre>' . $exception->getTraceAsString() . '</pre>';
} } else
else
{ {
echo '<h1>' . get_class($exception) . "</h1>\n"; echo '<h1>' . get_class($exception) . "</h1>\n";
echo '<p>' . $exception->getMessage() . '</p>'; echo '<p>' . $exception->getMessage() . '</p>';

51
framework/base/Component.php

@ -98,18 +98,15 @@ class Component extends Object
$getter = 'get' . $name; $getter = 'get' . $name;
if (method_exists($this, $getter)) { // read property, e.g. getName() if (method_exists($this, $getter)) { // read property, e.g. getName()
return $this->$getter(); return $this->$getter();
} } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event, e.g. onClick()
elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event, e.g. onClick()
$name = strtolower($name); $name = strtolower($name);
if (!isset($this->_e[$name])) { if (!isset($this->_e[$name])) {
$this->_e[$name] = new Vector; $this->_e[$name] = new Vector;
} }
return $this->_e[$name]; return $this->_e[$name];
} } elseif (isset($this->_b[$name])) { // behavior
elseif (isset($this->_b[$name])) { // behavior
return $this->_b[$name]; return $this->_b[$name];
} } elseif (is_array($this->_b)) { // a behavior property
elseif (is_array($this->_b)) { // a behavior property
foreach ($this->_b as $object) { foreach ($this->_b as $object) {
if ($object->canGetProperty($name)) { if ($object->canGetProperty($name)) {
return $object->$name; return $object->$name;
@ -140,15 +137,13 @@ class Component extends Object
$setter = 'set' . $name; $setter = 'set' . $name;
if (method_exists($this, $setter)) { // write property if (method_exists($this, $setter)) { // write property
return $this->$setter($value); return $this->$setter($value);
} } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event
elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event
$name = strtolower($name); $name = strtolower($name);
if (!isset($this->_e[$name])) { if (!isset($this->_e[$name])) {
$this->_e[$name] = new Vector; $this->_e[$name] = new Vector;
} }
return $this->_e[$name]->add($value); return $this->_e[$name]->add($value);
} } elseif (is_array($this->_b)) { // behavior
elseif (is_array($this->_b)) { // behavior
foreach ($this->_b as $object) { foreach ($this->_b as $object) {
if ($object->canSetProperty($name)) { if ($object->canSetProperty($name)) {
return $object->$name = $value; return $object->$name = $value;
@ -157,8 +152,7 @@ class Component extends Object
} }
if (method_exists($this, 'get' . $name)) { if (method_exists($this, 'get' . $name)) {
throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name); throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name);
} } else {
else {
throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name); throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name);
} }
} }
@ -181,15 +175,12 @@ class Component extends Object
$getter = 'get' . $name; $getter = 'get' . $name;
if (method_exists($this, $getter)) { // property is not null if (method_exists($this, $getter)) { // property is not null
return $this->$getter() !== null; return $this->$getter() !== null;
} } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // has event handler
elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // has event handler
$name = strtolower($name); $name = strtolower($name);
return isset($this->_e[$name]) && $this->_e[$name]->getCount(); return isset($this->_e[$name]) && $this->_e[$name]->getCount();
} } elseif (isset($this->_b[$name])) { // has behavior
elseif (isset($this->_b[$name])) { // has behavior
return true; return true;
} } elseif (is_array($this->_b)) {
elseif (is_array($this->_b)) {
foreach ($this->_b as $object) { foreach ($this->_b as $object) {
if ($object->canGetProperty($name)) { if ($object->canGetProperty($name)) {
return $object->$name !== null; return $object->$name !== null;
@ -217,15 +208,12 @@ class Component extends Object
$setter = 'set' . $name; $setter = 'set' . $name;
if (method_exists($this, $setter)) { // write property if (method_exists($this, $setter)) { // write property
return $this->$setter(null); return $this->$setter(null);
} } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event
elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event
unset($this->_e[strtolower($name)]); unset($this->_e[strtolower($name)]);
return; return;
} } elseif (isset($this->_b[$name])) { // behavior
elseif (isset($this->_b[$name])) { // behavior
return $this->detachBehavior($name); return $this->detachBehavior($name);
} } elseif (is_array($this->_b)) { // behavior property
elseif (is_array($this->_b)) { // behavior property
foreach ($this->_b as $object) { foreach ($this->_b as $object) {
if ($object->canSetProperty($name)) { if ($object->canSetProperty($name)) {
return $object->$name = null; return $object->$name = null;
@ -386,21 +374,17 @@ class Component extends Object
foreach ($this->_e[$name] as $handler) { foreach ($this->_e[$name] as $handler) {
if (is_string($handler) || $handler instanceof \Closure) { if (is_string($handler) || $handler instanceof \Closure) {
call_user_func($handler, $event); call_user_func($handler, $event);
} } elseif (is_callable($handler, true)) {
elseif (is_callable($handler, true)) {
// an array: 0 - object, 1 - method name // an array: 0 - object, 1 - method name
list($object, $method) = $handler; list($object, $method) = $handler;
if (is_string($object)) { // static method call if (is_string($object)) { // static method call
call_user_func($handler, $event); call_user_func($handler, $event);
} } elseif (method_exists($object, $method)) {
elseif (method_exists($object, $method)) {
$object->$method($event); $object->$method($event);
} } else {
else {
throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.'); throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.');
} }
} } else {
else {
throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.'); throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.');
} }
@ -409,8 +393,7 @@ class Component extends Object
return; return;
} }
} }
} } elseif (!$this->hasEvent($name)) {
elseif (!$this->hasEvent($name)) {
throw new Exception('Raising unknown event: ' . get_class($this) . '.' . $name); throw new Exception('Raising unknown event: ' . get_class($this) . '.' . $name);
} }
} }

27
framework/base/Dictionary.php

@ -114,8 +114,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
{ {
if ($key === null) { if ($key === null) {
$this->_d[] = $value; $this->_d[] = $value;
} } else {
else {
$this->_d[$key] = $value; $this->_d[$key] = $value;
} }
} }
@ -132,8 +131,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$value = $this->_d[$key]; $value = $this->_d[$key];
unset($this->_d[$key]); unset($this->_d[$key]);
return $value; return $value;
} } else { // the value is null
else { // the value is null
unset($this->_d[$key]); unset($this->_d[$key]);
return null; return null;
} }
@ -151,8 +149,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach (array_keys($this->_d) as $key) { foreach (array_keys($this->_d) as $key) {
$this->remove($key); $this->remove($key);
} }
} } else {
else {
$this->_d = array(); $this->_d = array();
} }
} }
@ -194,8 +191,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$this->add($key, $value); $this->add($key, $value);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); throw new Exception('Data must be either an array or an object implementing Traversable.');
} }
} }
@ -230,18 +226,15 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$d[$key] = $value; $d[$key] = $value;
} }
$this->_d = self::mergeArray($this->_d, $d); $this->_d = self::mergeArray($this->_d, $d);
} } else {
else {
$this->_d = self::mergeArray($this->_d, $data); $this->_d = self::mergeArray($this->_d, $data);
} }
} } else {
else {
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$this->add($key, $value); $this->add($key, $value);
} }
} }
} } else {
else {
throw new Exception('Dictionary data must be an array or an object implementing Traversable.'); throw new Exception('Dictionary data must be an array or an object implementing Traversable.');
} }
} }
@ -317,11 +310,9 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
foreach ($b as $k => $v) { foreach ($b as $k => $v) {
if (is_integer($k)) { if (is_integer($k)) {
isset($a[$k]) ? $a[] = $v : $a[$k] = $v; isset($a[$k]) ? $a[] = $v : $a[$k] = $v;
} } elseif (is_array($v) && isset($a[$k]) && is_array($a[$k])) {
elseif (is_array($v) && isset($a[$k]) && is_array($a[$k])) {
$a[$k] = self::mergeArray($a[$k], $v); $a[$k] = self::mergeArray($a[$k], $v);
} } else {
else {
$a[$k] = $v; $a[$k] = $v;
} }
} }

21
framework/base/Model.php

@ -367,8 +367,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
if (isset($rule[0], $rule[1])) { // attributes, validator type if (isset($rule[0], $rule[1])) { // attributes, validator type
$validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2)); $validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
$validators->add($validator); $validators->add($validator);
} } else {
else {
throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.'); throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.');
} }
} }
@ -456,8 +455,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
{ {
if ($attribute === null) { if ($attribute === null) {
return $this->_errors === null ? array() : $this->_errors; return $this->_errors === null ? array() : $this->_errors;
} } else {
else {
return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array(); return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
} }
} }
@ -496,8 +494,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($error as $e) { foreach ($error as $e) {
$this->_errors[$attribute][] = $e; $this->_errors[$attribute][] = $e;
} }
} } else {
else {
$this->_errors[$attribute][] = $error; $this->_errors[$attribute][] = $error;
} }
} }
@ -511,8 +508,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
{ {
if ($attribute === null) { if ($attribute === null) {
$this->_errors = array(); $this->_errors = array();
} } else {
else {
unset($this->_errors[$attribute]); unset($this->_errors[$attribute]);
} }
} }
@ -547,8 +543,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
$values[$name] = $this->$name; $values[$name] = $this->$name;
} }
} }
} } else {
else {
foreach ($this->attributeNames() as $name) { foreach ($this->attributeNames() as $name) {
$values[$name] = $this->$name; $values[$name] = $this->$name;
} }
@ -572,8 +567,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($values as $name => $value) { foreach ($values as $name => $value) {
if (isset($attributes[$name])) { if (isset($attributes[$name])) {
$this->$name = $value; $this->$name = $value;
} } elseif ($safeOnly) {
elseif ($safeOnly) {
$this->onUnsafeAttribute($name, $value); $this->onUnsafeAttribute($name, $value);
} }
} }
@ -639,8 +633,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc
foreach ($validator->attributes as $name) { foreach ($validator->attributes as $name) {
$unsafe[] = $name; $unsafe[] = $name;
} }
} } else {
else {
foreach ($validator->attributes as $name) { foreach ($validator->attributes as $name) {
$attributes[$name] = true; $attributes[$name] = true;
} }

33
framework/base/Module.php

@ -88,8 +88,7 @@ abstract class Module extends Component
{ {
if ($this->hasComponent($name)) { if ($this->hasComponent($name)) {
return $this->getComponent($name); return $this->getComponent($name);
} } else {
else {
return parent::__get($name); return parent::__get($name);
} }
} }
@ -105,8 +104,7 @@ abstract class Module extends Component
{ {
if ($this->hasComponent($name)) { if ($this->hasComponent($name)) {
return $this->getComponent($name) !== null; return $this->getComponent($name) !== null;
} } else {
else {
return parent::__isset($name); return parent::__isset($name);
} }
} }
@ -176,8 +174,7 @@ abstract class Module extends Component
{ {
if ($this->_modulePath !== null) { if ($this->_modulePath !== null) {
return $this->_modulePath; return $this->_modulePath;
} } else {
else {
return $this->_modulePath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'modules'; return $this->_modulePath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'modules';
} }
} }
@ -248,8 +245,7 @@ abstract class Module extends Component
{ {
if (isset($this->_modules[$id]) || array_key_exists($id, $this->_modules)) { if (isset($this->_modules[$id]) || array_key_exists($id, $this->_modules)) {
return $this->_modules[$id]; return $this->_modules[$id];
} } elseif (isset($this->_moduleConfig[$id]))
elseif (isset($this->_moduleConfig[$id]))
{ {
$config = $this->_moduleConfig[$id]; $config = $this->_moduleConfig[$id];
if (!isset($config['enabled']) || $config['enabled']) { if (!isset($config['enabled']) || $config['enabled']) {
@ -258,8 +254,7 @@ abstract class Module extends Component
unset($config['class'], $config['enabled']); unset($config['class'], $config['enabled']);
if ($this === \Yii::$app) { if ($this === \Yii::$app) {
$module = \Yii::createObject($class, $id, null, $config); $module = \Yii::createObject($class, $id, null, $config);
} } else
else
{ {
$module = \Yii::createObject($class, $this->getId() . '/' . $id, $this, $config); $module = \Yii::createObject($class, $this->getId() . '/' . $id, $this, $config);
} }
@ -328,8 +323,7 @@ abstract class Module extends Component
if (isset($this->_moduleConfig[$id])) { if (isset($this->_moduleConfig[$id])) {
$this->_moduleConfig[$id] = CMap::mergeArray($this->_moduleConfig[$id], $module); $this->_moduleConfig[$id] = CMap::mergeArray($this->_moduleConfig[$id], $module);
} } else
else
{ {
$this->_moduleConfig[$id] = $module; $this->_moduleConfig[$id] = $module;
} }
@ -358,8 +352,7 @@ abstract class Module extends Component
{ {
if (isset($this->_components[$id])) { if (isset($this->_components[$id])) {
return $this->_components[$id]; return $this->_components[$id];
} } elseif (isset($this->_componentConfig[$id]) && $createIfNull)
elseif (isset($this->_componentConfig[$id]) && $createIfNull)
{ {
$config = $this->_componentConfig[$id]; $config = $this->_componentConfig[$id];
if (!isset($config['enabled']) || $config['enabled']) { if (!isset($config['enabled']) || $config['enabled']) {
@ -383,8 +376,7 @@ abstract class Module extends Component
{ {
if ($component === null) { if ($component === null) {
unset($this->_components[$id]); unset($this->_components[$id]);
} } else {
else {
$this->_components[$id] = $component; $this->_components[$id] = $component;
if (!$component->getIsInitialized()) { if (!$component->getIsInitialized()) {
$component->init(); $component->init();
@ -404,8 +396,7 @@ abstract class Module extends Component
{ {
if ($loadedOnly) { if ($loadedOnly) {
return $this->_components; return $this->_components;
} } else {
else {
return array_merge($this->_componentConfig, $this->_components); return array_merge($this->_componentConfig, $this->_components);
} }
} }
@ -447,12 +438,10 @@ abstract class Module extends Component
{ {
if ($component instanceof IApplicationComponent) { if ($component instanceof IApplicationComponent) {
$this->setComponent($id, $component); $this->setComponent($id, $component);
} } elseif (isset($this->_componentConfig[$id]) && $merge)
elseif (isset($this->_componentConfig[$id]) && $merge)
{ {
$this->_componentConfig[$id] = CMap::mergeArray($this->_componentConfig[$id], $component); $this->_componentConfig[$id] = CMap::mergeArray($this->_componentConfig[$id], $component);
} } else
else
{ {
$this->_componentConfig[$id] = $component; $this->_componentConfig[$id] = $component;
} }

30
framework/base/Object.php

@ -85,8 +85,7 @@ class Object
$getter = 'get' . $name; $getter = 'get' . $name;
if (method_exists($this, $getter)) { if (method_exists($this, $getter)) {
return $this->$getter(); return $this->$getter();
} } else {
else {
throw new Exception('Getting unknown property: ' . get_class($this) . '.' . $name); throw new Exception('Getting unknown property: ' . get_class($this) . '.' . $name);
} }
} }
@ -106,11 +105,9 @@ class Object
$setter = 'set' . $name; $setter = 'set' . $name;
if (method_exists($this, $setter)) { if (method_exists($this, $setter)) {
$this->$setter($value); $this->$setter($value);
} } elseif (method_exists($this, 'get' . $name)) {
elseif (method_exists($this, 'get' . $name)) {
throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name); throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name);
} } else {
else {
throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name); throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name);
} }
} }
@ -130,8 +127,7 @@ class Object
$getter = 'get' . $name; $getter = 'get' . $name;
if (method_exists($this, $getter)) { // property is not null if (method_exists($this, $getter)) { // property is not null
return $this->$getter() !== null; return $this->$getter() !== null;
} } else {
else {
return false; return false;
} }
} }
@ -152,8 +148,7 @@ class Object
$setter = 'set' . $name; $setter = 'set' . $name;
if (method_exists($this, $setter)) { // write property if (method_exists($this, $setter)) { // write property
$this->$setter(null); $this->$setter(null);
} } elseif (method_exists($this, 'get' . $name)) {
elseif (method_exists($this, 'get' . $name)) {
throw new Exception('Unsetting read-only property: ' . get_class($this) . '.' . $name); throw new Exception('Unsetting read-only property: ' . get_class($this) . '.' . $name);
} }
} }
@ -254,8 +249,7 @@ class Object
if (is_string($_expression_)) { if (is_string($_expression_)) {
extract($_data_); extract($_data_);
return eval('return ' . $_expression_ . ';'); return eval('return ' . $_expression_ . ';');
} } else {
else {
$_data_[] = $this; $_data_[] = $this;
return call_user_func_array($_expression_, $_data_); return call_user_func_array($_expression_, $_data_);
} }
@ -321,17 +315,13 @@ class Object
if ($n === 0) { if ($n === 0) {
$object = new $class; $object = new $class;
} } elseif ($n === 1) {
elseif ($n === 1) {
$object = new $class($args[0]); $object = new $class($args[0]);
} } elseif ($n === 2) {
elseif ($n === 2) {
$object = new $class($args[0], $args[1]); $object = new $class($args[0], $args[1]);
} } elseif ($n === 3) {
elseif ($n === 3) {
$object = new $class($args[0], $args[1], $args[2]); $object = new $class($args[0], $args[1], $args[2]);
} } else {
else {
$r = new \ReflectionClass($class); $r = new \ReflectionClass($class);
$object = $r->newInstanceArgs($args); $object = $r->newInstanceArgs($args);
} }

33
framework/base/Vector.php

@ -103,11 +103,9 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{ {
if (isset($this->_d[$index])) { if (isset($this->_d[$index])) {
return $this->_d[$index]; return $this->_d[$index];
} } elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
return $this->_d[$index]; return $this->_d[$index];
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -136,12 +134,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{ {
if ($index === $this->_c) { if ($index === $this->_c) {
$this->_d[$this->_c++] = $item; $this->_d[$this->_c++] = $item;
} } elseif ($index >= 0 && $index < $this->_c) {
elseif ($index >= 0 && $index < $this->_c) {
array_splice($this->_d, $index, 0, array($item)); array_splice($this->_d, $index, 0, array($item));
$this->_c++; $this->_c++;
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -160,8 +156,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
if (($index = $this->indexOf($item)) >= 0) { if (($index = $this->indexOf($item)) >= 0) {
$this->removeAt($index); $this->removeAt($index);
return $index; return $index;
} } else {
else {
return false; return false;
} }
} }
@ -178,14 +173,12 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
$this->_c--; $this->_c--;
if ($index === $this->_c) { if ($index === $this->_c) {
return array_pop($this->_d); return array_pop($this->_d);
} } else {
else {
$item = $this->_d[$index]; $item = $this->_d[$index];
array_splice($this->_d, $index, 1); array_splice($this->_d, $index, 1);
return $item; return $item;
} }
} } else {
else {
throw new Exception('Index out of range: ' . $index); throw new Exception('Index out of range: ' . $index);
} }
} }
@ -202,8 +195,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
for ($i = $this->_c - 1; $i >= 0; --$i) { for ($i = $this->_c - 1; $i >= 0; --$i) {
$this->removeAt($i); $this->removeAt($i);
} }
} } else {
else {
$this->_d = array(); $this->_d = array();
$this->_c = 0; $this->_c = 0;
} }
@ -260,8 +252,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
foreach ($data as $item) { foreach ($data as $item) {
$this->add($item); $this->add($item);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); throw new Exception('Data must be either an array or an object implementing Traversable.');
} }
} }
@ -281,8 +272,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
foreach ($data as $item) { foreach ($data as $item) {
$this->add($item); $this->add($item);
} }
} } else {
else {
throw new Exception('Data must be either an array or an object implementing Traversable.'); throw new Exception('Data must be either an array or an object implementing Traversable.');
} }
} }
@ -328,8 +318,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
{ {
if ($offset === null || $offset === $this->_c) { if ($offset === null || $offset === $this->_c) {
$this->insertAt($this->_c, $item); $this->insertAt($this->_c, $item);
} } else {
else {
$this->removeAt($offset); $this->removeAt($offset);
$this->insertAt($offset, $item); $this->insertAt($offset, $item);
} }

15
framework/console/Command.php

@ -103,8 +103,7 @@ abstract class Command extends \yii\base\Component
$params[]=$options[$name]; $params[]=$options[$name];
else else
$this->usageError("Option --$name requires a scalar. Array is given."); $this->usageError("Option --$name requires a scalar. Array is given.");
} } else if($name==='args')
else if($name==='args')
$params[]=$args; $params[]=$args;
else if($param->isDefaultValueAvailable()) else if($param->isDefaultValueAvailable())
$params[]=$param->getDefaultValue(); $params[]=$param->getDefaultValue();
@ -183,11 +182,9 @@ abstract class Command extends \yii\base\Component
if(!is_array($options[$name])) if(!is_array($options[$name]))
$options[$name]=array($options[$name]); $options[$name]=array($options[$name]);
$options[$name][]=$value; $options[$name][]=$value;
} } else
else
$options[$name]=$value; $options[$name]=$value;
} } else if(isset($action))
else if(isset($action))
$params[]=$arg; $params[]=$arg;
else else
$action=$arg; $action=$arg;
@ -299,8 +296,7 @@ abstract class Command extends \yii\base\Component
ob_implicit_flush(false); ob_implicit_flush(false);
require($_viewFile_); require($_viewFile_);
return ob_get_clean(); return ob_get_clean();
} } else
else
require($_viewFile_); require($_viewFile_);
} }
@ -317,8 +313,7 @@ abstract class Command extends \yii\base\Component
$input = readline($message.' '); $input = readline($message.' ');
readline_add_history($input); readline_add_history($input);
return $input; return $input;
} } else
else
{ {
echo $message.' '; echo $message.' ';
return trim(fgets(STDIN)); return trim(fgets(STDIN));

12
framework/console/CommandRunner.php

@ -55,8 +55,7 @@ class CommandRunner extends \yii\base\Component
{ {
$name=$args[0]; $name=$args[0];
array_shift($args); array_shift($args);
} } else
else
$name='help'; $name='help';
if(($command=$this->createCommand($name))===null) if(($command=$this->createCommand($name))===null)
@ -126,15 +125,12 @@ class CommandRunner extends \yii\base\Component
$className=substr(basename($this->commands[$name]),0,-4); $className=substr(basename($this->commands[$name]),0,-4);
if(!class_exists($className,false)) if(!class_exists($className,false))
require_once($this->commands[$name]); require_once($this->commands[$name]);
} } else // an alias
else // an alias
$className=\Yii::import($this->commands[$name]); $className=\Yii::import($this->commands[$name]);
return new $className($name,$this); return new $className($name,$this);
} } else // an array configuration
else // an array configuration
return \Yii::create($this->commands[$name],$name,$this); return \Yii::create($this->commands[$name],$name,$this);
} } else if($name==='help')
else if($name==='help')
return new HelpCommand('help',$this); return new HelpCommand('help',$this);
else else
return null; return null;

6
framework/console/HelpCommand.php

@ -54,15 +54,13 @@ class HelpCommand extends Command
echo ' - '.implode("\n - ",$commandNames); echo ' - '.implode("\n - ",$commandNames);
echo "\n\nTo see individual command help, use the following:\n"; echo "\n\nTo see individual command help, use the following:\n";
echo " ".$runner->getScriptName()." help <command-name>\n"; echo " ".$runner->getScriptName()." help <command-name>\n";
} } else
else
{ {
echo "No available commands.\n"; echo "No available commands.\n";
echo "Please define them under the following directory:\n"; echo "Please define them under the following directory:\n";
echo "\t".\Yii::$app->getCommandPath()."\n"; echo "\t".\Yii::$app->getCommandPath()."\n";
} }
} } else
else
echo $runner->createCommand($name)->getHelp(); echo $runner->createCommand($name)->getHelp();
} }

63
framework/db/ar/ActiveRecord.php

@ -265,8 +265,7 @@ abstract class ActiveRecord extends \yii\base\Model
if ($exists) if ($exists)
$save = $this->_related[$name]; $save = $this->_related[$name];
$r = array($name => $params); $r = array($name => $params);
} } else
else
$r = $name; $r = $name;
unset($this->_related[$name]); unset($this->_related[$name]);
@ -291,8 +290,7 @@ abstract class ActiveRecord extends \yii\base\Model
else else
unset($this->_related[$name]); unset($this->_related[$name]);
return $results; return $results;
} } else
else
return $this->_related[$name]; return $this->_related[$name];
} }
@ -597,8 +595,7 @@ abstract class ActiveRecord extends \yii\base\Model
break; break;
} }
return $model->getAttributeLabel($name); return $model->getAttributeLabel($name);
} } else
else
return $this->generateAttributeLabel($attribute); return $this->generateAttributeLabel($attribute);
} }
@ -720,8 +717,7 @@ abstract class ActiveRecord extends \yii\base\Model
else else
$this->_related[$name][$index] = $record; $this->_related[$name][$index] = $record;
} }
} } elseif (!isset($this->_related[$name]))
elseif (!isset($this->_related[$name]))
$this->_related[$name] = $record; $this->_related[$name] = $record;
} }
@ -755,8 +751,7 @@ abstract class ActiveRecord extends \yii\base\Model
$attrs[$name] = isset($attributes[$name]) ? $attributes[$name] : null; $attrs[$name] = isset($attributes[$name]) ? $attributes[$name] : null;
} }
return $attrs; return $attrs;
} } else
else
return $attributes; return $attributes;
} }
@ -890,8 +885,7 @@ abstract class ActiveRecord extends \yii\base\Model
$event = new CModelEvent($this); $event = new CModelEvent($this);
$this->onBeforeSave($event); $this->onBeforeSave($event);
return $event->isValid; return $event->isValid;
} } else
else
return true; return true;
} }
@ -921,8 +915,7 @@ abstract class ActiveRecord extends \yii\base\Model
$event = new CModelEvent($this); $event = new CModelEvent($this);
$this->onBeforeDelete($event); $this->onBeforeDelete($event);
return $event->isValid; return $event->isValid;
} } else
else
return true; return true;
} }
@ -1063,8 +1056,7 @@ abstract class ActiveRecord extends \yii\base\Model
$this->_pk = $this->getPrimaryKey(); $this->_pk = $this->getPrimaryKey();
$this->afterSave(); $this->afterSave();
return true; return true;
} } else
else
return false; return false;
} }
@ -1105,11 +1097,9 @@ abstract class ActiveRecord extends \yii\base\Model
{ {
$this->_pk = $this->getPrimaryKey(); $this->_pk = $this->getPrimaryKey();
return true; return true;
} } else
else
return false; return false;
} } else
else
throw new CDbException(Yii::t('yii', 'The active record cannot be updated because it is new.')); throw new CDbException(Yii::t('yii', 'The active record cannot be updated because it is new.'));
} }
@ -1139,8 +1129,7 @@ abstract class ActiveRecord extends \yii\base\Model
foreach ($counters as $name => $value) foreach ($counters as $name => $value)
$this->$name = $this->$name + $value; $this->$name = $this->$name + $value;
return true; return true;
} } else
else
return false; return false;
} }
@ -1159,11 +1148,9 @@ abstract class ActiveRecord extends \yii\base\Model
$result = $this->deleteByPk($this->getPrimaryKey()) > 0; $result = $this->deleteByPk($this->getPrimaryKey()) > 0;
$this->afterDelete(); $this->afterDelete();
return $result; return $result;
} } else
else
return false; return false;
} } else
else
throw new CDbException(Yii::t('yii', 'The active record cannot be deleted because it is new.')); throw new CDbException(Yii::t('yii', 'The active record cannot be deleted because it is new.'));
} }
@ -1186,8 +1173,7 @@ abstract class ActiveRecord extends \yii\base\Model
$this->_attributes[$name] = $record->$name; $this->_attributes[$name] = $record->$name;
} }
return true; return true;
} } else
else
return false; return false;
} }
@ -1218,8 +1204,7 @@ abstract class ActiveRecord extends \yii\base\Model
foreach ($table->primaryKey as $name) foreach ($table->primaryKey as $name)
$values[$name] = $this->$name; $values[$name] = $this->$name;
return $values; return $values;
} } else
else
return null; return null;
} }
@ -1281,8 +1266,7 @@ abstract class ActiveRecord extends \yii\base\Model
$criteria->limit = 1; $criteria->limit = 1;
$command = $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria); $command = $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria);
return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow()); return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
} } else
else
{ {
$finder = new CActiveFinder($this, $criteria->with); $finder = new CActiveFinder($this, $criteria->with);
return $finder->query($criteria, $all); return $finder->query($criteria, $all);
@ -1314,14 +1298,12 @@ abstract class ActiveRecord extends \yii\base\Model
} }
$scope = $v; $scope = $v;
$params = array(); $params = array();
} } elseif (is_array($v))
elseif (is_array($v))
{ {
$scope = key($v); $scope = key($v);
$params = current($v); $params = current($v);
} }
} } elseif (is_string($k))
elseif (is_string($k))
{ {
$scope = $k; $scope = $k;
$params = $v; $params = $v;
@ -1481,8 +1463,7 @@ abstract class ActiveRecord extends \yii\base\Model
$this->_c = null; $this->_c = null;
$finder = new CActiveFinder($this, $criteria->with); $finder = new CActiveFinder($this, $criteria->with);
return $finder->findBySql($sql, $params); return $finder->findBySql($sql, $params);
} } else
else
{ {
$command = $this->getCommandBuilder()->createSqlCommand($sql, $params); $command = $this->getCommandBuilder()->createSqlCommand($sql, $params);
return $this->populateRecord($command->queryRow()); return $this->populateRecord($command->queryRow());
@ -1504,8 +1485,7 @@ abstract class ActiveRecord extends \yii\base\Model
$this->_c = null; $this->_c = null;
$finder = new CActiveFinder($this, $criteria->with); $finder = new CActiveFinder($this, $criteria->with);
return $finder->findAllBySql($sql, $params); return $finder->findAllBySql($sql, $params);
} } else
else
{ {
$command = $this->getCommandBuilder()->createSqlCommand($sql, $params); $command = $this->getCommandBuilder()->createSqlCommand($sql, $params);
return $this->populateRecords($command->queryAll()); return $this->populateRecords($command->queryAll());
@ -1795,8 +1775,7 @@ abstract class ActiveRecord extends \yii\base\Model
if ($callAfterFind) if ($callAfterFind)
$record->afterFind(); $record->afterFind();
return $record; return $record;
} } else
else
return null; return null;
} }

3
framework/db/dao/ColumnSchema.php

@ -94,8 +94,7 @@ class ColumnSchema extends \yii\base\Component
if (isset($typeMap[$this->type])) { if (isset($typeMap[$this->type])) {
if ($this->type === 'bigint') { if ($this->type === 'bigint') {
return PHP_INT_SIZE == 8 && !$this->unsigned ? 'integer' : 'string'; return PHP_INT_SIZE == 8 && !$this->unsigned ? 'integer' : 'string';
} } elseif ($this->type === 'integer') {
elseif ($this->type === 'integer') {
return PHP_INT_SIZE == 4 && $this->unsigned ? 'string' : 'integer'; return PHP_INT_SIZE == 4 && $this->unsigned ? 'string' : 'integer';
} }
return $typeMap[$this->type]; return $typeMap[$this->type];

38
framework/db/dao/Command.php

@ -44,6 +44,8 @@ use yii\db\Exception;
* ->queryRow(); * ->queryRow();
* ~~~ * ~~~
* *
* @property string $sql the SQL statement to be executed
*
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
@ -93,13 +95,11 @@ class Command extends \yii\base\Component
$this->connection = $connection; $this->connection = $connection;
if (is_object($query)) { if (is_object($query)) {
$this->query = $query; $this->query = $query;
} } else {
else {
$this->query = new Query; $this->query = new Query;
if (is_array($query)) { if (is_array($query)) {
$this->query->fromArray($query); $this->query->fromArray($query);
} } else {
else {
$this->_sql = $query; $this->_sql = $query;
} }
} }
@ -200,14 +200,11 @@ class Command extends \yii\base\Component
$this->prepare(); $this->prepare();
if ($dataType === null) { if ($dataType === null) {
$this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value))); $this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value)));
} } elseif ($length === null) {
elseif ($length === null) {
$this->pdoStatement->bindParam($name, $value, $dataType); $this->pdoStatement->bindParam($name, $value, $dataType);
} } elseif ($driverOptions === null) {
elseif ($driverOptions === null) {
$this->pdoStatement->bindParam($name, $value, $dataType, $length); $this->pdoStatement->bindParam($name, $value, $dataType, $length);
} } else {
else {
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions); $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
} }
$this->_params[$name] =& $value; $this->_params[$name] =& $value;
@ -230,8 +227,7 @@ class Command extends \yii\base\Component
$this->prepare(); $this->prepare();
if ($dataType === null) { if ($dataType === null) {
$this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value))); $this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value)));
} } else {
else {
$this->pdoStatement->bindValue($name, $value, $dataType); $this->pdoStatement->bindValue($name, $value, $dataType);
} }
$this->_params[$name] = $value; $this->_params[$name] = $value;
@ -270,8 +266,7 @@ class Command extends \yii\base\Component
$this->_params = array_merge($this->_params, $params); $this->_params = array_merge($this->_params, $params);
if ($this->_params === array()) { if ($this->_params === array()) {
$paramLog = ''; $paramLog = '';
} } else {
else {
$paramLog = "\nParameters: " . var_export($this->_params, true); $paramLog = "\nParameters: " . var_export($this->_params, true);
} }
@ -285,8 +280,7 @@ class Command extends \yii\base\Component
$this->prepare(); $this->prepare();
if ($params === array()) { if ($params === array()) {
$this->pdoStatement->execute(); $this->pdoStatement->execute();
} } else {
else {
$this->pdoStatement->execute($params); $this->pdoStatement->execute($params);
} }
$n = $this->pdoStatement->rowCount(); $n = $this->pdoStatement->rowCount();
@ -369,8 +363,7 @@ class Command extends \yii\base\Component
$result = $this->queryInternal('fetchColumn', $params); $result = $this->queryInternal('fetchColumn', $params);
if (is_resource($result) && get_resource_type($result) === 'stream') { if (is_resource($result) && get_resource_type($result) === 'stream') {
return stream_get_contents($result); return stream_get_contents($result);
} } else {
else {
return $result; return $result;
} }
} }
@ -408,8 +401,7 @@ class Command extends \yii\base\Component
$this->_params = array_merge($this->_params, $params); $this->_params = array_merge($this->_params, $params);
if ($this->_params === array()) { if ($this->_params === array()) {
$paramLog = ''; $paramLog = '';
} } else {
else {
$paramLog = "\nParameters: " . var_export($this->_params, true); $paramLog = "\nParameters: " . var_export($this->_params, true);
} }
@ -436,15 +428,13 @@ class Command extends \yii\base\Component
$this->prepare(); $this->prepare();
if ($params === array()) { if ($params === array()) {
$this->pdoStatement->execute(); $this->pdoStatement->execute();
} } else {
else {
$this->pdoStatement->execute($params); $this->pdoStatement->execute($params);
} }
if ($method === '') { if ($method === '') {
$result = new DataReader($this); $result = new DataReader($this);
} } else {
else {
if ($fetchMode === null) { if ($fetchMode === null) {
$fetchMode = $this->fetchMode; $fetchMode = $this->fetchMode;
} }

27
framework/db/dao/Connection.php

@ -84,6 +84,15 @@ use yii\db\Exception;
* ) * )
* ~~~ * ~~~
* *
* @property boolean $active Whether the DB connection is established.
* @property Transaction $currentTransaction The currently active transaction. Null if no active transaction.
* @property Schema $schema The database schema for the current connection.
* @property QueryBuilder $queryBuilder The query builder.
* @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object.
* @property string $driverName Name of the DB driver currently being used.
* @property string $clientVersion The version information of the DB driver.
* @property array $stats The statistical results of SQL executions.
*
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
@ -428,8 +437,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if ($this->_transaction !== null && $this->_transaction->active) { if ($this->_transaction !== null && $this->_transaction->active) {
return $this->_transaction; return $this->_transaction;
} } else {
else {
return null; return null;
} }
} }
@ -454,13 +462,11 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if ($this->_schema !== null) { if ($this->_schema !== null) {
return $this->_schema; return $this->_schema;
} } else {
else {
$driver = $this->getDriverName(); $driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) { if (isset($this->schemaMap[$driver])) {
return $this->_schema = \Yii::createObject($this->schemaMap[$driver], $this); return $this->_schema = \Yii::createObject($this->schemaMap[$driver], $this);
} } else {
else {
throw new Exception("Connection does not support reading schema for '$driver' database."); throw new Exception("Connection does not support reading schema for '$driver' database.");
} }
} }
@ -503,8 +509,7 @@ class Connection extends \yii\base\ApplicationComponent
$this->open(); $this->open();
if (($value = $this->pdo->quote($str)) !== false) { if (($value = $this->pdo->quote($str)) !== false) {
return $value; return $value;
} } else { // the driver doesn't support quote (e.g. oci)
else { // the driver doesn't support quote (e.g. oci)
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
} }
} }
@ -546,8 +551,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if ($this->tablePrefix !== null && strpos($sql, '{{') !== false) { if ($this->tablePrefix !== null && strpos($sql, '{{') !== false) {
return preg_replace('/{{(.*?)}}/', $this->tablePrefix . '\1', $sql); return preg_replace('/{{(.*?)}}/', $this->tablePrefix . '\1', $sql);
} } else {
else {
return $sql; return $sql;
} }
} }
@ -577,8 +581,7 @@ class Connection extends \yii\base\ApplicationComponent
{ {
if (($pos = strpos($this->dsn, ':')) !== false) { if (($pos = strpos($this->dsn, ':')) !== false) {
return strtolower(substr($this->dsn, 0, $pos)); return strtolower(substr($this->dsn, 0, $pos));
} } else {
else {
return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME)); return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME));
} }
} }

6
framework/db/dao/DataReader.php

@ -70,8 +70,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
{ {
if ($dataType === null) { if ($dataType === null) {
$this->_statement->bindColumn($column, $value); $this->_statement->bindColumn($column, $value);
} } else {
else {
$this->_statement->bindColumn($column, $value, $dataType); $this->_statement->bindColumn($column, $value, $dataType);
} }
} }
@ -204,8 +203,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable
if ($this->_index < 0) { if ($this->_index < 0) {
$this->_row = $this->_statement->fetch(); $this->_row = $this->_statement->fetch();
$this->_index = 0; $this->_index = 0;
} } else {
else {
throw new Exception('DataReader cannot rewind. It is a forward-only reader.'); throw new Exception('DataReader cannot rewind. It is a forward-only reader.');
} }
} }

63
framework/db/dao/Query.php

@ -87,8 +87,7 @@ class Query extends \yii\base\Object
foreach ($params as $name => $value) { foreach ($params as $name => $value) {
if (is_integer($name)) { if (is_integer($name)) {
$this->params[] = $value; $this->params[] = $value;
} } else {
else {
$this->params[$name] = $value; $this->params[$name] = $value;
} }
} }
@ -104,8 +103,7 @@ class Query extends \yii\base\Object
if ($this->select !== $query->select) { if ($this->select !== $query->select) {
if ($this->select === '*') { if ($this->select === '*') {
$this->select = $query->select; $this->select = $query->select;
} } elseif ($query->select !== '*') {
elseif ($query->select !== '*') {
$select1 = is_string($this->select) ? preg_split('/\s*,\s*/', trim($this->select), -1, PREG_SPLIT_NO_EMPTY) : $this->select; $select1 = is_string($this->select) ? preg_split('/\s*,\s*/', trim($this->select), -1, PREG_SPLIT_NO_EMPTY) : $this->select;
$select2 = is_string($query->select) ? preg_split('/\s*,\s*/', trim($query->select), -1, PREG_SPLIT_NO_EMPTY) : $query->select; $select2 = is_string($query->select) ? preg_split('/\s*,\s*/', trim($query->select), -1, PREG_SPLIT_NO_EMPTY) : $query->select;
$this->select = array_merge($select1, array_diff($select2, $select1)); $this->select = array_merge($select1, array_diff($select2, $select1));
@ -115,8 +113,7 @@ class Query extends \yii\base\Object
if ($this->selectOption !== $query->selectOption) { if ($this->selectOption !== $query->selectOption) {
if ($this->selectOption === null) { if ($this->selectOption === null) {
$this->selectOption = $query->selectOption; $this->selectOption = $query->selectOption;
} } elseif ($query->selectOption !== null) {
elseif ($query->selectOption !== null) {
$this->selectOption .= ' ' . $query->selectOption; $this->selectOption .= ' ' . $query->selectOption;
} }
} }
@ -128,8 +125,7 @@ class Query extends \yii\base\Object
if ($this->where !== $query->where) { if ($this->where !== $query->where) {
if (empty($this->where)) { if (empty($this->where)) {
$this->where = $query->where; $this->where = $query->where;
} } elseif (!empty($query->where)) {
elseif (!empty($query->where)) {
$this->where = array('AND', $this->where, $query->where); $this->where = array('AND', $this->where, $query->where);
} }
} }
@ -149,15 +145,13 @@ class Query extends \yii\base\Object
if ($this->orderBy !== $query->orderBy) { if ($this->orderBy !== $query->orderBy) {
if (empty($this->orderBy)) { if (empty($this->orderBy)) {
$this->orderBy = $query->orderBy; $this->orderBy = $query->orderBy;
} } elseif (!empty($query->orderBy)) {
elseif (!empty($query->orderBy)) {
if (!is_array($this->orderBy)) { if (!is_array($this->orderBy)) {
$this->orderBy = array($this->orderBy); $this->orderBy = array($this->orderBy);
} }
if (is_array($query->orderBy)) { if (is_array($query->orderBy)) {
$this->orderBy = array_merge($this->orderBy, $query->orderBy); $this->orderBy = array_merge($this->orderBy, $query->orderBy);
} } else {
else {
$this->orderBy[] = $query->orderBy; $this->orderBy[] = $query->orderBy;
} }
} }
@ -166,15 +160,13 @@ class Query extends \yii\base\Object
if ($this->groupBy !== $query->groupBy) { if ($this->groupBy !== $query->groupBy) {
if (empty($this->groupBy)) { if (empty($this->groupBy)) {
$this->groupBy = $query->groupBy; $this->groupBy = $query->groupBy;
} } elseif (!empty($query->groupBy)) {
elseif (!empty($query->groupBy)) {
if (!is_array($this->groupBy)) { if (!is_array($this->groupBy)) {
$this->groupBy = array($this->groupBy); $this->groupBy = array($this->groupBy);
} }
if (is_array($query->groupBy)) { if (is_array($query->groupBy)) {
$this->groupBy = array_merge($this->groupBy, $query->groupBy); $this->groupBy = array_merge($this->groupBy, $query->groupBy);
} } else {
else {
$this->groupBy[] = $query->groupBy; $this->groupBy[] = $query->groupBy;
} }
} }
@ -183,15 +175,13 @@ class Query extends \yii\base\Object
if ($this->join !== $query->join) { if ($this->join !== $query->join) {
if (empty($this->join)) { if (empty($this->join)) {
$this->join = $query->join; $this->join = $query->join;
} } elseif (!empty($query->join)) {
elseif (!empty($query->join)) {
if (!is_array($this->join)) { if (!is_array($this->join)) {
$this->join = array($this->join); $this->join = array($this->join);
} }
if (is_array($query->join)) { if (is_array($query->join)) {
$this->join = array_merge($this->join, $query->join); $this->join = array_merge($this->join, $query->join);
} } else {
else {
$this->join[] = $query->join; $this->join[] = $query->join;
} }
} }
@ -200,8 +190,7 @@ class Query extends \yii\base\Object
if ($this->having !== $query->having) { if ($this->having !== $query->having) {
if (empty($this->having)) { if (empty($this->having)) {
$this->having = $query->having; $this->having = $query->having;
} } elseif (!empty($query->having)) {
elseif (!empty($query->having)) {
$this->having = array('AND', $this->having, $query->having); $this->having = array('AND', $this->having, $query->having);
} }
} }
@ -209,15 +198,13 @@ class Query extends \yii\base\Object
if ($this->union !== $query->union) { if ($this->union !== $query->union) {
if (empty($this->union)) { if (empty($this->union)) {
$this->union = $query->union; $this->union = $query->union;
} } elseif (!empty($query->union)) {
elseif (!empty($query->union)) {
if (!is_array($this->union)) { if (!is_array($this->union)) {
$this->union = array($this->union); $this->union = array($this->union);
} }
if (is_array($query->union)) { if (is_array($query->union)) {
$this->union = array_merge($this->union, $query->union); $this->union = array_merge($this->union, $query->union);
} } else {
else {
$this->union[] = $query->union; $this->union[] = $query->union;
} }
} }
@ -246,8 +233,7 @@ class Query extends \yii\base\Object
} }
if ($this->condition === '') { if ($this->condition === '') {
$this->condition = $condition; $this->condition = $condition;
} } else
else
{ {
$this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')'; $this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')';
} }
@ -309,8 +295,7 @@ class Query extends \yii\base\Object
} }
$condition = $column . '=' . self::PARAM_PREFIX . self::$paramCount; $condition = $column . '=' . self::PARAM_PREFIX . self::$paramCount;
$this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value;
} } else
else
{ {
$params = array(); $params = array();
foreach ($values as $value) foreach ($values as $value)
@ -347,8 +332,7 @@ class Query extends \yii\base\Object
} }
$condition = $column . '!=' . self::PARAM_PREFIX . self::$paramCount; $condition = $column . '!=' . self::PARAM_PREFIX . self::$paramCount;
$this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value;
} } else
else
{ {
$params = array(); $params = array();
foreach ($values as $value) foreach ($values as $value)
@ -379,8 +363,7 @@ class Query extends \yii\base\Object
{ {
if ($value === null) { if ($value === null) {
$params[] = $name . ' IS NULL'; $params[] = $name . ' IS NULL';
} } else
else
{ {
$params[] = $name . '=' . self::PARAM_PREFIX . self::$paramCount; $params[] = $name . '=' . self::PARAM_PREFIX . self::$paramCount;
$this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value;
@ -439,8 +422,7 @@ class Query extends \yii\base\Object
return $this; return $this;
} }
return $this->addInCondition($column, $value, $operator); return $this->addInCondition($column, $value, $operator);
} } else
else
{ {
$value = "$value"; $value = "$value";
} }
@ -448,8 +430,7 @@ class Query extends \yii\base\Object
if (preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/', $value, $matches)) { if (preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/', $value, $matches)) {
$value = $matches[2]; $value = $matches[2];
$op = $matches[1]; $op = $matches[1];
} } else
else
{ {
$op = ''; $op = '';
} }
@ -465,8 +446,7 @@ class Query extends \yii\base\Object
if ($op === '<>') { if ($op === '<>') {
return $this->addSearchCondition($column, $value, $escape, $operator, 'NOT LIKE'); return $this->addSearchCondition($column, $value, $escape, $operator, 'NOT LIKE');
} }
} } elseif ($op === '')
elseif ($op === '')
{ {
$op = '='; $op = '=';
} }
@ -506,8 +486,7 @@ class Query extends \yii\base\Object
if ($this->condition === '') { if ($this->condition === '') {
$this->condition = $condition; $this->condition = $condition;
} } else
else
{ {
$this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')'; $this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')';
} }

51
framework/db/dao/QueryBuilder.php

@ -88,8 +88,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($value->params as $n => $v) { foreach ($value->params as $n => $v) {
$params[$n] = $v; $params[$n] = $v;
} }
} } else {
else {
$placeholders[] = ':p' . $count; $placeholders[] = ':p' . $count;
$params[':p' . $count] = $value; $params[':p' . $count] = $value;
$count++; $count++;
@ -121,8 +120,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($value->params as $n => $v) { foreach ($value->params as $n => $v) {
$params[$n] = $v; $params[$n] = $v;
} }
} } else {
else {
$lines[] = $this->schema->quoteSimpleColumnName($name) . '=:p' . $count; $lines[] = $this->schema->quoteSimpleColumnName($name) . '=:p' . $count;
$params[':p' . $count] = $value; $params[':p' . $count] = $value;
$count++; $count++;
@ -175,8 +173,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($columns as $name => $type) { foreach ($columns as $name => $type) {
if (is_string($name)) { if (is_string($name)) {
$cols[] = "\t" . $this->schema->quoteColumnName($name) . ' ' . $this->schema->getColumnType($type); $cols[] = "\t" . $this->schema->quoteColumnName($name) . ' ' . $this->schema->getColumnType($type);
} } else
else
{ {
$cols[] = "\t" . $type; $cols[] = "\t" . $type;
} }
@ -340,8 +337,7 @@ class QueryBuilder extends \yii\base\Object
{ {
if (strpos($col, '(') !== false) { if (strpos($col, '(') !== false) {
$cols[] = $col; $cols[] = $col;
} } else
else
{ {
$cols[] = $this->schema->quoteColumnName($col); $cols[] = $this->schema->quoteColumnName($col);
} }
@ -413,12 +409,10 @@ class QueryBuilder extends \yii\base\Object
{ {
if (isset($this->typeMap[$type])) { if (isset($this->typeMap[$type])) {
return $this->typeMap[$type]; return $this->typeMap[$type];
} } elseif (($pos = strpos($type, ' ')) !== false) {
elseif (($pos = strpos($type, ' ')) !== false) {
$t = substr($type, 0, $pos); $t = substr($type, 0, $pos);
return (isset($this->typeMap[$t]) ? $this->typeMap[$t] : $t) . substr($type, $pos); return (isset($this->typeMap[$t]) ? $this->typeMap[$t] : $t) . substr($type, $pos);
} } else {
else {
return $type; return $type;
} }
} }
@ -445,12 +439,10 @@ class QueryBuilder extends \yii\base\Object
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
if (is_object($column)) { if (is_object($column)) {
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} } elseif (strpos($column, '(') === false) {
elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) { if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) {
$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->connection->quoteSimpleColumnName($matches[2]); $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->connection->quoteSimpleColumnName($matches[2]);
} } else {
else {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->connection->quoteColumnName($column);
} }
} }
@ -473,8 +465,7 @@ class QueryBuilder extends \yii\base\Object
if (strpos($table, '(') === false) { if (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
$tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); $tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
} } else {
else {
$tables[$i] = $this->connection->quoteTableName($table); $tables[$i] = $this->connection->quoteTableName($table);
} }
} }
@ -500,8 +491,7 @@ class QueryBuilder extends \yii\base\Object
if (strpos($table, '(') === false) { if (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
$table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); $table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
} } else {
else {
$table = $this->connection->quoteTableName($table); $table = $this->connection->quoteTableName($table);
} }
} }
@ -510,8 +500,7 @@ class QueryBuilder extends \yii\base\Object
$condition = $this->buildCondition($join[2]); $condition = $this->buildCondition($join[2]);
$joins[$i] .= ' ON ' . $condition; $joins[$i] .= ' ON ' . $condition;
} }
} } else {
else {
throw new Exception('The join clause may be specified as an array of at least two elements.'); throw new Exception('The join clause may be specified as an array of at least two elements.');
} }
} }
@ -542,8 +531,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
if (is_object($column)) { if (is_object($column)) {
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} } elseif (strpos($column, '(') === false) {
elseif (strpos($column, '(') === false) {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->connection->quoteColumnName($column);
} }
} }
@ -572,12 +560,10 @@ class QueryBuilder extends \yii\base\Object
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
if (is_object($column)) { if (is_object($column)) {
$columns[$i] = (string)$column; $columns[$i] = (string)$column;
} } elseif (strpos($column, '(') === false) {
elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) { if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
$columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . strtoupper($matches[2]); $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . strtoupper($matches[2]);
} } else {
else {
$columns[$i] = $this->connection->quoteColumnName($column); $columns[$i] = $this->connection->quoteColumnName($column);
} }
} }
@ -618,8 +604,7 @@ class QueryBuilder extends \yii\base\Object
{ {
if (!is_array($conditions)) { if (!is_array($conditions)) {
return $conditions; return $conditions;
} } elseif ($conditions === array()) {
elseif ($conditions === array()) {
return ''; return '';
} }
@ -657,8 +642,7 @@ class QueryBuilder extends \yii\base\Object
foreach ($values as $i => $value) { foreach ($values as $i => $value) {
if (is_string($value)) { if (is_string($value)) {
$values[$i] = $this->connection->quoteValue($value); $values[$i] = $this->connection->quoteValue($value);
} } else {
else {
$values[$i] = (string)$value; $values[$i] = (string)$value;
} }
} }
@ -672,8 +656,7 @@ class QueryBuilder extends \yii\base\Object
if ($operator === 'LIKE' || $operator === 'NOT LIKE') { if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
$andor = ' AND '; $andor = ' AND ';
} } else {
else {
$andor = ' OR '; $andor = ' OR ';
$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE'; $operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
} }

9
framework/db/dao/Schema.php

@ -58,8 +58,7 @@ abstract class Schema extends \yii\base\Object
if (strpos($name, '{{') !== false) { if (strpos($name, '{{') !== false) {
$realName = preg_replace('/\{\{(.*?)\}\}/', $this->connection->tablePrefix . '$1', $name); $realName = preg_replace('/\{\{(.*?)\}\}/', $this->connection->tablePrefix . '$1', $name);
} } else {
else {
$realName = $name; $realName = $name;
} }
@ -80,8 +79,7 @@ abstract class Schema extends \yii\base\Object
} }
} }
$this->_tables[$name] = $table; $this->_tables[$name] = $table;
} } else {
else {
$this->_tables[$name] = $table = $this->loadTableSchema($realName); $this->_tables[$name] = $table = $this->loadTableSchema($realName);
} }
@ -195,8 +193,7 @@ abstract class Schema extends \yii\base\Object
if (($pos = strrpos($name, '.')) !== false) { if (($pos = strrpos($name, '.')) !== false) {
$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.'; $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1); $name = substr($name, $pos + 1);
} } else
else
{ {
$prefix = ''; $prefix = '';
} }

6
framework/db/dao/Transaction.php

@ -69,8 +69,7 @@ class Transaction extends \yii\base\Object
\Yii::trace('Committing transaction', __CLASS__); \Yii::trace('Committing transaction', __CLASS__);
$this->connection->pdo->commit(); $this->connection->pdo->commit();
$this->active = false; $this->active = false;
} } else {
else {
throw new Exception('Failed to commit transaction: transaction was inactive.'); throw new Exception('Failed to commit transaction: transaction was inactive.');
} }
} }
@ -85,8 +84,7 @@ class Transaction extends \yii\base\Object
\Yii::trace('Rolling back transaction', __CLASS__); \Yii::trace('Rolling back transaction', __CLASS__);
$this->connection->pdo->rollBack(); $this->connection->pdo->rollBack();
$this->active = false; $this->active = false;
} } else {
else {
throw new Exception('Failed to roll back transaction: transaction was inactive.'); throw new Exception('Failed to roll back transaction: transaction was inactive.');
} }
} }

12
framework/db/dao/mysql/ColumnSchema.php

@ -69,8 +69,7 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema
$values[$i] = trim($value, "'"); $values[$i] = trim($value, "'");
} }
$this->enumValues = $values; $this->enumValues = $values;
} } else {
else {
$values = explode(',', $matches[2]); $values = explode(',', $matches[2]);
$this->size = $this->precision = (int)$values[0]; $this->size = $this->precision = (int)$values[0];
if (isset($values[1])) { if (isset($values[1])) {
@ -78,12 +77,10 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema
} }
if ($this->size === 1 && ($type === 'tinyint' || $type === 'bit')) { if ($this->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
$this->type = 'boolean'; $this->type = 'boolean';
} } elseif ($type === 'bit') {
elseif ($type === 'bit') {
if ($this->size > 32) { if ($this->size > 32) {
$this->type = 'bigint'; $this->type = 'bigint';
} } elseif ($this->size === 32) {
elseif ($this->size === 32) {
$this->type = 'integer'; $this->type = 'integer';
} }
} }
@ -103,8 +100,7 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema
{ {
if ($this->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') { if ($this->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
$this->defaultValue = null; $this->defaultValue = null;
} } else {
else {
$this->defaultValue = $this->typecast($defaultValue); $this->defaultValue = $this->typecast($defaultValue);
} }
} }

3
framework/db/dao/mysql/QueryBuilder.php

@ -54,8 +54,7 @@ class QueryBuilder extends \yii\db\dao\QueryBuilder
throw new CDbException(Yii::t('yii', 'Unable to find "{column}" in table "{table}".', array('{column}' => $name, '{table}' => $table))); throw new CDbException(Yii::t('yii', 'Unable to find "{column}" in table "{table}".', array('{column}' => $name, '{table}' => $table)));
if (isset($row['Create Table'])) { if (isset($row['Create Table'])) {
$sql = $row['Create Table']; $sql = $row['Create Table'];
} } else {
else {
$row = array_values($row); $row = array_values($row);
$sql = $row[1]; $sql = $row[1];
} }

9
framework/db/dao/mysql/Schema.php

@ -68,8 +68,7 @@ class Schema extends \yii\db\dao\Schema
$table->schemaName = $parts[0]; $table->schemaName = $parts[0];
$table->name = $parts[1]; $table->name = $parts[1];
$table->quotedName = $this->quoteSimpleTableName($table->schemaName) . '.' . $this->quoteSimpleTableName($table->name); $table->quotedName = $this->quoteSimpleTableName($table->schemaName) . '.' . $this->quoteSimpleTableName($table->name);
} } else {
else {
$table->name = $parts[0]; $table->name = $parts[0];
$table->quotedName = $this->quoteSimpleTableName($table->name); $table->quotedName = $this->quoteSimpleTableName($table->name);
} }
@ -114,11 +113,9 @@ class Schema extends \yii\db\dao\Schema
if ($c->isPrimaryKey) { if ($c->isPrimaryKey) {
if ($table->primaryKey === null) { if ($table->primaryKey === null) {
$table->primaryKey = $c->name; $table->primaryKey = $c->name;
} } elseif (is_string($table->primaryKey)) {
elseif (is_string($table->primaryKey)) {
$table->primaryKey = array($table->primaryKey, $c->name); $table->primaryKey = array($table->primaryKey, $c->name);
} } else {
else {
$table->primaryKey[] = $c->name; $table->primaryKey[] = $c->name;
} }
if ($c->autoIncrement) { if ($c->autoIncrement) {

9
framework/logging/ProfileTarget.php

@ -107,8 +107,7 @@ class CProfileLogRoute extends CWebLogRoute
if (($last = array_pop($stack)) !== null && $last[0] === $token) { if (($last = array_pop($stack)) !== null && $last[0] === $token) {
$delta = $log[3] - $last[3]; $delta = $log[3] - $last[3];
$results[$last[4]] = array($token, $delta, count($stack)); $results[$last[4]] = array($token, $delta, count($stack));
} } else
else
{ {
throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
array('{token}' => $token))); array('{token}' => $token)));
@ -140,8 +139,7 @@ class CProfileLogRoute extends CWebLogRoute
{ {
$log[0] = substr($message, 6); $log[0] = substr($message, 6);
$stack[] = $log; $stack[] = $log;
} } elseif (!strncasecmp($message, 'end:', 4))
elseif (!strncasecmp($message, 'end:', 4))
{ {
$token = substr($message, 4); $token = substr($message, 4);
if (($last = array_pop($stack)) !== null && $last[0] === $token) if (($last = array_pop($stack)) !== null && $last[0] === $token)
@ -153,8 +151,7 @@ class CProfileLogRoute extends CWebLogRoute
$results[$token] = $this->aggregateResult($results[$token], $delta); $results[$token] = $this->aggregateResult($results[$token], $delta);
else else
$results[$token] = array($token, 1, $delta, $delta, $delta); $results[$token] = array($token, 1, $delta, $delta, $delta);
} } else
else
throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
array('{token}' => $token))); array('{token}' => $token)));
} }

3
framework/logging/Router.php

@ -108,8 +108,7 @@ class Router extends \yii\base\ApplicationComponent
foreach ($config as $name => $target) { foreach ($config as $name => $target) {
if ($target instanceof Target) { if ($target instanceof Target) {
$this->_targets[$name] = $target; $this->_targets[$name] = $target;
} } else {
else {
$this->_targets[$name] = \Yii::createObject($target); $this->_targets[$name] = \Yii::createObject($target);
} }
} }

3
framework/logging/WebTarget.php

@ -55,8 +55,7 @@ class CWebLogRoute extends CLogRoute
if ($isAjax && $this->ignoreAjaxInFireBug) if ($isAjax && $this->ignoreAjaxInFireBug)
return; return;
$view .= '-firebug'; $view .= '-firebug';
} } elseif (!($app instanceof CWebApplication) || $isAjax)
elseif (!($app instanceof CWebApplication) || $isAjax)
return; return;
$viewFile = YII_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view . '.php'; $viewFile = YII_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view . '.php';

6
framework/util/File.php

@ -79,15 +79,13 @@ class File
{ {
echo " overwrite $name\n"; echo " overwrite $name\n";
$overwriteAll=true; $overwriteAll=true;
} } else
else
{ {
echo " skip $name\n"; echo " skip $name\n";
continue; continue;
} }
} }
} } else
else
{ {
$this->ensureDirectory(dirname($target)); $this->ensureDirectory(dirname($target));
echo " generate $name\n"; echo " generate $name\n";

3
framework/validators/CaptchaValidator.php

@ -66,8 +66,7 @@ class CaptchaValidator extends Validator
list($controller, $actionID) = $ca; list($controller, $actionID) = $ca;
$action = $controller->createAction($actionID); $action = $controller->createAction($actionID);
} }
} } else {
else {
$action = Yii::app()->getController()->createAction($this->captchaAction); $action = Yii::app()->getController()->createAction($this->captchaAction);
} }

6
framework/validators/CompareValidator.php

@ -77,8 +77,7 @@ class CompareValidator extends Validator
} }
if ($this->compareValue !== null) { if ($this->compareValue !== null) {
$compareTo = $compareValue = $this->compareValue; $compareTo = $compareValue = $this->compareValue;
} } else {
else {
$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
$compareValue = $object->$compareAttribute; $compareValue = $object->$compareAttribute;
$compareTo = $object->getAttributeLabel($compareAttribute); $compareTo = $object->getAttributeLabel($compareAttribute);
@ -138,8 +137,7 @@ class CompareValidator extends Validator
if ($this->compareValue !== null) { if ($this->compareValue !== null) {
$compareTo = $this->compareValue; $compareTo = $this->compareValue;
$compareValue = json_encode($this->compareValue); $compareValue = json_encode($this->compareValue);
} } else {
else {
$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
$compareValue = "\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()"; $compareValue = "\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()";
$compareTo = $object->getAttributeLabel($compareAttribute); $compareTo = $object->getAttributeLabel($compareAttribute);

9
framework/validators/FileValidator.php

@ -117,12 +117,10 @@ class CFileValidator extends Validator
{ {
$message = $this->tooMany !== null ? $this->tooMany : Yii::t('yii', '{attribute} cannot accept more than {limit} files.'); $message = $this->tooMany !== null ? $this->tooMany : Yii::t('yii', '{attribute} cannot accept more than {limit} files.');
$this->addError($object, $attribute, $message, array('{attribute}' => $attribute, '{limit}' => $this->maxFiles)); $this->addError($object, $attribute, $message, array('{attribute}' => $attribute, '{limit}' => $this->maxFiles));
} } else
else
foreach ($files as $file) foreach ($files as $file)
$this->validateFile($object, $attribute, $file); $this->validateFile($object, $attribute, $file);
} } else
else
{ {
$file = $object->$attribute; $file = $object->$attribute;
if (!$file instanceof CUploadedFile) if (!$file instanceof CUploadedFile)
@ -149,8 +147,7 @@ class CFileValidator extends Validator
{ {
$message = $this->tooLarge !== null ? $this->tooLarge : Yii::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.'); $message = $this->tooLarge !== null ? $this->tooLarge : Yii::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.');
$this->addError($object, $attribute, $message, array('{file}' => $file->getName(), '{limit}' => $this->getSizeLimit())); $this->addError($object, $attribute, $message, array('{file}' => $file->getName(), '{limit}' => $this->getSizeLimit()));
} } elseif ($error == UPLOAD_ERR_PARTIAL)
elseif ($error == UPLOAD_ERR_PARTIAL)
throw new CException(Yii::t('yii', 'The file "{file}" was only partially uploaded.', array('{file}' => $file->getName()))); throw new CException(Yii::t('yii', 'The file "{file}" was only partially uploaded.', array('{file}' => $file->getName())));
elseif ($error == UPLOAD_ERR_NO_TMP_DIR) elseif ($error == UPLOAD_ERR_NO_TMP_DIR)
throw new CException(Yii::t('yii', 'Missing the temporary folder to store the uploaded file "{file}".', array('{file}' => $file->getName()))); throw new CException(Yii::t('yii', 'Missing the temporary folder to store the uploaded file "{file}".', array('{file}' => $file->getName())));

3
framework/validators/RangeValidator.php

@ -58,8 +58,7 @@ class RangeValidator extends Validator
if (!$this->not && !in_array($value, $this->range, $this->strict)) { if (!$this->not && !in_array($value, $this->range, $this->strict)) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should be in the list.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should be in the list.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} } elseif ($this->not && in_array($value, $this->range, $this->strict)) {
elseif ($this->not && in_array($value, $this->range, $this->strict)) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should NOT be in the list.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should NOT be in the list.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }

3
framework/validators/RegularExpressionValidator.php

@ -80,8 +80,7 @@ class RegularExpressionValidator extends Validator
$flag = substr($pattern, $endpos + 1); $flag = substr($pattern, $endpos + 1);
if ($delim !== '/') { if ($delim !== '/') {
$pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $endpos - 1)) . '/'; $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $endpos - 1)) . '/';
} } else {
else {
$pattern = substr($pattern, 0, $endpos + 1); $pattern = substr($pattern, 0, $endpos + 1);
} }
if (!empty($flag)) { if (!empty($flag)) {

6
framework/validators/RequiredValidator.php

@ -50,8 +50,7 @@ class RequiredValidator extends Validator
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} cannot be blank.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} cannot be blank.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
} } else {
else {
if (!$this->strict && $value != $this->requiredValue || $this->strict && $value !== $this->requiredValue) { if (!$this->strict && $value != $this->requiredValue || $this->strict && $value !== $this->requiredValue) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be "{requiredValue}".', $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be "{requiredValue}".',
array('{requiredValue}' => $this->requiredValue)); array('{requiredValue}' => $this->requiredValue));
@ -83,8 +82,7 @@ if (value != " . json_encode($this->requiredValue) . ") {
messages.push(" . json_encode($message) . "); messages.push(" . json_encode($message) . ");
} }
"; ";
} } else {
else {
if ($message === null) { if ($message === null) {
$message = Yii::t('yii', '{attribute} cannot be blank.'); $message = Yii::t('yii', '{attribute} cannot be blank.');
} }

3
framework/validators/StringValidator.php

@ -83,8 +83,7 @@ class StringValidator extends Validator
if (function_exists('mb_strlen') && $this->encoding !== false) { if (function_exists('mb_strlen') && $this->encoding !== false) {
$length = mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset); $length = mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
} } else {
else {
$length = strlen($value); $length = strlen($value);
} }

3
framework/validators/UniqueValidator.php

@ -104,8 +104,7 @@ class CUniqueValidator extends Validator
// non-primary key, need to exclude the current record based on PK // non-primary key, need to exclude the current record based on PK
$exists = array_shift($objects)->getPrimaryKey() != $object->getOldPrimaryKey(); $exists = array_shift($objects)->getPrimaryKey() != $object->getOldPrimaryKey();
} }
} } else
else
$exists = $n > 1; $exists = $n > 1;
} }

6
framework/validators/UrlValidator.php

@ -54,8 +54,7 @@ class UrlValidator extends Validator
} }
if (($value = $this->validateValue($value)) !== false) { if (($value = $this->validateValue($value)) !== false) {
$object->$attribute = $value; $object->$attribute = $value;
} } else {
else {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid URL.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid URL.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
@ -78,8 +77,7 @@ class UrlValidator extends Validator
if (strpos($this->pattern, '{schemes}') !== false) { if (strpos($this->pattern, '{schemes}') !== false) {
$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern); $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
} } else {
else {
$pattern = $this->pattern; $pattern = $this->pattern;
} }

12
framework/validators/Validator.php

@ -137,13 +137,11 @@ abstract class Validator extends \yii\base\Component
if (isset($params['on'])) { if (isset($params['on'])) {
if (is_array($params['on'])) { if (is_array($params['on'])) {
$on = $params['on']; $on = $params['on'];
} } else {
else {
$on = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY); $on = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY);
} }
$params['on'] = empty($on) ? array() : array_combine($on, $on); $params['on'] = empty($on) ? array() : array_combine($on, $on);
} } else {
else {
$params['on'] = array(); $params['on'] = array();
} }
@ -153,8 +151,7 @@ abstract class Validator extends \yii\base\Component
'method' => $type, 'method' => $type,
'attributes' => $attributes, 'attributes' => $attributes,
); );
} } else {
else {
if (is_string($type) && isset(self::$builtInValidators[$type])) { if (is_string($type) && isset(self::$builtInValidators[$type])) {
$type = self::$builtInValidators[$type]; $type = self::$builtInValidators[$type];
} }
@ -181,8 +178,7 @@ abstract class Validator extends \yii\base\Component
{ {
if (is_array($attributes)) { if (is_array($attributes)) {
$attributes = array_intersect($this->attributes, $attributes); $attributes = array_intersect($this->attributes, $attributes);
} } else {
else {
$attributes = $this->attributes; $attributes = $this->attributes;
} }
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {

3
framework/yiic.php

@ -19,8 +19,7 @@ if(isset($config))
$env=@getenv('YII_CONSOLE_COMMANDS'); $env=@getenv('YII_CONSOLE_COMMANDS');
if(!empty($env)) if(!empty($env))
$app->commandRunner->addCommands($env); $app->commandRunner->addCommands($env);
} } else
else
{ {
$app=new \yii\console\Application(array( $app=new \yii\console\Application(array(
'basePath'=>__DIR__.'/cli', 'basePath'=>__DIR__.'/cli',

33
tests/unit/MysqlTestCase.php

@ -0,0 +1,33 @@
<?php
namespace yiiunit;
class MysqlTestCase extends TestCase
{
function __construct()
{
if(!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) {
$this->markTestSkipped('pdo and pdo_mysql extensions are required.');
}
}
/**
* @param bool $reset whether to clean up the test database
* @return \yii\db\dao\Connection
*/
function getConnection($reset = true)
{
$params = $this->getParam('mysql');
$db = new \yii\db\dao\Connection($params['dsn'], $params['username'], $params['password']);
if ($reset) {
$db->active = true;
$lines = explode(';', file_get_contents($params['fixture']));
foreach ($lines as $line) {
if (trim($line) !== '') {
$db->pdo->exec($line);
}
}
}
return $db;
}
}

144
tests/unit/data/mysql.sql

@ -4,17 +4,17 @@
* and create an account 'test/test' which owns this test database. * and create an account 'test/test' which owns this test database.
*/ */
DROP TABLE IF EXISTS types CASCADE; DROP TABLE IF EXISTS yii_type CASCADE;
DROP TABLE IF EXISTS items CASCADE; DROP TABLE IF EXISTS yii_item CASCADE;
DROP TABLE IF EXISTS orders CASCADE; DROP TABLE IF EXISTS yii_order CASCADE;
DROP TABLE IF EXISTS post_category CASCADE; DROP TABLE IF EXISTS yii_post_category CASCADE;
DROP TABLE IF EXISTS categories CASCADE; DROP TABLE IF EXISTS yii_category CASCADE;
DROP TABLE IF EXISTS comments CASCADE; DROP TABLE IF EXISTS yii_comment CASCADE;
DROP TABLE IF EXISTS posts CASCADE; DROP TABLE IF EXISTS yii_post CASCADE;
DROP TABLE IF EXISTS profiles CASCADE; DROP TABLE IF EXISTS yii_profile CASCADE;
DROP TABLE IF EXISTS users CASCADE; DROP TABLE IF EXISTS yii_user CASCADE;
CREATE TABLE users CREATE TABLE yii_user
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(128) NOT NULL, username VARCHAR(128) NOT NULL,
@ -22,24 +22,24 @@ CREATE TABLE users
email VARCHAR(128) NOT NULL email VARCHAR(128) NOT NULL
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO users (username, password, email) VALUES ('user1','pass1','email1'); INSERT INTO yii_user (username, password, email) VALUES ('user1','pass1','email1');
INSERT INTO users (username, password, email) VALUES ('user2','pass2','email2'); INSERT INTO yii_user (username, password, email) VALUES ('user2','pass2','email2');
INSERT INTO users (username, password, email) VALUES ('user3','pass3','email3'); INSERT INTO yii_user (username, password, email) VALUES ('user3','pass3','email3');
CREATE TABLE profiles CREATE TABLE yii_profile
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(128) NOT NULL, first_name VARCHAR(128) NOT NULL,
last_name VARCHAR(128) NOT NULL, last_name VARCHAR(128) NOT NULL,
user_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
CONSTRAINT FK_profile_user FOREIGN KEY (user_id) CONSTRAINT FK_profile_user FOREIGN KEY (user_id)
REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO profiles (first_name, last_name, user_id) VALUES ('first 1','last 1',1); INSERT INTO yii_profile (first_name, last_name, user_id) VALUES ('first 1','last 1',1);
INSERT INTO profiles (first_name, last_name, user_id) VALUES ('first 2','last 2',2); INSERT INTO yii_profile (first_name, last_name, user_id) VALUES ('first 2','last 2',2);
CREATE TABLE posts CREATE TABLE yii_post
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(128) NOT NULL, title VARCHAR(128) NOT NULL,
@ -47,74 +47,74 @@ CREATE TABLE posts
author_id INTEGER NOT NULL, author_id INTEGER NOT NULL,
content TEXT, content TEXT,
CONSTRAINT FK_post_author FOREIGN KEY (author_id) CONSTRAINT FK_post_author FOREIGN KEY (author_id)
REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 1','2000-01-01',1,'content 1'); INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 1','2000-01-01',1,'content 1');
INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 2','2000-01-02',2,'content 2'); INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 2','2000-01-02',2,'content 2');
INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 3','2000-01-03',2,'content 3'); INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 3','2000-01-03',2,'content 3');
INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 4','2000-01-04',2,'content 4'); INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 4','2000-01-04',2,'content 4');
INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 5','2000-01-05',3,'content 5'); INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 5','2000-01-05',3,'content 5');
CREATE TABLE comments CREATE TABLE yii_comment
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
content TEXT NOT NULL, content TEXT NOT NULL,
post_id INTEGER NOT NULL, post_id INTEGER NOT NULL,
author_id INTEGER NOT NULL, author_id INTEGER NOT NULL,
CONSTRAINT FK_post_comment FOREIGN KEY (post_id) CONSTRAINT FK_post_comment FOREIGN KEY (post_id)
REFERENCES posts (id) ON DELETE CASCADE ON UPDATE RESTRICT, REFERENCES yii_post (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_user_comment FOREIGN KEY (author_id) CONSTRAINT FK_user_comment FOREIGN KEY (author_id)
REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 1',1, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 1',1, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 2',1, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 2',1, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 3',1, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 3',1, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 4',2, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 4',2, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 5',2, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 5',2, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 6',3, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 6',3, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 7',3, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 7',3, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 8',3, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 8',3, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 9',3, 2); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 9',3, 2);
INSERT INTO comments (content, post_id, author_id) VALUES ('comment 10',5, 3); INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 10',5, 3);
CREATE TABLE categories CREATE TABLE yii_category
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(128) NOT NULL, name VARCHAR(128) NOT NULL,
parent_id INTEGER, parent_id INTEGER,
CONSTRAINT FK_category_category FOREIGN KEY (parent_id) CONSTRAINT FK_category_category FOREIGN KEY (parent_id)
REFERENCES categories (id) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_category (id) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO categories (name, parent_id) VALUES ('cat 1',NULL); INSERT INTO yii_category (name, parent_id) VALUES ('cat 1',NULL);
INSERT INTO categories (name, parent_id) VALUES ('cat 2',NULL); INSERT INTO yii_category (name, parent_id) VALUES ('cat 2',NULL);
INSERT INTO categories (name, parent_id) VALUES ('cat 3',NULL); INSERT INTO yii_category (name, parent_id) VALUES ('cat 3',NULL);
INSERT INTO categories (name, parent_id) VALUES ('cat 4',1); INSERT INTO yii_category (name, parent_id) VALUES ('cat 4',1);
INSERT INTO categories (name, parent_id) VALUES ('cat 5',1); INSERT INTO yii_category (name, parent_id) VALUES ('cat 5',1);
INSERT INTO categories (name, parent_id) VALUES ('cat 6',5); INSERT INTO yii_category (name, parent_id) VALUES ('cat 6',5);
INSERT INTO categories (name, parent_id) VALUES ('cat 7',5); INSERT INTO yii_category (name, parent_id) VALUES ('cat 7',5);
CREATE TABLE post_category CREATE TABLE yii_post_category
( (
category_id INTEGER NOT NULL, category_id INTEGER NOT NULL,
post_id INTEGER NOT NULL, post_id INTEGER NOT NULL,
PRIMARY KEY (category_id, post_id), PRIMARY KEY (category_id, post_id),
CONSTRAINT FK_post_category_post FOREIGN KEY (post_id) CONSTRAINT FK_yii_post_category_post FOREIGN KEY (post_id)
REFERENCES posts (id) ON DELETE CASCADE ON UPDATE RESTRICT, REFERENCES yii_post (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_post_category_category FOREIGN KEY (category_id) CONSTRAINT FK_yii_post_category_category FOREIGN KEY (category_id)
REFERENCES categories (id) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_category (id) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO post_category (category_id, post_id) VALUES (1,1); INSERT INTO yii_post_category (category_id, post_id) VALUES (1,1);
INSERT INTO post_category (category_id, post_id) VALUES (2,1); INSERT INTO yii_post_category (category_id, post_id) VALUES (2,1);
INSERT INTO post_category (category_id, post_id) VALUES (3,1); INSERT INTO yii_post_category (category_id, post_id) VALUES (3,1);
INSERT INTO post_category (category_id, post_id) VALUES (4,2); INSERT INTO yii_post_category (category_id, post_id) VALUES (4,2);
INSERT INTO post_category (category_id, post_id) VALUES (1,2); INSERT INTO yii_post_category (category_id, post_id) VALUES (1,2);
INSERT INTO post_category (category_id, post_id) VALUES (1,3); INSERT INTO yii_post_category (category_id, post_id) VALUES (1,3);
CREATE TABLE orders CREATE TABLE yii_order
( (
key1 INTEGER NOT NULL, key1 INTEGER NOT NULL,
key2 INTEGER NOT NULL, key2 INTEGER NOT NULL,
@ -122,28 +122,28 @@ CREATE TABLE orders
PRIMARY KEY (key1, key2) PRIMARY KEY (key1, key2)
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO orders (key1,key2,name) VALUES (1,2,'order 12'); INSERT INTO yii_order (key1,key2,name) VALUES (1,2,'order 12');
INSERT INTO orders (key1,key2,name) VALUES (1,3,'order 13'); INSERT INTO yii_order (key1,key2,name) VALUES (1,3,'order 13');
INSERT INTO orders (key1,key2,name) VALUES (2,1,'order 21'); INSERT INTO yii_order (key1,key2,name) VALUES (2,1,'order 21');
INSERT INTO orders (key1,key2,name) VALUES (2,2,'order 22'); INSERT INTO yii_order (key1,key2,name) VALUES (2,2,'order 22');
CREATE TABLE items CREATE TABLE yii_item
( (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(128), name VARCHAR(128),
col1 INTEGER NOT NULL, col1 INTEGER NOT NULL,
col2 INTEGER NOT NULL, col2 INTEGER NOT NULL,
CONSTRAINT FK_order_item FOREIGN KEY (col1,col2) CONSTRAINT FK_order_item FOREIGN KEY (col1,col2)
REFERENCES orders (key1,key2) ON DELETE CASCADE ON UPDATE RESTRICT REFERENCES yii_order (key1,key2) ON DELETE CASCADE ON UPDATE RESTRICT
) TYPE=INNODB; ) TYPE=INNODB;
INSERT INTO items (name,col1,col2) VALUES ('item 1',1,2); INSERT INTO yii_item (name,col1,col2) VALUES ('item 1',1,2);
INSERT INTO items (name,col1,col2) VALUES ('item 2',1,2); INSERT INTO yii_item (name,col1,col2) VALUES ('item 2',1,2);
INSERT INTO items (name,col1,col2) VALUES ('item 3',1,3); INSERT INTO yii_item (name,col1,col2) VALUES ('item 3',1,3);
INSERT INTO items (name,col1,col2) VALUES ('item 4',2,2); INSERT INTO yii_item (name,col1,col2) VALUES ('item 4',2,2);
INSERT INTO items (name,col1,col2) VALUES ('item 5',2,2); INSERT INTO yii_item (name,col1,col2) VALUES ('item 5',2,2);
CREATE TABLE types CREATE TABLE yii_type
( (
int_col INT NOT NULL, int_col INT NOT NULL,
int_col2 INTEGER DEFAULT 1, int_col2 INTEGER DEFAULT 1,

99
tests/unit/framework/db/dao/CommandTest.php

@ -6,47 +6,40 @@ use yii\db\dao\Connection;
use yii\db\dao\Command; use yii\db\dao\Command;
use yii\db\dao\Query; use yii\db\dao\Query;
class CommandTest extends \yiiunit\TestCase class CommandTest extends \yiiunit\MysqlTestCase
{ {
private $connection;
function setUp()
{
if(!extension_loaded('pdo') || !extension_loaded('pdo_mysql'))
$this->markTestSkipped('pdo and pdo_mysql extensions are required.');
$params = $this->getParam('mysql');
$this->connection = new Connection($params['dsn'], $params['username'], $params['password']);
$this->connection->open();
$this->connection->pdo->exec(file_get_contents($params['fixture']));
}
function tearDown()
{
$this->connection->close();
}
function testConstruct() function testConstruct()
{ {
$command = $this->connection->createCommand(); $db = $this->getConnection(false);
$command = $db->createCommand();
$this->assertEquals("SELECT *\nFROM ", $command->sql); $this->assertEquals("SELECT *\nFROM ", $command->sql);
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$command = $this->connection->createCommand($sql); $command = $db->createCommand($sql);
$this->assertEquals($sql, $command->sql); $this->assertEquals($sql, $command->sql);
$query = new Query; $query = new Query;
$command = $this->connection->createCommand($query); $command = $db->createCommand($query);
$this->assertEquals($query, $command->query); $this->assertEquals($query, $command->query);
$query = array('select'=>'id', 'from'=>'posts'); $query = array('select'=>'id', 'from'=>'posts');
$command = $this->connection->createCommand($query); $command = $db->createCommand($query);
$this->assertEquals($query, $command->query->toArray()); $this->assertEquals($query, $command->query->toArray());
} }
function testReset() function testReset()
{ {
$db = $this->getConnection();
$command = $db->createCommand('SELECT * FROM yii_user');
$command->queryRow();
$this->assertNotEquals(null, $command->pdoStatement);
$this->assertEquals('SELECT * FROM yii_user', $command->sql);
$command->reset();
$this->assertEquals(null, $command->pdoStatement);
$this->assertNotEquals('SELECT * FROM yii_user', $command->sql);
} }
function testGetSetSql() function testGetSetSql()
@ -108,7 +101,7 @@ class CommandTest extends \yiiunit\TestCase
function testPrepare() function testPrepare()
{ {
$sql='SELECT title FROM posts'; $sql='SELECT title FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$this->assertEquals($command->pdoStatement,null); $this->assertEquals($command->pdoStatement,null);
$command->prepare(); $command->prepare();
$this->assertTrue($command->pdoStatement instanceof PDOStatement); $this->assertTrue($command->pdoStatement instanceof PDOStatement);
@ -122,7 +115,7 @@ class CommandTest extends \yiiunit\TestCase
function testCancel() function testCancel()
{ {
$sql='SELECT title FROM posts'; $sql='SELECT title FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->prepare(); $command->prepare();
$this->assertTrue($command->pdoStatement instanceof PDOStatement); $this->assertTrue($command->pdoStatement instanceof PDOStatement);
$command->cancel(); $command->cancel();
@ -132,15 +125,15 @@ class CommandTest extends \yiiunit\TestCase
function testExecute() function testExecute()
{ {
$sql='INSERT INTO comments(content,post_id,author_id) VALUES (\'test comment\', 1, 1)'; $sql='INSERT INTO comments(content,post_id,author_id) VALUES (\'test comment\', 1, 1)';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$this->assertEquals($command->execute(),1); $this->assertEquals($command->execute(),1);
$this->assertEquals($command->execute(),1); $this->assertEquals($command->execute(),1);
$command=$this->connection->createCommand('SELECT * FROM comments WHERE content=\'test comment\''); $command=$db->createCommand('SELECT * FROM comments WHERE content=\'test comment\'');
$this->assertEquals($command->execute(),0); $this->assertEquals($command->execute(),0);
$command=$this->connection->createCommand('SELECT COUNT(*) FROM comments WHERE content=\'test comment\''); $command=$db->createCommand('SELECT COUNT(*) FROM comments WHERE content=\'test comment\'');
$this->assertEquals($command->queryScalar(),2); $this->assertEquals($command->queryScalar(),2);
$command=$this->connection->createCommand('bad SQL'); $command=$db->createCommand('bad SQL');
$this->setExpectedException('CException'); $this->setExpectedException('CException');
$command->execute(); $command->execute();
} }
@ -148,16 +141,16 @@ class CommandTest extends \yiiunit\TestCase
function testQuery() function testQuery()
{ {
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$reader=$this->connection->createCommand($sql)->query(); $reader=$db->createCommand($sql)->query();
$this->assertTrue($reader instanceof CDbDataReader); $this->assertTrue($reader instanceof CDbDataReader);
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->prepare(); $command->prepare();
$reader=$command->query(); $reader=$command->query();
$this->assertTrue($reader instanceof CDbDataReader); $this->assertTrue($reader instanceof CDbDataReader);
$command=$this->connection->createCommand('bad SQL'); $command=$db->createCommand('bad SQL');
$this->setExpectedException('CException'); $this->setExpectedException('CException');
$command->query(); $command->query();
} }
@ -165,7 +158,7 @@ class CommandTest extends \yiiunit\TestCase
function testBindParam() function testBindParam()
{ {
$sql='INSERT INTO posts(title,create_time,author_id) VALUES (:title, :create_time, 1)'; $sql='INSERT INTO posts(title,create_time,author_id) VALUES (:title, :create_time, 1)';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$title='test title'; $title='test title';
$createTime=time(); $createTime=time();
$command->bindParam(':title',$title); $command->bindParam(':title',$title);
@ -173,12 +166,12 @@ class CommandTest extends \yiiunit\TestCase
$command->execute(); $command->execute();
$sql='SELECT create_time FROM posts WHERE title=:title'; $sql='SELECT create_time FROM posts WHERE title=:title';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->bindParam(':title',$title); $command->bindParam(':title',$title);
$this->assertEquals($command->queryScalar(),$createTime); $this->assertEquals($command->queryScalar(),$createTime);
$sql='INSERT INTO types (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, :blob_col, :numeric_col, :bool_col)'; $sql='INSERT INTO types (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, :blob_col, :numeric_col, :bool_col)';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$intCol=123; $intCol=123;
$charCol='abc'; $charCol='abc';
$floatCol=1.23; $floatCol=1.23;
@ -194,7 +187,7 @@ class CommandTest extends \yiiunit\TestCase
$this->assertEquals(1,$command->execute()); $this->assertEquals(1,$command->execute());
$sql='SELECT * FROM types'; $sql='SELECT * FROM types';
$row=$this->connection->createCommand($sql)->queryRow(); $row=$db->createCommand($sql)->queryRow();
$this->assertEquals($row['int_col'],$intCol); $this->assertEquals($row['int_col'],$intCol);
$this->assertEquals($row['char_col'],$charCol); $this->assertEquals($row['char_col'],$charCol);
$this->assertEquals($row['float_col'],$floatCol); $this->assertEquals($row['float_col'],$floatCol);
@ -205,47 +198,47 @@ class CommandTest extends \yiiunit\TestCase
function testBindValue() function testBindValue()
{ {
$sql='INSERT INTO comments(content,post_id,author_id) VALUES (:content, 1, 1)'; $sql='INSERT INTO comments(content,post_id,author_id) VALUES (:content, 1, 1)';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->bindValue(':content','test comment'); $command->bindValue(':content','test comment');
$command->execute(); $command->execute();
$sql='SELECT post_id FROM comments WHERE content=:content'; $sql='SELECT post_id FROM comments WHERE content=:content';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->bindValue(':content','test comment'); $command->bindValue(':content','test comment');
$this->assertEquals($command->queryScalar(),1); $this->assertEquals($command->queryScalar(),1);
} }
function testQueryAll() function testQueryAll()
{ {
$rows=$this->connection->createCommand('SELECT * FROM posts')->queryAll(); $rows=$db->createCommand('SELECT * FROM posts')->queryAll();
$this->assertEquals(count($rows),5); $this->assertEquals(count($rows),5);
$row=$rows[2]; $row=$rows[2];
$this->assertEquals($row['id'],3); $this->assertEquals($row['id'],3);
$this->assertEquals($row['title'],'post 3'); $this->assertEquals($row['title'],'post 3');
$rows=$this->connection->createCommand('SELECT * FROM posts WHERE id=10')->queryAll(); $rows=$db->createCommand('SELECT * FROM posts WHERE id=10')->queryAll();
$this->assertEquals($rows,array()); $this->assertEquals($rows,array());
} }
function testQueryRow() function testQueryRow()
{ {
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$row=$this->connection->createCommand($sql)->queryRow(); $row=$db->createCommand($sql)->queryRow();
$this->assertEquals($row['id'],1); $this->assertEquals($row['id'],1);
$this->assertEquals($row['title'],'post 1'); $this->assertEquals($row['title'],'post 1');
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->prepare(); $command->prepare();
$row=$command->queryRow(); $row=$command->queryRow();
$this->assertEquals($row['id'],1); $this->assertEquals($row['id'],1);
$this->assertEquals($row['title'],'post 1'); $this->assertEquals($row['title'],'post 1');
$sql='SELECT * FROM posts WHERE id=10'; $sql='SELECT * FROM posts WHERE id=10';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$this->assertFalse($command->queryRow()); $this->assertFalse($command->queryRow());
$command=$this->connection->createCommand('bad SQL'); $command=$db->createCommand('bad SQL');
$this->setExpectedException('CException'); $this->setExpectedException('CException');
$command->queryRow(); $command->queryRow();
} }
@ -253,13 +246,13 @@ class CommandTest extends \yiiunit\TestCase
function testQueryColumn() function testQueryColumn()
{ {
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$column=$this->connection->createCommand($sql)->queryColumn(); $column=$db->createCommand($sql)->queryColumn();
$this->assertEquals($column,range(1,5)); $this->assertEquals($column,range(1,5));
$command=$this->connection->createCommand('SELECT id FROM posts WHERE id=10'); $command=$db->createCommand('SELECT id FROM posts WHERE id=10');
$this->assertEquals($command->queryColumn(),array()); $this->assertEquals($command->queryColumn(),array());
$command=$this->connection->createCommand('bad SQL'); $command=$db->createCommand('bad SQL');
$this->setExpectedException('CException'); $this->setExpectedException('CException');
$command->queryColumn(); $command->queryColumn();
} }
@ -267,29 +260,29 @@ class CommandTest extends \yiiunit\TestCase
function testQueryScalar() function testQueryScalar()
{ {
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$this->assertEquals($this->connection->createCommand($sql)->queryScalar(),1); $this->assertEquals($db->createCommand($sql)->queryScalar(),1);
$sql='SELECT id FROM posts'; $sql='SELECT id FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->prepare(); $command->prepare();
$this->assertEquals($command->queryScalar(),1); $this->assertEquals($command->queryScalar(),1);
$command=$this->connection->createCommand('SELECT id FROM posts WHERE id=10'); $command=$db->createCommand('SELECT id FROM posts WHERE id=10');
$this->assertFalse($command->queryScalar()); $this->assertFalse($command->queryScalar());
$command=$this->connection->createCommand('bad SQL'); $command=$db->createCommand('bad SQL');
$this->setExpectedException('CException'); $this->setExpectedException('CException');
$command->queryScalar(); $command->queryScalar();
} }
function testFetchMode(){ function testFetchMode(){
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$result = $command->queryRow(); $result = $command->queryRow();
$this->assertTrue(is_array($result)); $this->assertTrue(is_array($result));
$sql='SELECT * FROM posts'; $sql='SELECT * FROM posts';
$command=$this->connection->createCommand($sql); $command=$db->createCommand($sql);
$command->setFetchMode(PDO::FETCH_OBJ); $command->setFetchMode(PDO::FETCH_OBJ);
$result = $command->queryRow(); $result = $command->queryRow();
$this->assertTrue(is_object($result)); $this->assertTrue(is_object($result));

30
tests/unit/framework/db/dao/ConnectionTest.php

@ -4,17 +4,11 @@ namespace yiiunit\framework\db\dao;
use yii\db\dao\Connection; use yii\db\dao\Connection;
class ConnectionTest extends \yiiunit\TestCase class ConnectionTest extends \yiiunit\MysqlTestCase
{ {
function setUp()
{
if(!extension_loaded('pdo') || !extension_loaded('pdo_mysql'))
$this->markTestSkipped('pdo and pdo_mysql extensions are required.');
}
function testConstruct() function testConstruct()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$params = $this->getParam('mysql'); $params = $this->getParam('mysql');
$this->assertEquals($params['dsn'], $connection->dsn); $this->assertEquals($params['dsn'], $connection->dsn);
@ -24,7 +18,7 @@ class ConnectionTest extends \yiiunit\TestCase
function testOpenClose() function testOpenClose()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertFalse($connection->active); $this->assertFalse($connection->active);
$this->assertEquals(null, $connection->pdo); $this->assertEquals(null, $connection->pdo);
@ -44,14 +38,14 @@ class ConnectionTest extends \yiiunit\TestCase
function testGetDriverName() function testGetDriverName()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertEquals('mysql', $connection->driverName); $this->assertEquals('mysql', $connection->driverName);
$this->assertFalse($connection->active); $this->assertFalse($connection->active);
} }
function testQuoteValue() function testQuoteValue()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertEquals(123, $connection->quoteValue(123)); $this->assertEquals(123, $connection->quoteValue(123));
$this->assertEquals("'string'", $connection->quoteValue('string')); $this->assertEquals("'string'", $connection->quoteValue('string'));
$this->assertEquals("'It\'s interesting'", $connection->quoteValue("It's interesting")); $this->assertEquals("'It\'s interesting'", $connection->quoteValue("It's interesting"));
@ -59,23 +53,25 @@ class ConnectionTest extends \yiiunit\TestCase
function testQuoteTableName() function testQuoteTableName()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertEquals('`table`', $connection->quoteTableName('table')); $this->assertEquals('`table`', $connection->quoteTableName('table'));
$this->assertEquals('`table`', $connection->quoteTableName('`table`')); $this->assertEquals('`table`', $connection->quoteTableName('`table`'));
$this->assertEquals('`schema`.`table`', $connection->quoteTableName('schema.table')); $this->assertEquals('`schema`.`table`', $connection->quoteTableName('schema.table'));
$this->assertEquals('`schema.table`', $connection->quoteTableName('schema.table', true));
} }
function testQuoteColumnName() function testQuoteColumnName()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertEquals('`column`', $connection->quoteColumnName('column')); $this->assertEquals('`column`', $connection->quoteColumnName('column'));
$this->assertEquals('`column`', $connection->quoteColumnName('`column`')); $this->assertEquals('`column`', $connection->quoteColumnName('`column`'));
$this->assertEquals('`table`.`column`', $connection->quoteColumnName('table.column')); $this->assertEquals('`table`.`column`', $connection->quoteColumnName('table.column'));
$this->assertEquals('`table.column`', $connection->quoteColumnName('table.column', true));
} }
function testGetPdoType() function testGetPdoType()
{ {
$connection = $this->createConnection(); $connection = $this->getConnection();
$this->assertEquals(\PDO::PARAM_BOOL, $connection->getPdoType('boolean')); $this->assertEquals(\PDO::PARAM_BOOL, $connection->getPdoType('boolean'));
$this->assertEquals(\PDO::PARAM_INT, $connection->getPdoType('integer')); $this->assertEquals(\PDO::PARAM_INT, $connection->getPdoType('integer'));
$this->assertEquals(\PDO::PARAM_STR, $connection->getPdoType('string')); $this->assertEquals(\PDO::PARAM_STR, $connection->getPdoType('string'));
@ -86,10 +82,4 @@ class ConnectionTest extends \yiiunit\TestCase
{ {
} }
function createConnection()
{
$params = $this->getParam('mysql');
return new Connection($params['dsn'], $params['username'], $params['password']);
}
} }

Loading…
Cancel
Save