Commit 3210a217 by Qiang Xue

...

parent 965fe5c4
......@@ -69,7 +69,7 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Component extends Object
class Component extends \yii\base\Object
{
/**
* @var Vector[] the attached event handlers (event name => handlers)
......
......@@ -15,11 +15,12 @@ use yii\db\dao\BaseQuery;
use yii\db\Exception;
/**
* 1. eager loading, base limited and has has_many relations
* 2.
* ActiveFinder.php is ...
* todo: add SQL monitor
* todo: better handling on join() support in QueryBuilder: use regexp to detect table name and quote it
* todo: do not support anonymous parameter binding
* todo: add ActiveFinderBuilder
* todo: quote join/on part of the relational query
* todo: modify QueryBuilder about join() methods
* todo: unify ActiveFinder and ActiveRelation in query building process
......@@ -48,6 +49,10 @@ class ActiveQuery extends BaseQuery implements \IteratorAggregate, \ArrayAccess,
*/
public $with;
/**
* @var array list of relations that should be used as filters for this query.
*/
public $filters;
/**
* @var string the table alias to be used for query
*/
public $tableAlias;
......@@ -66,10 +71,14 @@ class ActiveQuery extends BaseQuery implements \IteratorAggregate, \ArrayAccess,
*/
public $scopes;
/**
* @var string the SQL statement to be executed to retrieve primary records.
* This is set by [[ActiveRecord::findBySql()]].
*/
public $sql;
/**
* @var array list of query results
*/
public $records;
public $sql;
/**
* @param string $modelClass the name of the ActiveRecord class.
......@@ -95,6 +104,16 @@ class ActiveQuery extends BaseQuery implements \IteratorAggregate, \ArrayAccess,
return $this;
}
public function filters()
{
$this->filters = func_get_args();
if (isset($this->filters[0]) && is_array($this->filters[0])) {
// the parameter is given as an array
$this->filters = $this->filters[0];
}
return $this;
}
public function indexBy($column)
{
$this->indexBy = $column;
......@@ -129,7 +148,7 @@ class ActiveQuery extends BaseQuery implements \IteratorAggregate, \ArrayAccess,
{
if ($this->records === null) {
// todo: load only one record
$this->records = $this->findRecords();
$this->records = $this->findRecords(false);
}
return isset($this->records[0]) ? $this->records[0] : null;
}
......@@ -276,178 +295,13 @@ class ActiveQuery extends BaseQuery implements \IteratorAggregate, \ArrayAccess,
unset($this->records[$offset]);
}
public function joinWith()
{
// todo: inner join with one or multiple relations as filters
}
protected function findRecords()
protected function findRecords($all = true)
{
$finder = new ActiveFinder($this->getDbConnection());
if (!empty($this->with)) {
// todo: handle findBySql() and limit cases
$joinTree = $this->buildRelationalQuery();
}
if ($this->sql === null) {
$this->initFrom($this->query);
$command = $this->query->createCommand($this->getDbConnection());
$this->sql = $command->getSql();
} else {
$command = $this->getDbConnection()->createCommand($this->sql);
$command->bindValues($this->query->params);
}
$rows = $command->queryAll();
if (isset($joinTree)) {
foreach ($rows as $row) {
$joinTree->populateData($row);
}
return array_values($joinTree->records);
}
if ($this->asArray) {
if ($this->indexBy === null) {
return $rows;
}
$records = array();
foreach ($rows as $row) {
$records[$row[$this->indexBy]] = $row;
}
return $records;
return $finder->findRecordsWithRelations();
} else {
$records = array();
$class = $this->modelClass;
if ($this->indexBy === null) {
foreach ($rows as $row) {
$records[] = $class::populateData($row);
}
} else {
$attribute = $this->indexBy;
foreach ($rows as $row) {
$record = $class::populateData($row);
$records[$record->$attribute] = $record;
}
}
return $records;
}
}
protected function initFrom($query)
{
if ($query->from === null) {
$modelClass = $this->modelClass;
$tableName = $modelClass::tableName();
if ($this->tableAlias !== null) {
$tableName .= ' ' . $this->tableAlias;
}
$query->from = array($tableName);
}
}
protected function buildRelationalQuery()
{
$joinTree = new JoinElement($this, null, null);
$this->buildJoinTree($joinTree, $this->with);
$this->buildTableAlias($joinTree);
$query = new Query;
foreach ($joinTree->children as $child) {
$child->buildQuery($query);
}
$select = $joinTree->buildSelect($this->query->select);
if (!empty($query->select)) {
$this->query->select = array_merge($select, $query->select);
} else {
$this->query->select = $select;
}
if (!empty($query->where)) {
$this->query->andWhere('(' . implode(') AND (', $query->where) . ')');
}
if (!empty($query->having)) {
$this->query->andHaving('(' . implode(') AND (', $query->having) . ')');
}
if (!empty($query->join)) {
if ($this->query->join === null) {
$this->query->join = $query->join;
} else {
$this->query->join = array_merge($this->query->join, $query->join);
}
}
if (!empty($query->orderBy)) {
$this->query->addOrderBy($query->orderBy);
}
if (!empty($query->groupBy)) {
$this->query->addGroupBy($query->groupBy);
}
if (!empty($query->params)) {
$this->query->addParams($query->params);
}
return $joinTree;
}
/**
* @param JoinElement $parent
* @param array|string $with
* @param array $config
* @return null|JoinElement
* @throws \yii\db\Exception
*/
protected function buildJoinTree($parent, $with, $config = array())
{
if (is_array($with)) {
foreach ($with as $name => $value) {
if (is_string($value)) {
$this->buildJoinTree($parent, $value);
} elseif (is_string($name) && is_array($value)) {
$this->buildJoinTree($parent, $name, $value);
}
}
return null;
}
if (($pos = strrpos($with, '.')) !== false) {
$parent = $this->buildJoinTree($parent, substr($with, 0, $pos));
$with = substr($with, $pos + 1);
}
if (isset($parent->children[$with])) {
$child = $parent->children[$with];
$child->joinOnly = false;
} else {
$modelClass = $parent->relation->modelClass;
$relations = $modelClass::getMetaData()->relations;
if (!isset($relations[$with])) {
throw new Exception("$modelClass has no relation named '$with'.");
}
$relation = clone $relations[$with];
if ($relation->via !== null && isset($relations[$relation->via])) {
$relation->via = null;
$parent2 = $this->buildJoinTree($parent, $relation->via);
if ($parent2->joinOnly === null) {
$parent2->joinOnly = true;
}
$child = new JoinElement($relation, $parent2, $parent);
} else {
$child = new JoinElement($relation, $parent, $parent);
}
}
foreach ($config as $name => $value) {
$child->relation->$name = $value;
}
return $child;
}
protected function buildTableAlias($element, &$count = 0)
{
if ($element->relation->tableAlias === null) {
$element->relation->tableAlias = 't' . ($count++);
}
foreach ($element->children as $child) {
$this->buildTableAlias($child, $count);
return $finder->findRecords($this, $all);
}
}
}
......@@ -427,7 +427,7 @@ abstract class ActiveRecord extends Model
if (array_key_exists($name, $this->_related)) {
return $this->_related[$name];
} else {
return $this->_related[$name] = $this->loadRelatedRecord($md->relations[$name]);
return $this->_related[$name] = $this->findByRelation($md->relations[$name]);
}
}
return parent::__get($name);
......@@ -501,7 +501,7 @@ abstract class ActiveRecord extends Model
{
$md = $this->getMetaData();
if (isset($md->relations[$name])) {
return $this->loadRelatedRecord($md->relations[$name], isset($params[0]) ? $params[0] : array());
return $this->findByRelation($md->relations[$name], isset($params[0]) ? $params[0] : array());
}
return parent::__call($name, $params);
}
......@@ -532,14 +532,12 @@ abstract class ActiveRecord extends Model
* or null if the object does not exist.
* If the relation is HAS_MANY or MANY_MANY, it will return an array of objects
* or an empty array.
* @param string $name the relation name (see {@link relations})
* @param boolean $refresh whether to reload the related objects from database. Defaults to false.
* @param ActiveRelation|string $relation the relation object or the name of the relation
* @param array $params additional parameters that customize the query conditions as specified in the relation declaration.
* This parameter has been available since version 1.0.5.
* @return mixed the related object(s).
* @throws Exception if the relation is not specified in {@link relations}.
* @throws Exception if the relation is not specified in [[relations()]].
*/
public function loadRelatedRecord($relation, $params = array())
public function findByRelation($relation, $params = array())
{
if (is_string($relation)) {
$md = $this->getMetaData();
......@@ -548,7 +546,8 @@ abstract class ActiveRecord extends Model
}
$relation = $md->relations[$relation];
}
$finder = $this->createActiveQuery();
$query = $this->createActiveQuery();
return $query->findRelatedRecords($this, $relation, $params);
}
/**
......
......@@ -33,9 +33,10 @@ class ActiveRelation extends BaseQuery
*/
public $hasMany;
/**
* @var string the join type (e.g. INNER JOIN, LEFT JOIN). Defaults to 'LEFT JOIN'.
* @var string the join type (e.g. INNER JOIN, LEFT JOIN). Defaults to 'LEFT JOIN' when
* this relation is used to load related records, and 'INNER JOIN' when this relation is used as a filter.
*/
public $joinType = 'LEFT JOIN';
public $joinType;
/**
* @var string the table alias used for the corresponding table during query
*/
......@@ -58,6 +59,10 @@ class ActiveRelation extends BaseQuery
*/
public $with;
/**
* @var array the relations that should be used as filters for this query
*/
public $filters;
/**
* @var array the scopes that should be applied during query
*/
public $scopes;
......
......@@ -3,7 +3,7 @@
namespace yiiunit\framework\db\ar;
use yii\db\dao\Query;
use yii\db\ar\ActiveFinder;
use yii\db\ar\ActiveQuery;
use yiiunit\data\ar\ActiveRecord;
use yiiunit\data\ar\Customer;
use yiiunit\data\ar\OrderItem;
......@@ -45,28 +45,14 @@ class ActiveRecordTest extends \yiiunit\MysqlTestCase
$customer2 = Customer::find(2)->one();
$this->assertEquals('user2x', $customer2->name);
// saveAttributes
$customer = Customer::find(1)->one();
$this->assertEquals('user1', $customer->name);
$this->assertEquals('address1', $customer->address);
$customer->saveAttributes(array(
'name' => 'user1x',
'address' => 'address1x',
));
$this->assertEquals('user1x', $customer->name);
$this->assertEquals('address1x', $customer->address);
$customer = Customer::find(1)->one();
$this->assertEquals('user1x', $customer->name);
$this->assertEquals('address1x', $customer->address);
// saveCounters
// updateCounters
$pk = array('order_id' => 2, 'item_id' => 4);
$orderItem = OrderItem::find($pk)->one();
$orderItem = OrderItem::find()->where($pk)->one();
$this->assertEquals(1, $orderItem->quantity);
$ret = $orderItem->saveCounters(array('quantity' => -1));
$ret = $orderItem->updateCounters(array('quantity' => -1));
$this->assertTrue($ret);
$this->assertEquals(0, $orderItem->quantity);
$orderItem = OrderItem::find($pk)->one();
$orderItem = OrderItem::find()->where($pk)->one();
$this->assertEquals(0, $orderItem->quantity);
// updateAll
......@@ -81,13 +67,13 @@ class ActiveRecordTest extends \yiiunit\MysqlTestCase
// updateCounters
$pk = array('order_id' => 1, 'item_id' => 2);
$orderItem = OrderItem::find($pk)->one();
$orderItem = OrderItem::find()->where($pk)->one();
$this->assertEquals(2, $orderItem->quantity);
$ret = OrderItem::updateCounters(array(
$ret = OrderItem::updateAllCounters(array(
'quantity' => 3,
), $pk);
$this->assertEquals(1, $ret);
$orderItem = OrderItem::find($pk)->one();
$orderItem = OrderItem::find()->where($pk)->one();
$this->assertEquals(5, $orderItem->quantity);
}
......@@ -114,7 +100,7 @@ class ActiveRecordTest extends \yiiunit\MysqlTestCase
{
// find one
$result = Customer::find();
$this->assertTrue($result instanceof ActiveFinder);
$this->assertTrue($result instanceof ActiveQuery);
$customer = $result->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals(1, $result->count);
......@@ -158,13 +144,15 @@ class ActiveRecordTest extends \yiiunit\MysqlTestCase
$this->assertEquals('user2', $customer->name);
// find by attributes
$customer = Customer::find(array('name' => 'user2'))->one();
$customer = Customer::find()->where(array('name' => 'user2'))->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals(2, $customer->id);
// find by Query
$query = new Query;
$query->where('id=:id', array(':id' => 2));
$query = array(
'where' => 'id=:id',
'params' => array(':id' => 2),
);
$customer = Customer::find($query)->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals('user2', $customer->name);
......@@ -190,16 +178,16 @@ class ActiveRecordTest extends \yiiunit\MysqlTestCase
$this->assertEquals('user2', $customer->name);
// count
$finder = Customer::findBySql('SELECT * FROM tbl_customer ORDER BY id DESC');
$finder->one();
$this->assertEquals(3, $finder->count);
$finder = Customer::findBySql('SELECT * FROM tbl_customer ORDER BY id DESC');
$this->assertEquals(3, $finder->count);
$query = Customer::findBySql('SELECT * FROM tbl_customer ORDER BY id DESC');
$query->one();
$this->assertEquals(1, $query->count);
$query = Customer::findBySql('SELECT * FROM tbl_customer ORDER BY id DESC');
$this->assertEquals(3, $query->count);
}
public function testQueryMethods()
{
$customer = Customer::find()->where('id=?', 2)->one();
$customer = Customer::find()->where('id=:id', array(':id' => 2))->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals('user2', $customer->name);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment