Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

600 lines
16 KiB

13 years ago
<?php
/**
13 years ago
* ActiveFinder class file.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\ar;
13 years ago
use yii\base\Object;
13 years ago
use yii\base\VectorIterator;
13 years ago
use yii\db\dao\Query;
13 years ago
use yii\db\Exception;
13 years ago
13 years ago
/**
* ActiveFinder.php is ...
13 years ago
*
13 years ago
* @property integer $count
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
13 years ago
class ActiveFinder extends \yii\base\Object
13 years ago
{
13 years ago
/**
13 years ago
* @var \yii\db\dao\Connection
13 years ago
*/
13 years ago
public $connection;
13 years ago
13 years ago
public function __construct($connection)
13 years ago
{
13 years ago
$this->connection = $connection;
13 years ago
}
/**
13 years ago
* @param ActiveQuery $query
13 years ago
*/
13 years ago
public function find($query, $returnScalar = false)
13 years ago
{
13 years ago
if (!empty($query->with)) {
13 years ago
return $this->findWithRelations($query, $returnScalar);
13 years ago
}
13 years ago
if ($query->sql !== null) {
$sql = $query->sql;
13 years ago
} else {
13 years ago
$modelClass = $query->modelClass;
$tableName = $modelClass::tableName();
13 years ago
if ($query->from === null) {
if ($query->tableAlias !== null) {
$tableName .= ' ' . $query->tableAlias;
}
$query->from = array($tableName);
}
13 years ago
$this->applyScopes($query);
$sql = $this->connection->getQueryBuilder()->build($query);
13 years ago
if ($query->tableAlias !== null) {
$alias = $this->connection->quoteTableName($query->tableAlias) . '.';
} else {
$alias = $this->connection->quoteTableName($tableName) . '.';
13 years ago
}
13 years ago
$tokens = array(
'@.' => $alias,
$this->connection->quoteTableName('@', true) . '.' => $alias,
);
$sql = strtr($sql, $tokens);
13 years ago
}
13 years ago
$command = $this->connection->createCommand($sql, $query->params);
13 years ago
13 years ago
if ($returnScalar) {
return $command->queryScalar();
} else {
$rows = $command->queryAll();
return $this->createRecords($query, $rows);
}
}
13 years ago
private $_joinCount;
private $_tableAliases;
private $_hasMany;
/**
* @param ActiveQuery $query
* @return array
*/
protected function findWithRelations($query, $returnScalar = false)
{
13 years ago
$this->_joinCount = 0;
$this->_tableAliases = array();
$this->_hasMany = false;
$joinTree = new JoinElement($this->_joinCount++, $query, null, null);
if ($query->sql !== null) {
$command = $this->connection->createCommand($query->sql, $query->params);
if ($returnScalar) {
return $command->queryScalar();
13 years ago
}
13 years ago
$rows = $command->queryAll();
$records = $this->createRecords($query, $rows);
$modelClass = $query->modelClass;
$table = $modelClass::getMetaData()->table;
foreach ($records as $record) {
$pk = array();
foreach ($table->primaryKey as $name) {
$pk[] = $record[$name];
}
$pk = count($pk) === 1 ? $pk[0] : serialize($pk);
$joinTree->records[$pk] = $record;
13 years ago
}
13 years ago
$q = new ActiveQuery($modelClass);
$q->with = $query->with;
$q->tableAlias = 't';
$q->asArray = $query->asArray;
$q->index = $query->index;
$q->select = $table->primaryKey;
$this->addPkCondition($q, $table, $rows, 't.');
$joinTree->query = $query = $q;
}
$this->buildJoinTree($joinTree, $query->with);
$this->initJoinTree($joinTree);
$q = new Query;
$this->buildJoinQuery($joinTree, $q, $returnScalar);
if ($returnScalar) {
return $q->createCommand($this->connection)->queryScalar();
13 years ago
} else {
13 years ago
if ($this->_hasMany && ($query->limit > 0 || $query->offset > 0)) {
$this->limitQuery($query, $q);
13 years ago
}
13 years ago
$command = $q->createCommand($this->connection);
$rows = $command->queryAll();
$joinTree->populateData($rows);
return $query->index === null ? array_values($joinTree->records) : $joinTree->records;
13 years ago
}
}
/**
* @param ActiveRecord $record
* @param ActiveRelation $relation
* @return array
*/
13 years ago
public function findWithRecord($record, $relation)
13 years ago
{
13 years ago
$this->_joinCount = 0;
$this->_tableAliases = array();
$this->_hasMany = false;
$query = new ActiveQuery(get_class($record));
$modelClass = $query->modelClass;
$table = $modelClass::getMetaData()->table;
$query->select = $table->primaryKey;
$query->limit = $relation->limit;
$query->offset = $relation->offset;
13 years ago
$joinTree = new JoinElement($this->_joinCount++, $query, null, null);
$child = $this->buildJoinTree($joinTree, $relation->name);
$child->query = $relation;
$child->container = null;
13 years ago
$this->buildJoinTree($child, $relation->with);
$this->initJoinTree($joinTree);
13 years ago
$pk = $record->getPrimaryKey(true);
$this->addPkCondition($query, $table, array($pk), $query->tableAlias . '.');
13 years ago
$q = new Query;
$this->buildJoinQuery($joinTree, $q);
if ($this->_hasMany && ($query->limit > 0 || $query->offset > 0)) {
$this->limitQuery($query, $q);
}
$rows = $q->createCommand($this->connection)->queryAll();
$child->populateData($rows);
13 years ago
$records = $relation->index === null ? array_values($child->records) : $child->records;
if ($relation->hasMany) {
13 years ago
return $records;
} else {
return $records === array() ? null : reset($records);
13 years ago
}
13 years ago
}
13 years ago
protected function createRecords($query, $rows)
13 years ago
{
13 years ago
$records = array();
if ($query->asArray) {
if ($query->index === null) {
return $rows;
}
foreach ($rows as $row) {
$records[$row[$query->index]] = $row;
}
} else {
/** @var $class ActiveRecord */
13 years ago
$class = $query->modelClass;
if ($query->index === null) {
foreach ($rows as $row) {
$records[] = $class::create($row);
}
} else {
foreach ($rows as $row) {
$records[$row[$query->index]] = $class::create($row);
}
}
}
13 years ago
return $records;
13 years ago
}
13 years ago
protected function applyScopes($query)
{
/** @var $class ActiveRecord */
13 years ago
$class = $query->modelClass;
$class::defaultScope($query);
13 years ago
if (is_array($query->scopes)) {
$model = new $class;
13 years ago
foreach ($query->scopes as $name => $params) {
if (is_string($params)) {
// scope name only without parameters
13 years ago
$name = $params;
13 years ago
$params = array();
}
if (method_exists($class, $name)) {
13 years ago
array_unshift($params, $query);
call_user_func_array(array($model, $name), $params);
13 years ago
} else {
13 years ago
throw new Exception("$class has no scope named '$name'.");
}
13 years ago
}
}
}
13 years ago
/**
* @param JoinElement $parent
* @param array|string $with
* @param array|\Closure $config
13 years ago
* @return null|JoinElement
* @throws \yii\db\Exception
*/
13 years ago
protected function buildJoinTree($parent, $with, $config = array())
13 years ago
{
13 years ago
if (empty($with)) {
return null;
}
13 years ago
if (is_array($with)) {
foreach ($with as $name => $value) {
13 years ago
if (is_array($value) || $value instanceof \Closure) {
13 years ago
$this->buildJoinTree($parent, $name, $value);
13 years ago
} else {
$this->buildJoinTree($parent, $value);
13 years ago
}
}
return null;
}
if (($pos = strrpos($with, '.')) !== false) {
13 years ago
$parent = $this->buildJoinTree($parent, substr($with, 0, $pos));
13 years ago
$with = substr($with, $pos + 1);
}
if (isset($parent->children[$with])) {
$child = $parent->children[$with];
} else {
13 years ago
$modelClass = $parent->query->modelClass;
13 years ago
$relations = $modelClass::getMetaData()->relations;
if (!isset($relations[$with])) {
throw new Exception("$modelClass has no relation named '$with'.");
}
$relation = clone $relations[$with];
13 years ago
if (is_string($relation->via)) {
// join via an existing relation
13 years ago
$parent2 = $this->buildJoinTree($parent, $relation->via);
13 years ago
if ($parent2->query->select === null) {
$parent2->query->select = false;
unset($parent2->container->relations[$parent2->query->name]);
13 years ago
}
13 years ago
$child = new JoinElement($this->_joinCount++, $relation, $parent2, $parent);
13 years ago
} elseif (is_array($relation->via)) {
// join via a pivoting table
$r = new ActiveRelation;
$r->name = 'vt' . $this->_joinCount;
13 years ago
$r->hasMany = $relation->hasMany;
foreach ($relation->via as $name => $value) {
$r->$name = $value;
}
$r->select = false;
if ($r->joinType === null) {
$r->joinType = $relation->joinType;
}
$parent2 = new JoinElement($this->_joinCount++, $r, $parent, $parent);
$child = new JoinElement($this->_joinCount++, $relation, $parent2, $parent);
13 years ago
} else {
13 years ago
$child = new JoinElement($this->_joinCount++, $relation, $parent, $parent);
13 years ago
}
}
13 years ago
if ($config instanceof \Closure) {
13 years ago
$config($child->query);
13 years ago
} else {
foreach ($config as $name => $value) {
$child->query->$name = $value;
}
13 years ago
}
return $child;
}
13 years ago
13 years ago
/**
* @param JoinElement $element
*/
13 years ago
protected function initJoinTree($element)
13 years ago
{
13 years ago
if ($element->query->tableAlias !== null) {
$alias = $element->query->tableAlias;
} elseif ($element->query instanceof ActiveRelation) {
$alias = $element->query->name;
} else {
$alias = 't';
13 years ago
}
if ($element->query instanceof ActiveRelation) {
if ($element->query->hasMany) {
$this->_hasMany = true;
}
if ($element->parent->query->asArray !== null && $element->query->asArray === null) {
$element->query->asArray = $element->parent->query->asArray;
}
}
13 years ago
$count = 0;
while (isset($this->_tableAliases[$alias])) {
$alias = 't' . $count++;
}
$this->_tableAliases[$alias] = true;
$element->query->tableAlias = $alias;
13 years ago
if ($element->records !== array()) {
13 years ago
$this->applyScopes($element->query);
}
if ($element->container !== null && $element->query->asArray === null) {
$element->query->asArray = $element->container->query->asArray;
}
13 years ago
13 years ago
foreach ($element->children as $child) {
13 years ago
$this->initJoinTree($child);
13 years ago
}
}
13 years ago
/**
* @param JoinElement $element
13 years ago
* @param \yii\db\dao\Query $query
13 years ago
*/
13 years ago
protected function buildJoinQuery($element, $query, $keepSelect = false)
13 years ago
{
13 years ago
if ($element->parent) {
$prefixes = array(
'@.' => $element->query->tableAlias . '.',
'?.' => $element->parent->query->tableAlias . '.',
);
$quotedPrefixes = array(
'@.' => $this->connection->quoteTableName($element->query->tableAlias, true) . '.',
'?.' => $this->connection->quoteTableName($element->parent->query->tableAlias, true) . '.',
);
} else {
$prefixes = array(
'@.' => $element->query->tableAlias . '.',
);
$quotedPrefixes = array(
'@.' => $this->connection->quoteTableName($element->query->tableAlias, true) . '.',
);
$query->limit = $element->query->limit;
$query->offset = $element->query->offset;
13 years ago
}
$qb = $this->connection->getQueryBuilder();
13 years ago
13 years ago
if ($keepSelect) {
if (!empty($element->query->select)) {
$select = $element->query->select;
if (is_string($select)) {
$select = explode(',', $select);
}
foreach ($select as $column) {
$query->select[] = strtr(trim($column), $prefixes);
}
}
} else {
foreach ($this->buildSelect($element, $element->query->select) as $column) {
$query->select[] = strtr($column, $prefixes);
}
13 years ago
}
13 years ago
if ($element->query instanceof ActiveQuery) {
if ($element->query->from === null) {
$modelClass = $element->query->modelClass;
$tableName = $modelClass::tableName();
if ($element->query->tableAlias !== null) {
$tableName .= ' ' . $element->query->tableAlias;
}
$query->from = array($tableName);
} else {
$query->from = $element->query->from;
}
13 years ago
}
13 years ago
if (($where = $qb->buildCondition($element->query->where)) !== '') {
$query->andWhere(strtr($where, $quotedPrefixes));
13 years ago
}
13 years ago
if (($having = $qb->buildCondition($element->query->having)) !== '') {
$query->andHaving(strtr($having, $quotedPrefixes));
13 years ago
}
13 years ago
if ($element->query instanceof ActiveRelation) {
13 years ago
$joinType = $element->query->joinType ?: 'LEFT JOIN';
13 years ago
if ($element->query->modelClass !== null) {
$modelClass = $element->query->modelClass;
$tableName = $this->connection->quoteTableName($modelClass::tableName());
} else {
$tableName = $this->connection->quoteTableName($element->query->table);
}
13 years ago
$tableAlias = $this->connection->quoteTableName($element->query->tableAlias);
$join = "$joinType $tableName $tableAlias";
13 years ago
$on = '';
if (is_array($element->query->link)) {
foreach ($element->query->link as $pk => $fk) {
$pk = $quotedPrefixes['@.'] . $this->connection->quoteColumnName($pk, true);
$fk = $quotedPrefixes['?.'] . $this->connection->quoteColumnName($fk, true);
if ($on !== '') {
$on .= ' AND ';
}
$on .= "$pk = $fk";
}
}
13 years ago
if ($element->query->on !== null) {
13 years ago
$condition = strtr($qb->buildCondition($element->query->on), $quotedPrefixes);
if ($on !== '') {
$on .= " AND ($condition)";
} else {
$on = $condition;
}
}
if ($on !== '') {
$join .= ' ON ' . $on;
13 years ago
}
$query->join[] = $join;
13 years ago
}
if ($element->query->join !== null) {
13 years ago
if (is_array($element->query->join)) {
foreach ($element->query->join as $join) {
if (is_array($join) && isset($join[2])) {
$join[2] = strtr($join[2], $quotedPrefixes);
}
$query->join[] = $join;
}
} else {
$query->join[] = strtr($element->query->join, $quotedPrefixes);
}
13 years ago
}
if ($element->query->order !== null) {
if (!is_array($element->query->order)) {
$element->query->order = preg_split('/\s*,\s*/', trim($element->query->order), -1, PREG_SPLIT_NO_EMPTY);
13 years ago
}
foreach ($element->query->order as $order) {
$query->order[] = strtr($order, $prefixes);
13 years ago
}
}
if ($element->query->group !== null) {
if (!is_array($element->query->group)) {
$element->query->group = preg_split('/\s*,\s*/', trim($element->query->group), -1, PREG_SPLIT_NO_EMPTY);
13 years ago
}
foreach ($element->query->group as $group) {
$query->group[] = strtr($group, $prefixes);
13 years ago
}
}
if ($element->query->params !== null) {
$query->addParams($element->query->params);
}
foreach ($element->children as $child) {
13 years ago
$this->buildJoinQuery($child, $query, $keepSelect);
13 years ago
}
}
protected function buildSelect($element, $select)
{
if ($select === false) {
return array();
}
$modelClass = $element->query->modelClass;
$table = $modelClass::getMetaData()->table;
$columns = array();
$columnCount = 0;
$prefix = $element->query->tableAlias;
13 years ago
foreach ($table->primaryKey as $column) {
$alias = "c{$element->id}_" . ($columnCount++);
$columns[] = "$prefix.$column AS $alias";
$element->pkAlias[$column] = $alias;
$element->columnAliases[$alias] = $column;
}
13 years ago
if (empty($select) || $select === '*') {
foreach ($table->columns as $column) {
13 years ago
if (!isset($element->pkAlias[$column->name])) {
$alias = "c{$element->id}_" . ($columnCount++);
$columns[] = "$prefix.{$column->name} AS $alias";
$element->columnAliases[$alias] = $column->name;
13 years ago
}
}
} else {
if (is_string($select)) {
$select = explode(',', $select);
}
foreach ($select as $column) {
$column = trim($column);
if (preg_match('/^(.*?)\s+AS\s+(\w+)$/im', $column, $matches)) {
// if the column is already aliased
$element->columnAliases[$matches[2]] = $matches[2];
$columns[] = $column;
} elseif (!isset($element->pkAlias[$column])) {
13 years ago
$alias = "c{$element->id}_" . ($columnCount++);
13 years ago
if (strpos($column, '(') !== false) {
$columns[] = "$column AS $alias";
} else {
$columns[] = "$prefix.$column AS $alias";
}
13 years ago
$element->columnAliases[$alias] = $column;
}
}
}
13 years ago
// determine the actual index column(s)
if ($element->query->index !== null) {
$index = array_search($element->query->index, $element->columnAliases);
}
if (empty($index)) {
$index = $element->pkAlias;
if (count($index) === 1) {
$index = reset($element->pkAlias);
}
}
$element->key = $index;
13 years ago
return $columns;
}
protected function limitQuery($activeQuery, $query)
{
$q = clone $query;
$modelClass = $activeQuery->modelClass;
$table = $modelClass::getMetaData()->table;
$q->select = array();
foreach ($table->primaryKey as $name) {
$q->select[] = $alias = $activeQuery->tableAlias . '.' . $name;
}
$q->distinct = true;
$rows = $q->createCommand($this->connection)->queryAll();
$prefix = $activeQuery->tableAlias . '.';
$this->addPkCondition($query, $table, $rows, $prefix);
$query->limit = $query->offset = null;
}
protected function addPkCondition($query, $table, $rows, $prefix)
{
if (count($table->primaryKey) === 1 && count($rows) > 1) {
$name = $table->primaryKey[0];
$values = array();
foreach ($rows as $row) {
$values[] = $table->columns[$name]->typecast($row[$name]);
}
$query->andWhere(array('in', $prefix . $name, $values));
} else {
$ors = array('or');
foreach ($rows as $row) {
$hash = array();
foreach ($table->primaryKey as $name) {
$value = $table->columns[$name]->typecast($row[$name]);
if (is_string($value)) {
$value = $this->connection->quoteValue($value);
}
$hash[$prefix . $name] = $value;
}
$ors[] = $hash;
}
$query->andWhere($ors);
}
}
13 years ago
}