Commit c073f1d1 authored by piccoloprincipe's avatar piccoloprincipe

[2.0] completed implementation of lazy loading for Collections. Created debug...

[2.0] completed implementation of lazy loading for Collections. Created debug helper class. Fixed default for orderBy clause to ASC
parent 2807a83d
......@@ -392,4 +392,4 @@ class Collection implements Countable, IteratorAggregate, ArrayAccess
{
$this->_elements = array();
}
}
\ No newline at end of file
}
<?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Util;
/**
* Static class containing most used debug methods.
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
* @since 2.0
*/
final class Debug
{
private function __construct() {}
/**
* Prints a dump of the public, protected and private properties of $var.
* To print a meaningful dump, whose depth is limited, requires xdebug
* php extension.
* @link http://xdebug.org/
* @param mixed $var
* @param integer $maxDepth maximum nesting level for object properties
*/
public static function dump($var, $maxDepth = 2)
{
ini_set('html_errors', 'On');
ini_set('xdebug.var_display_max_depth', $maxDepth);
ob_start();
var_dump($var);
$dump = ob_get_contents();
ob_end_clean();
echo strip_tags(html_entity_decode($dump));
ini_set('html_errors', 'Off');
}
}
......@@ -137,7 +137,6 @@ class ObjectHydrator extends AbstractHydrator
* Updates the result pointer for an entity. The result pointers point to the
* last seen instance of each entity type. This is used for graph construction.
*
* @param array $resultPointers The result pointers.
* @param Collection $coll The element.
* @param boolean|integer $index Index of the element in the collection.
* @param string $dqlAlias
......@@ -173,6 +172,7 @@ class ObjectHydrator extends AbstractHydrator
*
* @param object $entity The entity to which the collection belongs.
* @param string $name The name of the field on the entity that holds the collection.
* @return PersistentCollection
*/
private function initRelatedCollection($entity, $name)
{
......@@ -190,6 +190,7 @@ class ObjectHydrator extends AbstractHydrator
$classMetadata->reflFields[$name]->setValue($entity, $coll);
$this->_uow->setOriginalEntityProperty($oid, $name, $coll);
$this->_initializedRelations[$oid][$name] = true;
return $coll;
}
/**
......@@ -263,13 +264,14 @@ class ObjectHydrator extends AbstractHydrator
$assoc->load($entity, new $assoc->targetEntityName, $this->_em, $joinColumns);
}
} else {
//TODO: Eager load
// Inject collection
$this->_ce[$className]->reflFields[$field]
->setValue($entity, new PersistentCollection(
$this->_em,
$this->_em->getClassMetadata($assoc->targetEntityName)
));
$collection = $this->initRelatedCollection($entity, $field);
if ($assoc->isLazilyFetched()) {
$collection->setLazyInitialization();
} else {
//TODO: Allow more efficient and configurable batching of these loads
$assoc->load($entity, $collection, $this->_em);
}
}
}
}
......
......@@ -391,14 +391,28 @@ abstract class AssociationMapping
}
/**
* Loads data in $targetEntity domain object using this association.
* Loads data in $target domain object using this association.
* The data comes from the association navigated from $sourceEntity
* using $em.
*
* @param object $sourceEntity
* @param object $targetEntity
* @param object $target an entity or a collection
* @param EntityManager $em
* @param array $joinColumnValues
* @param array $joinColumnValues foreign keys (significative for this
* association) of $sourceEntity, if needed
*/
abstract public function load($sourceEntity, $targetEntity, $em, array $joinColumnValues);
abstract public function load($sourceEntity, $target, $em, array $joinColumnValues = array());
/**
* Uses reflection to access internal data of entities.
* @param ClassMetadata $class
* @param $entity a domain object
* @param $column name of private field
* @return mixed
*/
protected function _getPrivateValue(ClassMetadata $class, $entity, $column)
{
$reflField = $class->getReflectionProperty($class->getFieldName($column));
return $reflField->getValue($entity);
}
}
......@@ -35,6 +35,7 @@ namespace Doctrine\ORM\Mapping;
*
* @since 2.0
* @author Roman Borschel <roman@code-factory.org>
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
*/
class ManyToManyMapping extends AssociationMapping
{
......@@ -138,9 +139,47 @@ class ManyToManyMapping extends AssociationMapping
return $this->targetKeyColumns;
}
public function load($owningEntity, $targetEntity, $em, array $joinColumnValues)
/**
* Loads entities in $targetCollection using $em.
* The data of $sourceEntity are used to restrict the collection
* via the join table.
*/
public function load($sourceEntity, $targetCollection, $em, array $joinColumnValues = array())
{
throw new Exception('Not yet implemented.');
$sourceClass = $em->getClassMetadata($this->sourceEntityName);
$joinTableConditions = array();
if ($this->isOwningSide()) {
$joinTable = $this->getJoinTable();
$joinClauses = $this->getTargetToRelationKeyColumns();
foreach ($this->getSourceToRelationKeyColumns() as $sourceKeyColumn => $relationKeyColumn) {
// getting id
if (isset($sourceClass->reflFields[$sourceKeyColumn])) {
$joinTableConditions[$relationKeyColumn] = $this->_getPrivateValue($sourceClass, $sourceEntity, $sourceKeyColumn);
} else {
$joinTableConditions[$relationKeyColumn] = $joinColumnValues[$sourceKeyColumn];
}
}
} else {
$owningAssoc = $em->getClassMetadata($this->targetEntityName)->getAssociationMapping($this->mappedByFieldName);
$joinTable = $owningAssoc->getJoinTable();
// TRICKY: since the association is inverted source and target are flipped
$joinClauses = $owningAssoc->getSourceToRelationKeyColumns();
foreach ($owningAssoc->getTargetToRelationKeyColumns() as $sourceKeyColumn => $relationKeyColumn) {
// getting id
if (isset($sourceClass->reflFields[$sourceKeyColumn])) {
$joinTableConditions[$relationKeyColumn] = $this->_getPrivateValue($sourceClass, $sourceEntity, $sourceKeyColumn);
} else {
$joinTableConditions[$relationKeyColumn] = $joinColumnValues[$sourceKeyColumn];
}
}
}
$joinTableCriteria = array(
'table' => $joinTable['name'],
'join' => $joinClauses,
'criteria' => $joinTableConditions
);
$persister = $em->getUnitOfWork()->getEntityPersister($this->targetEntityName);
$persister->loadCollection(array($joinTableCriteria), $targetCollection);
}
/**
......
......@@ -38,6 +38,7 @@ namespace Doctrine\ORM\Mapping;
* the serialized representation).
*
* @author Roman Borschel <roman@code-factory.org>
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
* @since 2.0
*/
class OneToManyMapping extends AssociationMapping
......@@ -47,6 +48,13 @@ class OneToManyMapping extends AssociationMapping
/** FUTURE: The key column mapping, if any. The key column holds the keys of the Collection. */
//public $keyColumn;
/**
* TODO: Allow any combination of source/target columns in lazy loading.
* What is supported now is primary key (that can spread on multiple fields)
* pointed to foreign keys on the target
public $targetColumns;
*/
/**
* Initializes a new OneToManyMapping.
*
......@@ -67,7 +75,7 @@ class OneToManyMapping extends AssociationMapping
protected function _validateAndCompleteMapping(array $mapping)
{
parent::_validateAndCompleteMapping($mapping);
// one-side MUST be inverse (must have mappedBy)
if ( ! isset($mapping['mappedBy'])) {
throw MappingException::oneToManyRequiresMappedBy($mapping['fieldName']);
......@@ -97,8 +105,22 @@ class OneToManyMapping extends AssociationMapping
return true;
}
public function load($owningEntity, $targetEntity, $em, array $joinColumnValues)
public function load($sourceEntity, $targetCollection, $em, array $joinColumnValues = array())
{
throw new Exception('Not yet implemented.');
$persister = $em->getUnitOfWork()->getEntityPersister($this->targetEntityName);
// a one-to-many is always inverse (does not have foreign key)
$sourceClass = $em->getClassMetadata($this->sourceEntityName);
$owningAssoc = $em->getClassMetadata($this->targetEntityName)->getAssociationMapping($this->mappedByFieldName);
// TRICKY: since the association is specular source and target are flipped
foreach ($owningAssoc->getTargetToSourceKeyColumns() as $sourceKeyColumn => $targetKeyColumn) {
// getting id
if (isset($sourceClass->reflFields[$sourceKeyColumn])) {
$conditions[$targetKeyColumn] = $this->_getPrivateValue($sourceClass, $sourceEntity, $sourceKeyColumn);
} else {
$conditions[$targetKeyColumn] = $joinColumnValues[$sourceKeyColumn];
}
}
$persister->loadCollection($conditions, $targetCollection);
}
}
......@@ -163,7 +163,7 @@ class OneToOneMapping extends AssociationMapping
* @param array $joinColumnValues values of the join columns of $sourceEntity. There are no fields
* to store this data in $sourceEntity
*/
public function load($sourceEntity, $targetEntity, $em, array $joinColumnValues)
public function load($sourceEntity, $targetEntity, $em, array $joinColumnValues = array())
{
$sourceClass = $em->getClassMetadata($this->sourceEntityName);
$targetClass = $em->getClassMetadata($this->targetEntityName);
......@@ -189,12 +189,13 @@ class OneToOneMapping extends AssociationMapping
}
} else {
$owningAssoc = $em->getClassMetadata($this->targetEntityName)->getAssociationMapping($this->mappedByFieldName);
foreach ($owningAssoc->getTargetToSourceKeyColumns() as $targetKeyColumn => $sourceKeyColumn) {
// TRICKY: since the association is specular source and target are flipped
foreach ($owningAssoc->getTargetToSourceKeyColumns() as $sourceKeyColumn => $targetKeyColumn) {
// getting id
if (isset($sourceClass->reflFields[$targetKeyColumn])) {
$conditions[$sourceKeyColumn] = $this->_getPrivateValue($sourceClass, $sourceEntity, $targetKeyColumn);
if (isset($sourceClass->reflFields[$sourceKeyColumn])) {
$conditions[$targetKeyColumn] = $this->_getPrivateValue($sourceClass, $sourceEntity, $sourceKeyColumn);
} else {
$conditions[$sourceKeyColumn] = $joinColumnValues[$targetKeyColumn];
$conditions[$targetKeyColumn] = $joinColumnValues[$sourceKeyColumn];
}
}
......@@ -203,10 +204,4 @@ class OneToOneMapping extends AssociationMapping
$targetClass->setFieldValue($targetEntity, $this->mappedByFieldName, $sourceEntity);
}
}
protected function _getPrivateValue(ClassMetadata $class, $entity, $column)
{
$reflField = $class->getReflectionProperty($class->getFieldName($column));
return $reflField->getValue($entity);
}
}
This diff is collapsed.
......@@ -273,7 +273,7 @@ class JoinedSubclassPersister extends StandardEntityPersister
* @todo Quote identifier.
* @override
*/
protected function _getSelectSingleEntitySql(array $criteria)
protected function _getSelectSingleEntitySql(array &$criteria)
{
$tableAliases = array();
$aliasIndex = 1;
......@@ -326,4 +326,4 @@ class JoinedSubclassPersister extends StandardEntityPersister
return $sql . ' WHERE ' . $conditionSql;
}
}
\ No newline at end of file
}
......@@ -35,6 +35,7 @@ use Doctrine\ORM\Events;
* how to persist (and to some extent how to load) entities of a specific type.
*
* @author Roman Borschel <roman@code-factory.org>
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version $Revision: 3406 $
* @link www.doctrine-project.org
......@@ -396,10 +397,26 @@ class StandardEntityPersister
{
$stmt = $this->_conn->prepare($this->_getSelectSingleEntitySql($criteria));
$stmt->execute(array_values($criteria));
$data = array();
$joinColumnValues = array();
$result = $stmt->fetch(Connection::FETCH_ASSOC);
$stmt->closeCursor();
return $this->_createEntity($result, $entity);
}
public function loadCollection(array $criteria, PersistentCollection $collection)
{
$sql = $this->_getSelectSingleEntitySql($criteria);
$stmt = $this->_conn->prepare($sql);
$stmt->execute(array_values($criteria));
while ($result = $stmt->fetch(Connection::FETCH_ASSOC)) {
$collection->hydrateAdd($this->_createEntity($result));
}
$stmt->closeCursor();
}
private function _createEntity($result, $entity = null)
{
$data = array();
$joinColumnValues = array();
if ($result === false) {
return null;
......@@ -448,10 +465,15 @@ class StandardEntityPersister
}
} else {
// Inject collection
//TODO: Eager load
$this->_class->reflFields[$field]->setValue(
$entity, new PersistentCollection($this->_em, $this->_em->getClassMetadata($assoc->targetEntityName)
));
$coll = new PersistentCollection($this->_em, $this->_em->getClassMetadata($assoc->targetEntityName));
$coll->setOwner($entity, $assoc);
$this->_class->reflFields[$field]->setValue($entity, $coll);
if ($assoc->isLazilyFetched()) {
$coll->setLazyInitialization();
} else {
//TODO: Allow more efficient and configurable batching of these loads
$assoc->load($entity, $coll, $this->_em);
}
}
}
}
......@@ -461,11 +483,14 @@ class StandardEntityPersister
/**
* Gets the SELECT SQL to select a single entity by a set of field criteria.
* No joins are used but the query can return multiple rows.
*
* @param array $criteria
* @param array $criteria every element can be a value or an joinClause
* if it is a joinClause, it will be removed and correspondent nested values will be added to $criteria.
* JoinClauses are used to restrict the result returned but only columns of this entity are selected (@see _getJoinSql()).
* @return string The SQL.
*/
protected function _getSelectSingleEntitySql(array $criteria)
protected function _getSelectSingleEntitySql(array &$criteria)
{
$columnList = '';
foreach ($this->_class->columnNames as $column) {
......@@ -485,9 +510,23 @@ class StandardEntityPersister
}
}
$joinSql = '';
$conditionSql = '';
foreach ($criteria as $field => $value) {
if ($conditionSql != '') $conditionSql .= ' AND ';
if ($conditionSql != '') {
$conditionSql .= ' AND ';
}
if (is_array($value)) {
$joinSql .= $this->_getJoinSql($value);
foreach ($value['criteria'] as $nestedField => $nestedValue) {
$columnName = "{$value['table']}.{$nestedField}";
$conditionSql .= $this->_conn->quoteIdentifier($columnName) . ' = ?';
$criteria[$columnName] = $nestedValue;
}
unset($criteria[$field]);
continue;
}
if (isset($this->_class->columnNames[$field])) {
$columnName = $this->_class->columnNames[$field];
} else if (in_array($field, $joinColumnNames)) {
......@@ -498,7 +537,27 @@ class StandardEntityPersister
$conditionSql .= $this->_conn->quoteIdentifier($columnName) . ' = ?';
}
return 'SELECT ' . $columnList . ' FROM ' . $this->_class->getTableName()
. ' WHERE ' . $conditionSql;
return 'SELECT ' . $columnList
. ' FROM ' . $this->_class->getTableName()
. $joinSql
. ' WHERE ' . $conditionSql;
}
/**
* Builds a LEFT JOIN sql query part using $joinClause
* @param array $joinClause keys are:
* 'table' => table to join
* 'join' => array of [sourceField => joinTableField]
* 'criteria' => array of [joinTableField => value]
* @return string
*/
protected function _getJoinSql(array $joinClause)
{
$clauses = array();
foreach ($joinClause['join'] as $sourceField => $joinTableField) {
$clauses[] = $this->_class->getTableName() . ".{$sourceField} = "
. "{$joinClause['table']}.{$joinTableField}";
}
return " LEFT JOIN {$joinClause['table']} ON " . implode(' AND ', $clauses);
}
}
......@@ -70,4 +70,4 @@ class OrderByItem extends Node
{
return $sqlWalker->walkOrderByItem($this);
}
}
\ No newline at end of file
}
......@@ -1164,16 +1164,16 @@ class Parser
if ($this->_lexer->isNextToken(Lexer::T_ASC)) {
$this->match(Lexer::T_ASC);
$item->setAsc(true);
return $item;
}
if ($this->_lexer->isNextToken(Lexer::T_DESC)) {
$this->match(Lexer::T_DESC);
$item->setDesc(true);
return $item;
}
$item->setDesc(true);
$item->setAsc(true);
return $item;
}
......
......@@ -248,7 +248,11 @@ class SqlWalker implements TreeWalker
$qComp = $this->_queryComponents[$dqlAlias];
$columnName = $qComp['metadata']->getColumnName($parts[0]);
$sql = $this->getSqlTableAlias($qComp['metadata']->getTableName(), $dqlAlias) . '.' . $columnName;
$sql .= $orderByItem->isAsc() ? ' ASC' : ' DESC';
if ($orderByItem->isAsc()) {
$sql .= ' ASC ';
} else if ($orderByItem->isDesc()) {
$sql .= ' DESC ';
}
return $sql;
}
......
......@@ -1938,4 +1938,4 @@ class UnitOfWork implements PropertyChangedListener
$this->_entityUpdates[$oid] = $entity;
}
}
}
\ No newline at end of file
}
......@@ -349,4 +349,4 @@ class BasicFunctionalTest extends \Doctrine\Tests\OrmFunctionalTestCase
$this->_em->refresh($user);
$this->assertEquals('developer', $user->status);
}
}
\ No newline at end of file
}
......@@ -86,5 +86,6 @@ class DetachedEntityTest extends \Doctrine\Tests\OrmFunctionalTestCase
$this->assertTrue($this->_em->contains($phonenumbers[0]));
$this->assertTrue($this->_em->contains($phonenumbers[1]));
}
}
......@@ -5,12 +5,13 @@ namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Collections\Collection;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceCategory;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional many-to-many association mapping (without inheritance).
* Inverse side is not present.
* Owning side is ECommerceProduct, inverse side is ECommerceCategory.
*/
class ManyToManyBidirectionalAssociationTest extends AbstractManyToManyAssociationTestCase
{
......@@ -67,36 +68,45 @@ class ManyToManyBidirectionalAssociationTest extends AbstractManyToManyAssociati
$this->_createLoadingFixture();
list ($firstProduct, $secondProduct) = $this->_findProducts();
$categories = $firstProduct->getCategories();
$this->assertTrue($categories[0] instanceof ECommerceCategory);
$this->assertTrue($categories[1] instanceof ECommerceCategory);
$this->assertCollectionEquals($categories, $secondProduct->getCategories());
$this->assertLoadingOfInverseSide($categories);
$this->assertLoadingOfInverseSide($secondProduct->getCategories());
}
public function testEagerLoadsOwningSide()
{
$this->_createLoadingFixture();
list ($firstProduct, $secondProduct) = $this->_findProducts();
$this->assertEquals(2, count($firstProduct->getCategories()));
$this->assertEquals(2, count($secondProduct->getCategories()));
$categories = $firstProduct->getCategories();
$firstCategoryProducts = $categories[0]->getProducts();
$secondCategoryProducts = $categories[1]->getProducts();
$this->assertEquals(2, count($firstCategoryProducts));
$this->assertEquals(2, count($secondCategoryProducts));
$products = $this->_findProducts();
$this->assertLoadingOfOwningSide($products);
}
public function testLazyLoadsCollectionOnTheInverseSide()
{
$this->_createLoadingFixture();
$this->assertTrue($firstCategoryProducts[0] instanceof ECommerceProduct);
$this->assertTrue($firstCategoryProducts[1] instanceof ECommerceProduct);
$this->assertTrue($secondCategoryProducts[0] instanceof ECommerceProduct);
$this->assertTrue($secondCategoryProducts[1] instanceof ECommerceProduct);
$this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts);
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCategory');
$metadata->getAssociationMapping('products')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id');
$categories = $query->getResultList();
$this->assertLoadingOfInverseSide($categories);
}
public function testLazyLoadsCollectionOnTheOwningSide()
{
$this->_createLoadingFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$metadata->getAssociationMapping('categories')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p order by p.id');
$products = $query->getResultList();
$this->assertLoadingOfOwningSide($products);
}
protected function _createLoadingFixture()
private function _createLoadingFixture()
{
$this->firstProduct->addCategory($this->firstCategory);
$this->firstProduct->addCategory($this->secondCategory);
......@@ -115,8 +125,30 @@ class ManyToManyBidirectionalAssociationTest extends AbstractManyToManyAssociati
return $query->getResultList();
}
/* TODO: not yet implemented
public function testLazyLoad() {
public function assertLoadingOfOwningSide($products)
{
list ($firstProduct, $secondProduct) = $products;
$this->assertEquals(2, count($firstProduct->getCategories()));
$this->assertEquals(2, count($secondProduct->getCategories()));
$categories = $firstProduct->getCategories();
$firstCategoryProducts = $categories[0]->getProducts();
$secondCategoryProducts = $categories[1]->getProducts();
}*/
$this->assertEquals(2, count($firstCategoryProducts));
$this->assertEquals(2, count($secondCategoryProducts));
$this->assertTrue($firstCategoryProducts[0] instanceof ECommerceProduct);
$this->assertTrue($firstCategoryProducts[1] instanceof ECommerceProduct);
$this->assertTrue($secondCategoryProducts[0] instanceof ECommerceProduct);
$this->assertTrue($secondCategoryProducts[1] instanceof ECommerceProduct);
$this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts);
}
public function assertLoadingOfInverseSide($categories)
{
$this->assertTrue($categories[0] instanceof ECommerceCategory);
$this->assertTrue($categories[1] instanceof ECommerceCategory);
}
}
......@@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Collections\Collection;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -65,8 +66,26 @@ class ManyToManySelfReferentialAssociationTest extends AbstractManyToManyAssocia
public function testEagerLoadsOwningSide()
{
$this->_createLoadingFixture();
list ($firstProduct, $secondProduct) = $this->_findProducts();
$products = $this->_findProducts();
$this->assertLoadingOfOwningSide($products);
}
public function testLazyLoadsOwningSide()
{
$this->_createLoadingFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$metadata->getAssociationMapping('related')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$products = $query->getResultList();
$this->assertLoadingOfOwningSide($products);
}
public function assertLoadingOfOwningSide($products)
{
list ($firstProduct, $secondProduct) = $products;
$this->assertEquals(2, count($firstProduct->getRelated()));
$this->assertEquals(2, count($secondProduct->getRelated()));
......@@ -103,9 +122,4 @@ class ManyToManySelfReferentialAssociationTest extends AbstractManyToManyAssocia
$query = $this->_em->createQuery('SELECT p, r FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.related r ORDER BY p.id, r.id');
return $query->getResultList();
}
/* TODO: not yet implemented
public function testLazyLoad() {
}*/
}
......@@ -5,6 +5,7 @@ namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Collections\Collection;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -60,15 +61,7 @@ class ManyToManyUnidirectionalAssociationTest extends AbstractManyToManyAssociat
public function testEagerLoad()
{
$this->firstCart->addProduct($this->firstProduct);
$this->firstCart->addProduct($this->secondProduct);
$this->secondCart->addProduct($this->firstProduct);
$this->secondCart->addProduct($this->secondProduct);
$this->_em->persist($this->firstCart);
$this->_em->persist($this->secondCart);
$this->_em->flush();
$this->_em->clear();
$this->_createFixture();
$query = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c LEFT JOIN c.products p ORDER BY c.id, p.id');
$result = $query->getResultList();
......@@ -83,8 +76,34 @@ class ManyToManyUnidirectionalAssociationTest extends AbstractManyToManyAssociat
//$this->assertEquals("Doctrine 2.x Manual", $products[1]->getName());
}
/* TODO: not yet implemented
public function testLazyLoad() {
public function testLazyLoadsCollection()
{
$this->_createFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart');
$metadata->getAssociationMapping('products')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c');
$result = $query->getResultList();
$firstCart = $result[0];
$products = $firstCart->getProducts();
$secondCart = $result[1];
}*/
$this->assertTrue($products[0] instanceof ECommerceProduct);
$this->assertTrue($products[1] instanceof ECommerceProduct);
$this->assertCollectionEquals($products, $secondCart->getProducts());
}
private function _createFixture()
{
$this->firstCart->addProduct($this->firstProduct);
$this->firstCart->addProduct($this->secondProduct);
$this->secondCart->addProduct($this->firstProduct);
$this->secondCart->addProduct($this->secondProduct);
$this->_em->persist($this->firstCart);
$this->_em->persist($this->secondCart);
$this->_em->flush();
$this->_em->clear();
}
}
......@@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceFeature;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -69,13 +70,7 @@ class OneToManyBidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctiona
public function testEagerLoadsOneToManyAssociation()
{
$this->product->addFeature($this->firstFeature);
$this->product->addFeature($this->secondFeature);
$this->_em->persist($this->product);
$this->_em->flush();
$this->_em->clear();
$this->_createFixture();
$query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\ECommerce\ECommerceProduct p join p.features f');
$result = $query->getResultList();
$product = $result[0];
......@@ -89,10 +84,50 @@ class OneToManyBidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctiona
$this->assertEquals('Annotations examples', $features[1]->getDescription());
}
/* TODO: not yet implemented
public function testLazyLoad() {
public function testLazyLoadsObjectsOnTheOwningSide()
{
$this->_createFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$metadata->getAssociationMapping('features')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$result = $query->getResultList();
$product = $result[0];
$features = $product->getFeatures();
}*/
$this->assertTrue($features[0] instanceof ECommerceFeature);
$this->assertSame($product, $features[0]->getProduct());
$this->assertEquals('Model writing tutorial', $features[0]->getDescription());
$this->assertTrue($features[1] instanceof ECommerceFeature);
$this->assertSame($product, $features[1]->getProduct());
$this->assertEquals('Annotations examples', $features[1]->getDescription());
}
public function testLazyLoadsObjectsOnTheInverseSide()
{
$this->_createFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceFeature');
$metadata->getAssociationMapping('product')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('select f from Doctrine\Tests\Models\ECommerce\ECommerceFeature f');
$features = $query->getResultList();
$product = $features[0]->getProduct();
$this->assertTrue($product instanceof ECommerceProduct);
$this->assertSame('Doctrine Cookbook', $product->getName());
}
private function _createFixture()
{
$this->product->addFeature($this->firstFeature);
$this->product->addFeature($this->secondFeature);
$this->_em->persist($this->product);
$this->_em->flush();
$this->_em->clear();
}
public function assertFeatureForeignKeyIs($value, ECommerceFeature $feature) {
$foreignKey = $this->_em->getConnection()->execute('SELECT product_id FROM ecommerce_features WHERE id=?', array($feature->getId()))->fetchColumn();
......
......@@ -3,6 +3,7 @@
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCategory;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -69,12 +70,7 @@ class OneToManySelfReferentialAssociationTest extends \Doctrine\Tests\OrmFunctio
public function testEagerLoadsOneToManyAssociation()
{
$this->parent->addChild($this->firstChild);
$this->parent->addChild($this->secondChild);
$this->_em->persist($this->parent);
$this->_em->flush();
$this->_em->clear();
$this->_createFixture();
$query = $this->_em->createQuery('select c1, c2 from Doctrine\Tests\Models\ECommerce\ECommerceCategory c1 join c1.children c2');
$result = $query->getResultList();
......@@ -89,11 +85,36 @@ class OneToManySelfReferentialAssociationTest extends \Doctrine\Tests\OrmFunctio
$this->assertSame($parent, $children[1]->getParent());
$this->assertEquals(' books', strstr($children[1]->getName(), ' books'));
}
/* TODO: not yet implemented
public function testLazyLoad() {
public function testLazyLoadsOneToManyAssociation()
{
$this->_createFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCategory');
$metadata->getAssociationMapping('children')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc');
$result = $query->getResultList();
$parent = $result[0];
$children = $parent->getChildren();
$this->assertTrue($children[0] instanceof ECommerceCategory);
$this->assertSame($parent, $children[0]->getParent());
$this->assertEquals(' books', strstr($children[0]->getName(), ' books'));
$this->assertTrue($children[1] instanceof ECommerceCategory);
$this->assertSame($parent, $children[1]->getParent());
$this->assertEquals(' books', strstr($children[1]->getName(), ' books'));
}
private function _createFixture()
{
$this->parent->addChild($this->firstChild);
$this->parent->addChild($this->secondChild);
$this->_em->persist($this->parent);
}*/
$this->_em->flush();
$this->_em->clear();
}
public function assertForeignKeyIs($value, ECommerceCategory $child) {
$foreignKey = $this->_em->getConnection()->execute('SELECT parent_id FROM ecommerce_categories WHERE id=?', array($child->getId()))->fetchColumn();
......
......@@ -3,6 +3,7 @@
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCustomer;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -47,34 +48,52 @@ class OneToOneSelfReferentialAssociationTest extends \Doctrine\Tests\OrmFunction
$this->assertForeignKeyIs(null);
}
public function testEagerLoad()
public function testEagerLoadsAssociation()
{
$customer = new ECommerceCustomer;
$customer->setName('Luke Skywalker');
$mentor = new ECommerceCustomer;
$mentor->setName('Obi-wan Kenobi');
$customer->setMentor($mentor);
$this->_em->persist($customer);
$this->_em->flush();
$this->_em->clear();
$this->_createFixture();
$query = $this->_em->createQuery('select c, m from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c left join c.mentor m order by c.id asc');
$result = $query->getResultList();
$customer = $result[0];
$this->assertLoadingOfAssociation($customer);
}
public function testLazyLoadsAssociation()
{
$this->_createFixture();
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCustomer');
$metadata->getAssociationMapping('mentor')->fetchMode = AssociationMapping::FETCH_LAZY;
$query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c');
$result = $query->getResultList();
$customer = $result[0];
$this->assertLoadingOfAssociation($customer);
}
public function assertLoadingOfAssociation($customer)
{
$this->assertTrue($customer->getMentor() instanceof ECommerceCustomer);
$this->assertEquals('Obi-wan Kenobi', $customer->getMentor()->getName());
}
/* TODO: not yet implemented
public function testLazyLoad() {
}*/
public function assertForeignKeyIs($value) {
$foreignKey = $this->_em->getConnection()->execute('SELECT mentor_id FROM ecommerce_customers WHERE id=?', array($this->customer->getId()))->fetchColumn();
$this->assertEquals($value, $foreignKey);
}
private function _createFixture()
{
$customer = new ECommerceCustomer;
$customer->setName('Luke Skywalker');
$mentor = new ECommerceCustomer;
$mentor->setName('Obi-wan Kenobi');
$customer->setMentor($mentor);
$this->_em->persist($customer);
$this->_em->flush();
$this->_em->clear();
}
}
......@@ -4,6 +4,7 @@ namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
use Doctrine\Tests\Models\ECommerce\ECommerceCustomer;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
......@@ -20,7 +21,8 @@ class StandardEntityPersisterTest extends \Doctrine\Tests\OrmFunctionalTestCase
parent::setUp();
}
public function testAcceptsForeignKeysAsCriteria() {
public function testAcceptsForeignKeysAsCriteria()
{
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$customer = new ECommerceCustomer();
......@@ -38,4 +40,30 @@ class StandardEntityPersisterTest extends \Doctrine\Tests\OrmFunctionalTestCase
$persister->load(array('customer_id' => $customer->getId()), $newCart);
$this->assertEquals('Credit card', $newCart->getPayment());
}
public function testAcceptsJoinTableAsCriteria()
{
$this->_em->getConfiguration()->setAllowPartialObjects(false);
$cart = new ECommerceCart();
$product = new ECommerceProduct();
$product->setName('Star Wars: A New Hope');
$cart->addProduct($product);
$this->_em->persist($cart);
$this->_em->flush();
$this->_em->clear();
unset($product);
$persister = $this->_em->getUnitOfWork()->getEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$newProduct = new ECommerceProduct();
$criteria = array(
array(
'table' => 'ecommerce_carts_products',
'join' => array('id' => 'product_id'),
'criteria' => array('cart_id' => $cart->getId())
)
);
$persister->load($criteria, $newProduct);
$this->assertEquals('Star Wars: A New Hope', $newProduct->getName());
}
}
<?php
namespace Doctrine\Tests\ORM;
use Doctrine\ORM\PersistentCollection;
use Doctrine\Tests\Mocks\ConnectionMock;
use Doctrine\Tests\Mocks\EntityManagerMock;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
require_once __DIR__ . '/../TestInit.php';
/**
* Tests the lazy-loading capabilities of the PersistentCollection.
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
*/
class PersistentCollectionTest extends \Doctrine\Tests\OrmTestCase
{
private $_connectionMock;
private $_emMock;
protected function setUp()
{
parent::setUp();
// SUT
$this->_connectionMock = new ConnectionMock(array(), new \Doctrine\Tests\Mocks\DriverMock());
$this->_emMock = EntityManagerMock::create($this->_connectionMock);
}
public function testCanBePutInLazyLoadingMode()
{
$class = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$collection = new PersistentCollection($this->_emMock, $class);
$collection->setLazyInitialization();
}
public function testQueriesAssociationToLoadItself()
{
$class = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$collection = new PersistentCollection($this->_emMock, $class);
$collection->setLazyInitialization();
$association = $this->getMock('Doctrine\ORM\Mapping\OneToManyMapping', array('load'), array(), '', false, false, false);
$association->targetEntityName = 'Doctrine\Tests\Models\ECommerce\ECommerceFeature';
$product = new ECommerceProduct();
$association->expects($this->once())
->method('load')
->with($product, $this->isInstanceOf($collection), $this->isInstanceOf($this->_emMock));
$collection->setOwner($product, $association);
count($collection);
}
}
......@@ -90,7 +90,7 @@ class ProxyClassGeneratorTest extends \Doctrine\Tests\OrmTestCase
$proxyClass = $this->_generator->generateReferenceProxyClass('Doctrine\Tests\Models\ECommerce\ECommerceFeature');
$persister = $this->_getMockPersister();
$proxy = new $proxyClass($persister, $identifier);
$persister->expects($this->any())
$persister->expects($this->atLeastOnce())
->method('load')
->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass));
$proxy->getDescription();
......@@ -102,7 +102,7 @@ class ProxyClassGeneratorTest extends \Doctrine\Tests\OrmTestCase
$proxyClass = $this->_generator->generateReferenceProxyClass('Doctrine\Tests\Models\ECommerce\ECommerceFeature');
$persister = $this->_getMockPersister();
$proxy = new $proxyClass($persister, $identifier);
$persister->expects($this->once())
$persister->expects($this->atLeastOnce())
->method('load')
->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass));
$proxy->getId();
......@@ -165,7 +165,7 @@ class ProxyClassGeneratorTest extends \Doctrine\Tests\OrmTestCase
$foreignKeys = array('customer_id' => 42);
$assoc = $this->_getAssociationMock();
$proxy = new $proxyClass($this->_emMock, $assoc, $product, $foreignKeys);
$assoc->expects($this->any())
$assoc->expects($this->atLeastOnce())
->method('load')
->with($product, $this->isInstanceOf($proxyClass), $this->isInstanceOf('Doctrine\Tests\Mocks\EntityManagerMock'), $foreignKeys);
$proxy->getDescription();
......
......@@ -66,6 +66,29 @@ class SelectSqlGenerationTest extends \Doctrine\Tests\OrmTestCase
);
}
public function testSupportsOrderByWithAscAsDefault()
{
$this->assertSqlGeneration(
'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id',
'SELECT f0_.id AS id0, f0_.username AS username1 FROM forum_users f0_ ORDER BY f0_.id ASC '
);
}
public function testSupportsOrderByAsc()
{
$this->assertSqlGeneration(
'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id asc',
'SELECT f0_.id AS id0, f0_.username AS username1 FROM forum_users f0_ ORDER BY f0_.id ASC '
);
}
public function testSupportsOrderByDesc()
{
$this->assertSqlGeneration(
'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id desc',
'SELECT f0_.id AS id0, f0_.username AS username1 FROM forum_users f0_ ORDER BY f0_.id DESC '
);
}
public function testSupportsSelectDistinct()
{
$this->assertSqlGeneration(
......@@ -339,4 +362,4 @@ class SelectSqlGenerationTest extends \Doctrine\Tests\OrmTestCase
$this->assertEquals('SELECT c0_.id AS id0, c0_.status AS status1, c0_.username AS username2, c0_.name AS name3 FROM cms_users c0_ OFFSET 0 LIMIT 10', $q->getSql());
}
}
\ No newline at end of file
}
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