Vendor update && Started using DoctrineMigrations

This commit is contained in:
Polonkai Gergely
2012-07-23 17:09:03 +02:00
parent 7c36f93436
commit bf46316347
1102 changed files with 103189 additions and 7 deletions

View File

@@ -0,0 +1,56 @@
<?php
namespace Doctrine\Tests\ORM;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../TestInit.php';
/**
* Tests of the commit order calculation.
*
* IMPORTANT: When writing tests here consider that a lot of graph constellations
* can have many valid orderings, so you may want to build a graph that has only
* 1 valid order to simplify your tests.
*/
class CommitOrderCalculatorTest extends \Doctrine\Tests\OrmTestCase
{
private $_calc;
protected function setUp()
{
$this->_calc = new \Doctrine\ORM\Internal\CommitOrderCalculator();
}
public function testCommitOrdering1()
{
$class1 = new ClassMetadata(__NAMESPACE__ . '\NodeClass1');
$class2 = new ClassMetadata(__NAMESPACE__ . '\NodeClass2');
$class3 = new ClassMetadata(__NAMESPACE__ . '\NodeClass3');
$class4 = new ClassMetadata(__NAMESPACE__ . '\NodeClass4');
$class5 = new ClassMetadata(__NAMESPACE__ . '\NodeClass5');
$this->_calc->addClass($class1);
$this->_calc->addClass($class2);
$this->_calc->addClass($class3);
$this->_calc->addClass($class4);
$this->_calc->addClass($class5);
$this->_calc->addDependency($class1, $class2);
$this->_calc->addDependency($class2, $class3);
$this->_calc->addDependency($class3, $class4);
$this->_calc->addDependency($class5, $class1);
$sorted = $this->_calc->getCommitOrder();
// There is only 1 valid ordering for this constellation
$correctOrder = array($class5, $class1, $class2, $class3, $class4);
$this->assertSame($correctOrder, $sorted);
}
}
class NodeClass1 {}
class NodeClass2 {}
class NodeClass3 {}
class NodeClass4 {}
class NodeClass5 {}

View File

@@ -0,0 +1,252 @@
<?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\Tests\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Test case for testing the saving and referencing of query identifiers.
*
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Janne Vanhala <jpvanhal@cc.hut.fi>
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://www.doctrine-project.org
* @since 2.0
* @version $Revision$
*/
class DqlGenerationTest extends \Doctrine\Tests\OrmTestCase
{
protected function setUp() {
$this->markTestSkipped('Not yet implemented.');
}
protected function createQuery()
{
return $this->_em->createQuery();
}
public function testSelect()
{
$query = $this->createQuery();
// select and from
$query->setDql('FROM User u');
$this->assertEquals('FROM User u', $query->getDql()); // Internally we use SELECT * FROM User u to process the DQL
$query->free();
$query->select()->from('User u');
$this->assertEquals('SELECT * FROM User u', $query->getDql());
$query->free();
$query->select('u.*')->from('User u');
$this->assertEquals('SELECT u.* FROM User u', $query->getDql());
$query->free();
$query->select('u.id')->from('User u');
$this->assertEquals('SELECT u.id FROM User u', $query->getDql());
$query->free();
$query->select('u.id, u.name')->from('User u');
$this->assertEquals('SELECT u.id, u.name FROM User u', $query->getDql());
$query->free();
$query->select('u.name AS myCustomName')->from('User u');
$this->assertEquals('SELECT u.name AS myCustomName FROM User u', $query->getDql());
$query->free();
$query->select('u.id')->select('u.name')->from('User u');
$this->assertEquals('SELECT u.id, u.name FROM User u', $query->getDql());
$query->free();
}
public function testSelectDistinct()
{
$query = $this->createQuery();
$query->select()->distinct()->from('User u');
$this->assertEquals('SELECT DISTINCT * FROM User u', $query->getDql());
$query->free();
$query->select('u.name')->distinct(false)->from('User u');
$this->assertEquals('SELECT u.name FROM User u', $query->getDql());
$query->free();
$query->select()->distinct(false)->from('User u');
$this->assertEquals('SELECT * FROM User u', $query->getDql());
$query->free();
$query->select('u.name')->distinct()->from('User u');
$this->assertEquals('SELECT DISTINCT u.name FROM User u', $query->getDql());
$query->free();
$query->select('u.name, u.email')->distinct()->from('User u');
$this->assertEquals('SELECT DISTINCT u.name, u.email FROM User u', $query->getDql());
$query->free();
$query->select('u.name')->select('u.email')->distinct()->from('User u');
$this->assertEquals('SELECT DISTINCT u.name, u.email FROM User u', $query->getDql());
$query->free();
$query->select('DISTINCT u.name')->from('User u');
$this->assertEquals('SELECT DISTINCT u.name FROM User u', $query->getDql());
$query->free();
$query->select('DISTINCT u.name, u.email')->from('User u');
$this->assertEquals('SELECT DISTINCT u.name, u.email FROM User u', $query->getDql());
$query->free();
$query->select('DISTINCT u.name')->select('u.email')->from('User u');
$this->assertEquals('SELECT DISTINCT u.name, u.email FROM User u', $query->getDql());
$query->free();
}
public function testSelectJoin()
{
$query = $this->createQuery();
$query->select('u.*')->from('User u')->join('u.Group g')->where('g.id = ?', 1);
$this->assertEquals('SELECT u.* FROM User u INNER JOIN u.Group g WHERE g.id = ?', $query->getDql());
$this->assertEquals(array(1), $query->getParams());
$query->free();
$query->select('u.*')->from('User u')->innerJoin('u.Group g')->where('g.id = ?', 1);
$this->assertEquals('SELECT u.* FROM User u INNER JOIN u.Group g WHERE g.id = ?', $query->getDql());
$this->assertEquals(array(1), $query->getParams());
$query->free();
$query->select('u.*')->from('User u')->leftJoin('u.Group g')->where('g.id IS NULL');
$this->assertEquals('SELECT u.* FROM User u LEFT JOIN u.Group g WHERE g.id IS NULL', $query->getDql());
$query->free();
$query->select('u.*')->from('User u')->leftJoin('u.UserGroup ug')->leftJoin('ug.Group g')->where('g.name = ?', 'admin');
$this->assertEquals('SELECT u.* FROM User u LEFT JOIN u.UserGroup ug LEFT JOIN ug.Group g WHERE g.name = ?', $query->getDql());
$query->free();
}
public function testSelectWhere()
{
$query = $this->createQuery();
$query->select('u.name')->from('User u')->where('u.id = ?', 1);
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ?', $query->getDql());
$this->assertEquals(array(1), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.id = ? AND u.type != ?', array(1, 'admin'));
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ? AND u.type != ?', $query->getDql());
$this->assertEquals(array(1, 'admin'), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.id = ?', 1)->andWhere('u.type != ?', 'admin');
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ? AND u.type != ?', $query->getDql());
$this->assertEquals(array(1, 'admin'), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('( u.id = ?', 1)->andWhere('u.type != ? )', 'admin');
$this->assertEquals('SELECT u.name FROM User u WHERE ( u.id = ? AND u.type != ? )', $query->getDql());
$this->assertEquals(array(1, 'admin'), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.id = ? OR u.type != ?', array(1, 'admin'));
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ? OR u.type != ?', $query->getDql());
$this->assertEquals(array(1, 'admin'), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.id = ?', 1)->orWhere('u.type != ?', 'admin');
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ? OR u.type != ?', $query->getDql());
$this->assertEquals(array(1, 'admin'), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->andwhere('u.id = ?', 1)->andWhere('u.type != ?', 'admin')->orWhere('u.email = ?', 'admin@localhost');
$this->assertEquals('SELECT u.name FROM User u WHERE u.id = ? AND u.type != ? OR u.email = ?', $query->getDql());
$this->assertEquals(array(1, 'admin', 'admin@localhost'), $query->getParams());
$query->free();
}
public function testSelectWhereIn()
{
$query = $this->createQuery();
$query->select('u.name')->from('User u')->whereIn('u.id', array(1, 2, 3, 4, 5));
$this->assertEquals('SELECT u.name FROM User u WHERE u.id IN (?, ?, ?, ?, ?)', $query->getDql());
$this->assertEquals(array(1, 2, 3, 4, 5), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->whereNotIn('u.id', array(1, 2, 3));
$this->assertEquals('SELECT u.name FROM User u WHERE u.id NOT IN (?, ?, ?)', $query->getDql());
$this->assertEquals(array(1, 2, 3), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.type = ?', 'admin')->andWhereIn('u.id', array(1, 2));
$this->assertEquals('SELECT u.name FROM User u WHERE u.type = ? AND u.id IN (?, ?)', $query->getDql());
$this->assertEquals(array('admin', 1, 2), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->where('u.type = ?', 'admin')->andWhereNotIn('u.id', array(1, 2));
$this->assertEquals('SELECT u.name FROM User u WHERE u.type = ? AND u.id NOT IN (?, ?)', $query->getDql());
$this->assertEquals(array('admin', 1, 2), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->whereIn('u.type', array('admin', 'moderator'))->andWhereNotIn('u.id', array(1, 2, 3, 4));
$this->assertEquals('SELECT u.name FROM User u WHERE u.type IN (?, ?) AND u.id NOT IN (?, ?, ?, ?)', $query->getDql());
$this->assertEquals(array('admin', 'moderator', 1, 2, 3, 4), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->whereIn('u.type', array('admin', 'moderator'))->orWhereIn('u.id', array(1, 2, 3, 4));
$this->assertEquals('SELECT u.name FROM User u WHERE u.type IN (?, ?) OR u.id IN (?, ?, ?, ?)', $query->getDql());
$this->assertEquals(array('admin', 'moderator', 1, 2, 3, 4), $query->getParams());
$query->free();
$query->select('u.name')->from('User u')->whereIn('u.type', array('admin', 'moderator'))->andWhereNotIn('u.id', array(1, 2))->orWhereNotIn('u.type', array('admin', 'moderator'))->andWhereNotIn('u.email', array('user@localhost', 'guest@localhost'));
$this->assertEquals('SELECT u.name FROM User u WHERE u.type IN (?, ?) AND u.id NOT IN (?, ?) OR u.type NOT IN (?, ?) AND u.email NOT IN (?, ?)', $query->getDql());
$this->assertEquals(array('admin', 'moderator', 1, 2, 'admin', 'moderator', 'user@localhost', 'guest@localhost'), $query->getParams());
$query->free();
}
public function testDelete()
{
$query = $this->createQuery();
$query->setDql('DELETE CmsUser u');
$this->assertEquals('DELETE CmsUser u', $query->getDql());
$query->free();
$query->delete()->from('CmsUser u');
$this->assertEquals('DELETE FROM CmsUser u', $query->getDql());
$query->free();
$query->delete()->from('CmsUser u')->where('u.id = ?', 1);
$this->assertEquals('DELETE FROM CmsUser u WHERE u.id = ?', $query->getDql());
$query->free();
$query->delete()->from('CmsUser u')->where('u.username = ?', 'gblanco')->orWhere('u.name = ?', 'Guilherme');
$this->assertEquals('DELETE FROM CmsUser u WHERE u.username = ? OR u.name = ?', $query->getDql());
$query->free();
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Doctrine\Tests\ORM\Entity;
require_once __DIR__ . '/../../TestInit.php';
class ConstructorTest extends \Doctrine\Tests\OrmTestCase
{
public function testFieldInitializationInConstructor()
{
$entity = new ConstructorTestEntity1("romanb");
$this->assertEquals("romanb", $entity->username);
}
}
class ConstructorTestEntity1
{
private $id;
public $username;
public function __construct($username = null)
{
if ($username !== null) {
$this->username = $username;
}
}
}

View File

@@ -0,0 +1,158 @@
<?php
namespace Doctrine\Tests\ORM;
require_once __DIR__ . '/../TestInit.php';
class EntityManagerTest extends \Doctrine\Tests\OrmTestCase
{
private $_em;
function setUp()
{
parent::setUp();
$this->_em = $this->_getTestEntityManager();
}
/**
* @group DDC-899
*/
public function testIsOpen()
{
$this->assertTrue($this->_em->isOpen());
$this->_em->close();
$this->assertFalse($this->_em->isOpen());
}
public function testGetConnection()
{
$this->assertInstanceOf('Doctrine\DBAL\Connection', $this->_em->getConnection());
}
public function testGetMetadataFactory()
{
$this->assertInstanceOf('Doctrine\ORM\Mapping\ClassMetadataFactory', $this->_em->getMetadataFactory());
}
public function testGetConfiguration()
{
$this->assertInstanceOf('Doctrine\ORM\Configuration', $this->_em->getConfiguration());
}
public function testGetUnitOfWork()
{
$this->assertInstanceOf('Doctrine\ORM\UnitOfWork', $this->_em->getUnitOfWork());
}
public function testGetProxyFactory()
{
$this->assertInstanceOf('Doctrine\ORM\Proxy\ProxyFactory', $this->_em->getProxyFactory());
}
public function testGetEventManager()
{
$this->assertInstanceOf('Doctrine\Common\EventManager', $this->_em->getEventManager());
}
public function testCreateNativeQuery()
{
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$query = $this->_em->createNativeQuery('SELECT foo', $rsm);
$this->assertSame('SELECT foo', $query->getSql());
}
public function testCreateQueryBuilder()
{
$this->assertInstanceOf('Doctrine\ORM\QueryBuilder', $this->_em->createQueryBuilder());
}
public function testCreateQueryBuilderAliasValid()
{
$q = $this->_em->createQueryBuilder()
->select('u')->from('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$q2 = clone $q;
$this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q->getQuery()->getDql());
$this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q2->getQuery()->getDql());
$q3 = clone $q;
$this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q3->getQuery()->getDql());
}
public function testCreateQuery_DqlIsOptional()
{
$this->assertInstanceOf('Doctrine\ORM\Query', $this->_em->createQuery());
}
public function testGetPartialReference()
{
$user = $this->_em->getPartialReference('Doctrine\Tests\Models\CMS\CmsUser', 42);
$this->assertTrue($this->_em->contains($user));
$this->assertEquals(42, $user->id);
$this->assertNull($user->getName());
}
public function testCreateQuery()
{
$q = $this->_em->createQuery('SELECT 1');
$this->assertInstanceOf('Doctrine\ORM\Query', $q);
$this->assertEquals('SELECT 1', $q->getDql());
}
static public function dataMethodsAffectedByNoObjectArguments()
{
return array(
array('persist'),
array('remove'),
array('merge'),
array('refresh'),
array('detach')
);
}
/**
* @dataProvider dataMethodsAffectedByNoObjectArguments
* @expectedException \InvalidArgumentException
* @param string $methodName
*/
public function testThrowsExceptionOnNonObjectValues($methodName) {
$this->_em->$methodName(null);
}
static public function dataAffectedByErrorIfClosedException()
{
return array(
array('flush'),
array('persist'),
array('remove'),
array('merge'),
array('refresh'),
);
}
/**
* @dataProvider dataAffectedByErrorIfClosedException
* @param string $methodName
*/
public function testAffectedByErrorIfClosedException($methodName)
{
$this->setExpectedException('Doctrine\ORM\ORMException', 'closed');
$this->_em->close();
$this->_em->$methodName(new \stdClass());
}
/**
* @group DDC-1125
*/
public function testTransactionalAcceptsReturn()
{
$return = $this->_em->transactional(function ($em) {
return 'foo';
});
$this->assertEquals('foo', $return);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Collections\Collection;
require_once __DIR__ . '/../../TestInit.php';
/**
* Base class for testing a many-to-many association mapping (without inheritance).
*/
class AbstractManyToManyAssociationTestCase extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected $_firstField;
protected $_secondField;
protected $_table;
public function assertForeignKeysContain($firstId, $secondId)
{
$this->assertEquals(1, $this->_countForeignKeys($firstId, $secondId));
}
public function assertForeignKeysNotContain($firstId, $secondId)
{
$this->assertEquals(0, $this->_countForeignKeys($firstId, $secondId));
}
protected function _countForeignKeys($firstId, $secondId)
{
return count($this->_em->getConnection()->executeQuery("
SELECT {$this->_firstField}
FROM {$this->_table}
WHERE {$this->_firstField} = ?
AND {$this->_secondField} = ?
", array($firstId, $secondId))->fetchAll());
}
public function assertCollectionEquals(Collection $first, Collection $second)
{
return $first->forAll(function($k, $e) use($second) { return $second->contains($e); });
}
}

View File

@@ -0,0 +1,598 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional tests for the Single Table Inheritance mapping strategy.
*
* @author robo
*/
class AdvancedAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Phrase'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\PhraseType'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Definition'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Lemma'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Type')
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
public function testIssue()
{
//setup
$phrase = new Phrase;
$phrase->setPhrase('lalala');
$type = new PhraseType;
$type->setType('nonsense');
$type->setAbbreviation('non');
$def1 = new Definition;
$def1->setDefinition('def1');
$def2 = new Definition;
$def2->setDefinition('def2');
$phrase->setType($type);
$phrase->addDefinition($def1);
$phrase->addDefinition($def2);
$this->_em->persist($phrase);
$this->_em->persist($type);
$this->_em->flush();
$this->_em->clear();
//end setup
// test1 - lazy-loading many-to-one after find()
$phrase2 = $this->_em->find('Doctrine\Tests\ORM\Functional\Phrase', $phrase->getId());
$this->assertTrue(is_numeric($phrase2->getType()->getId()));
$this->_em->clear();
// test2 - eager load in DQL query
$query = $this->_em->createQuery("SELECT p,t FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t");
$res = $query->getResult();
$this->assertEquals(1, count($res));
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\PhraseType', $res[0]->getType());
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $res[0]->getType()->getPhrases());
$this->assertFalse($res[0]->getType()->getPhrases()->isInitialized());
$this->_em->clear();
// test2 - eager load in DQL query with double-join back and forth
$query = $this->_em->createQuery("SELECT p,t,pp FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t JOIN t.phrases pp");
$res = $query->getResult();
$this->assertEquals(1, count($res));
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\PhraseType', $res[0]->getType());
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $res[0]->getType()->getPhrases());
$this->assertTrue($res[0]->getType()->getPhrases()->isInitialized());
$this->_em->clear();
// test3 - lazy-loading one-to-many after find()
$phrase3 = $this->_em->find('Doctrine\Tests\ORM\Functional\Phrase', $phrase->getId());
$definitions = $phrase3->getDefinitions();
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $definitions);
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Definition', $definitions[0]);
$this->_em->clear();
// test4 - lazy-loading after DQL query
$query = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\Phrase p");
$res = $query->getResult();
$definitions = $res[0]->getDefinitions();
$this->assertEquals(1, count($res));
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Definition', $definitions[0]);
$this->assertEquals(2, $definitions->count());
}
public function testManyToMany()
{
$lemma = new Lemma;
$lemma->setLemma('abu');
$type = new Type();
$type->setType('nonsense');
$type->setAbbreviation('non');
$lemma->addType($type);
$this->_em->persist($lemma);
$this->_em->persist($type);
$this->_em->flush();
// test5 ManyToMany
$query = $this->_em->createQuery("SELECT l FROM Doctrine\Tests\ORM\Functional\Lemma l");
$res = $query->getResult();
$types = $res[0]->getTypes();
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Type', $types[0]);
}
}
/**
* @Entity
* @Table(name="lemma")
*/
class Lemma {
const CLASS_NAME = __CLASS__;
/**
* @var int
* @Id
* @Column(type="integer", name="lemma_id")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* @var string
* @Column(type="string", name="lemma_name", unique=true, length=255)
*/
private $lemma;
/**
* @var kateglo\application\utilities\collections\ArrayCollection
* @ManyToMany(targetEntity="Type", mappedBy="lemmas", cascade={"persist"})
*/
private $types;
public function __construct() {
$this->types = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
*
* @return int
*/
public function getId(){
return $this->id;
}
/**
*
* @param string $lemma
* @return void
*/
public function setLemma($lemma){
$this->lemma = $lemma;
}
/**
*
* @return string
*/
public function getLemma(){
return $this->lemma;
}
/**
*
* @param kateglo\application\models\Type $type
* @return void
*/
public function addType(Type $type){
if (!$this->types->contains($type)) {
$this->types[] = $type;
$type->addLemma($this);
}
}
/**
*
* @param kateglo\application\models\Type $type
* @return void
*/
public function removeType(Type $type)
{
$removed = $this->sources->removeElement($type);
if ($removed !== null) {
$removed->removeLemma($this);
}
}
/**
*
* @return kateglo\application\helpers\collections\ArrayCollection
*/
public function getTypes()
{
return $this->types;
}
}
/**
* @Entity
* @Table(name="type")
*/
class Type {
const CLASS_NAME = __CLASS__;
/**
*
* @var int
* @Id
* @Column(type="integer", name="type_id")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* @var string
* @Column(type="string", name="type_name", unique=true)
*/
private $type;
/**
*
* @var string
* @Column(type="string", name="type_abbreviation", unique=true)
*/
private $abbreviation;
/**
* @var kateglo\application\helpers\collections\ArrayCollection
* @ManyToMany(targetEntity="Lemma")
* @JoinTable(name="lemma_type",
* joinColumns={@JoinColumn(name="type_id", referencedColumnName="type_id")},
* inverseJoinColumns={@JoinColumn(name="lemma_id", referencedColumnName="lemma_id")}
* )
*/
private $lemmas;
public function __construct(){
$this->lemmas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
*
* @return int
*/
public function getId(){
return $this->id;
}
/**
*
* @param string $type
* @return void
*/
public function setType($type){
$this->type = $type;
}
/**
*
* @return string
*/
public function getType(){
return $this->type;
}
/**
*
* @param string $abbreviation
* @return void
*/
public function setAbbreviation($abbreviation){
$this->abbreviation = $abbreviation;
}
/**
*
* @return string
*/
public function getAbbreviation(){
return $this->abbreviation;
}
/**
*
* @param kateglo\application\models\Lemma $lemma
* @return void
*/
public function addLemma(Lemma $lemma)
{
if (!$this->lemmas->contains($lemma)) {
$this->lemmas[] = $lemma;
$lemma->addType($this);
}
}
/**
*
* @param kateglo\application\models\Lemma $lemma
* @return void
*/
public function removeLEmma(Lemma $lemma)
{
$removed = $this->lemmas->removeElement($lemma);
if ($removed !== null) {
$removed->removeType($this);
}
}
/**
*
* @return kateglo\application\helpers\collections\ArrayCollection
*/
public function getCategories()
{
return $this->categories;
}
}
/**
* @Entity
* @Table(name="phrase")
*/
class Phrase {
const CLASS_NAME = __CLASS__;
/**
* @Id
* @Column(type="integer", name="phrase_id")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string", name="phrase_name", unique=true, length=255)
*/
private $phrase;
/**
* @ManyToOne(targetEntity="PhraseType")
* @JoinColumn(name="phrase_type_id", referencedColumnName="phrase_type_id")
*/
private $type;
/**
* @OneToMany(targetEntity="Definition", mappedBy="phrase", cascade={"persist"})
*/
private $definitions;
public function __construct() {
$this->definitions = new \Doctrine\Common\Collections\ArrayCollection;
}
/**
*
* @param Definition $definition
* @return void
*/
public function addDefinition(Definition $definition){
$this->definitions[] = $definition;
$definition->setPhrase($this);
}
/**
* @return int
*/
public function getId(){
return $this->id;
}
/**
* @param string $phrase
* @return void
*/
public function setPhrase($phrase){
$this->phrase = $phrase;
}
/**
* @return string
*/
public function getPhrase(){
return $this->phrase;
}
/**
*
* @param PhraseType $type
* @return void
*/
public function setType(PhraseType $type){
$this->type = $type;
}
/**
*
* @return PhraseType
*/
public function getType(){
return $this->type;
}
/**
*
* @return ArrayCollection
*/
public function getDefinitions(){
return $this->definitions;
}
}
/**
* @Entity
* @Table(name="phrase_type")
*/
class PhraseType {
const CLASS_NAME = __CLASS__;
/**
* @Id
* @Column(type="integer", name="phrase_type_id")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string", name="phrase_type_name", unique=true)
*/
private $type;
/**
* @Column(type="string", name="phrase_type_abbreviation", unique=true)
*/
private $abbreviation;
/**
* @OneToMany(targetEntity="Phrase", mappedBy="type")
*/
private $phrases;
public function __construct() {
$this->phrases = new \Doctrine\Common\Collections\ArrayCollection;
}
/**
* @return int
*/
public function getId(){
return $this->id;
}
/**
* @param string $type
* @return void
*/
public function setType($type){
$this->type = $type;
}
/**
* @return string
*/
public function getType(){
return $this->type;
}
/**
* @param string $abbreviation
* @return void
*/
public function setAbbreviation($abbreviation){
$this->abbreviation = $abbreviation;
}
/**
* @return string
*/
public function getAbbreviation(){
return $this->abbreviation;
}
/**
* @param ArrayCollection $phrases
* @return void
*/
public function setPhrases($phrases){
$this->phrases = $phrases;
}
/**
*
* @return ArrayCollection
*/
public function getPhrases(){
return $this->phrases;
}
}
/**
* @Entity
* @Table(name="definition")
*/
class Definition {
const CLASS_NAME = __CLASS__;
/**
* @Id
* @Column(type="integer", name="definition_id")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Phrase")
* @JoinColumn(name="definition_phrase_id", referencedColumnName="phrase_id")
*/
private $phrase;
/**
* @Column(type="text", name="definition_text")
*/
private $definition;
/**
* @return int
*/
public function getId(){
return $this->id;
}
/**
* @param Phrase $phrase
* @return void
*/
public function setPhrase(Phrase $phrase){
$this->phrase = $phrase;
}
/**
* @return Phrase
*/
public function getPhrase(){
return $this->phrase;
}
public function removePhrase() {
if ($this->phrase !== null) {
/*@var $phrase kateglo\application\models\Phrase */
$phrase = $this->phrase;
$this->phrase = null;
$phrase->removeDefinition($this);
}
}
/**
* @param string $definition
* @return void
*/
public function setDefinition($definition){
$this->definition = $definition;
}
/**
* @return string
*/
public function getDefinition(){
return $this->definition;
}
}

View File

@@ -0,0 +1,181 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\Company\CompanyEmployee,
Doctrine\Tests\Models\Company\CompanyManager,
Doctrine\Tests\Models\Company\CompanyPerson,
Doctrine\Tests\Models\Company\CompanyCar;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional Query tests.
*
* @author Benjamin <kontakt@beberlei.de>
*/
class AdvancedDqlQueryTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('company');
parent::setUp();
$this->generateFixture();
}
public function testAggregateWithHavingClause()
{
$dql = 'SELECT p.department, AVG(p.salary) AS avgSalary '.
'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '.
'GROUP BY p.department HAVING SUM(p.salary) > 200000 ORDER BY p.department';
$result = $this->_em->createQuery($dql)->getScalarResult();
$this->assertEquals(2, count($result));
$this->assertEquals('IT', $result[0]['department']);
$this->assertEquals(150000, $result[0]['avgSalary']);
$this->assertEquals('IT2', $result[1]['department']);
$this->assertEquals(600000, $result[1]['avgSalary']);
}
public function testUnnamedScalarResultsAreOneBased()
{
$dql = 'SELECT p.department, AVG(p.salary) '.
'FROM Doctrine\Tests\Models\Company\CompanyEmployee p '.
'GROUP BY p.department HAVING SUM(p.salary) > 200000 ORDER BY p.department';
$result = $this->_em->createQuery($dql)->getScalarResult();
$this->assertEquals(2, count($result));
$this->assertEquals(150000, $result[0][1]);
$this->assertEquals(600000, $result[1][1]);
}
public function testOrderByResultVariableCollectionSize()
{
$dql = 'SELECT p.name, size(p.friends) AS friends ' .
'FROM Doctrine\Tests\Models\Company\CompanyPerson p ' .
'WHERE p.friends IS NOT EMPTY ' .
'ORDER BY friends DESC, p.name DESC';
$result = $this->_em->createQuery($dql)->getScalarResult();
$this->assertEquals(4, count($result));
$this->assertEquals("Jonathan W.", $result[0]['name']);
$this->assertEquals(3, $result[0]['friends']);
$this->assertEquals('Guilherme B.', $result[1]['name']);
$this->assertEquals(2, $result[1]['friends']);
$this->assertEquals('Benjamin E.', $result[2]['name']);
$this->assertEquals(2, $result[2]['friends']);
$this->assertEquals('Roman B.', $result[3]['name']);
$this->assertEquals(1, $result[3]['friends']);
}
public function testIsNullAssocation()
{
$dql = 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p '.
'WHERE p.spouse IS NULL';
$result = $this->_em->createQuery($dql)->getResult();
$this->assertEquals(2, count($result));
$this->assertTrue($result[0]->getId() > 0);
$this->assertNull($result[0]->getSpouse());
$this->assertTrue($result[1]->getId() > 0);
$this->assertNull($result[1]->getSpouse());
}
public function testSelectSubselect()
{
$dql = 'SELECT p, (SELECT c.brand FROM Doctrine\Tests\Models\Company\CompanyCar c WHERE p.car = c) brandName '.
'FROM Doctrine\Tests\Models\Company\CompanyManager p';
$result = $this->_em->createQuery($dql)->getArrayResult();
$this->assertEquals(1, count($result));
$this->assertEquals("Caramba", $result[0]['brandName']);
}
public function testInSubselect()
{
$dql = "SELECT p.name FROM Doctrine\Tests\Models\Company\CompanyPerson p ".
"WHERE p.name IN (SELECT n.name FROM Doctrine\Tests\Models\Company\CompanyPerson n WHERE n.name = 'Roman B.')";
$result = $this->_em->createQuery($dql)->getScalarResult();
$this->assertEquals(1, count($result));
$this->assertEquals('Roman B.', $result[0]['name']);
}
public function testGroupByMultipleFields()
{
$dql = 'SELECT p.department, p.name, count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p '.
'GROUP BY p.department, p.name';
$result = $this->_em->createQuery($dql)->getResult();
$this->assertEquals(4, count($result));
}
public function testUpdateAs()
{
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.salary = 1';
$this->_em->createQuery($dql)->execute();
$this->assertTrue(count($this->_em->createQuery(
'SELECT count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p WHERE p.salary = 1')->getResult()) > 0);
}
/*public function testDeleteAs()
{
$dql = 'DELETE Doctrine\Tests\Models\Company\CompanyEmployee AS p';
$this->_em->createQuery($dql)->getResult();
$this->assertEquals(0, count($this->_em->createQuery(
'SELECT count(p) FROM Doctrine\Tests\Models\Company\CompanyEmployee p')->getResult()));
}*/
public function generateFixture()
{
$car = new CompanyCar('Caramba');
$manager1 = new CompanyManager();
$manager1->setName('Roman B.');
$manager1->setTitle('Foo');
$manager1->setDepartment('IT');
$manager1->setSalary(100000);
$manager1->setCar($car);
$person2 = new CompanyEmployee();
$person2->setName('Benjamin E.');
$person2->setDepartment('IT');
$person2->setSalary(200000);
$person3 = new CompanyEmployee();
$person3->setName('Guilherme B.');
$person3->setDepartment('IT2');
$person3->setSalary(400000);
$person4 = new CompanyEmployee();
$person4->setName('Jonathan W.');
$person4->setDepartment('IT2');
$person4->setSalary(800000);
$person2->setSpouse($person3);
$manager1->addFriend($person4);
$person2->addFriend($person3);
$person2->addFriend($person4);
$person3->addFriend($person4);
$this->_em->persist($car);
$this->_em->persist($manager1);
$this->_em->persist($person2);
$this->_em->persist($person3);
$this->_em->persist($person4);
$this->_em->flush();
$this->_em->clear();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,470 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
use Doctrine\Tests\Models\Company\CompanyPerson,
Doctrine\Tests\Models\Company\CompanyEmployee,
Doctrine\Tests\Models\Company\CompanyManager,
Doctrine\Tests\Models\Company\CompanyOrganization,
Doctrine\Tests\Models\Company\CompanyEvent,
Doctrine\Tests\Models\Company\CompanyAuction,
Doctrine\Tests\Models\Company\CompanyRaffle,
Doctrine\Tests\Models\Company\CompanyCar;
/**
* Functional tests for the Class Table Inheritance mapping strategy.
*
* @author robo
*/
class ClassTableInheritanceTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('company');
parent::setUp();
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
}
public function testCRUD()
{
$person = new CompanyPerson;
$person->setName('Roman S. Borschel');
$this->_em->persist($person);
$employee = new CompanyEmployee;
$employee->setName('Roman S. Borschel');
$employee->setSalary(100000);
$employee->setDepartment('IT');
$this->_em->persist($employee);
$employee->setName('Guilherme Blanco');
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select p from Doctrine\Tests\Models\Company\CompanyPerson p order by p.name desc");
$entities = $query->getResult();
$this->assertEquals(2, count($entities));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $entities[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $entities[1]);
$this->assertTrue(is_numeric($entities[0]->getId()));
$this->assertTrue(is_numeric($entities[1]->getId()));
$this->assertEquals('Roman S. Borschel', $entities[0]->getName());
$this->assertEquals('Guilherme Blanco', $entities[1]->getName());
$this->assertEquals(100000, $entities[1]->getSalary());
$this->_em->clear();
$query = $this->_em->createQuery("select p from Doctrine\Tests\Models\Company\CompanyEmployee p");
$entities = $query->getResult();
$this->assertEquals(1, count($entities));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $entities[0]);
$this->assertTrue(is_numeric($entities[0]->getId()));
$this->assertEquals('Guilherme Blanco', $entities[0]->getName());
$this->assertEquals(100000, $entities[0]->getSalary());
$this->_em->clear();
$guilherme = $this->_em->getRepository(get_class($employee))->findOneBy(array('name' => 'Guilherme Blanco'));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $guilherme);
$this->assertEquals('Guilherme Blanco', $guilherme->getName());
$this->_em->clear();
$query = $this->_em->createQuery("update Doctrine\Tests\Models\Company\CompanyEmployee p set p.name = ?1, p.department = ?2 where p.name='Guilherme Blanco' and p.salary = ?3");
$query->setParameter(1, 'NewName', 'string');
$query->setParameter(2, 'NewDepartment');
$query->setParameter(3, 100000);
$query->getSql();
$numUpdated = $query->execute();
$this->assertEquals(1, $numUpdated);
$query = $this->_em->createQuery("delete from Doctrine\Tests\Models\Company\CompanyPerson p");
$numDeleted = $query->execute();
$this->assertEquals(2, $numDeleted);
}
public function testMultiLevelUpdateAndFind() {
$manager = new CompanyManager;
$manager->setName('Roman S. Borschel');
$manager->setSalary(100000);
$manager->setDepartment('IT');
$manager->setTitle('CTO');
$this->_em->persist($manager);
$this->_em->flush();
$manager->setName('Roman B.');
$manager->setSalary(119000);
$manager->setTitle('CEO');
$this->_em->persist($manager);
$this->_em->flush();
$this->_em->clear();
$manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyManager', $manager);
$this->assertEquals('Roman B.', $manager->getName());
$this->assertEquals(119000, $manager->getSalary());
$this->assertEquals('CEO', $manager->getTitle());
$this->assertTrue(is_numeric($manager->getId()));
}
public function testFindOnBaseClass() {
$manager = new CompanyManager;
$manager->setName('Roman S. Borschel');
$manager->setSalary(100000);
$manager->setDepartment('IT');
$manager->setTitle('CTO');
$this->_em->persist($manager);
$this->_em->flush();
$this->_em->clear();
$person = $this->_em->find('Doctrine\Tests\Models\Company\CompanyPerson', $manager->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyManager', $person);
$this->assertEquals('Roman S. Borschel', $person->getName());
$this->assertEquals(100000, $person->getSalary());
$this->assertEquals('CTO', $person->getTitle());
$this->assertTrue(is_numeric($person->getId()));
//$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyCar', $person->getCar());
}
public function testSelfReferencingOneToOne() {
$manager = new CompanyManager;
$manager->setName('John Smith');
$manager->setSalary(100000);
$manager->setDepartment('IT');
$manager->setTitle('CTO');
$wife = new CompanyPerson;
$wife->setName('Mary Smith');
$wife->setSpouse($manager);
$this->assertSame($manager, $wife->getSpouse());
$this->assertSame($wife, $manager->getSpouse());
$this->_em->persist($manager);
$this->_em->persist($wife);
$this->_em->flush();
//var_dump($this->_em->getConnection()->fetchAll('select * from company_persons'));
//var_dump($this->_em->getConnection()->fetchAll('select * from company_employees'));
//var_dump($this->_em->getConnection()->fetchAll('select * from company_managers'));
$this->_em->clear();
$query = $this->_em->createQuery('select p, s from Doctrine\Tests\Models\Company\CompanyPerson p join p.spouse s where p.name=\'Mary Smith\'');
$result = $query->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $result[0]);
$this->assertEquals('Mary Smith', $result[0]->getName());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result[0]->getSpouse());
$this->assertEquals('John Smith', $result[0]->getSpouse()->getName());
$this->assertSame($result[0], $result[0]->getSpouse()->getSpouse());
}
public function testSelfReferencingManyToMany()
{
$person1 = new CompanyPerson;
$person1->setName('Roman');
$person2 = new CompanyPerson;
$person2->setName('Jonathan');
$person1->addFriend($person2);
$this->assertEquals(1, count($person1->getFriends()));
$this->assertEquals(1, count($person2->getFriends()));
$this->_em->persist($person1);
$this->_em->persist($person2);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\Company\CompanyPerson p join p.friends f where p.name=?1');
$query->setParameter(1, 'Roman');
$result = $query->getResult();
$this->assertEquals(1, count($result));
$this->assertEquals(1, count($result[0]->getFriends()));
$this->assertEquals('Roman', $result[0]->getName());
$friends = $result[0]->getFriends();
$this->assertEquals('Jonathan', $friends[0]->getName());
}
public function testLazyLoading1()
{
$org = new CompanyOrganization;
$event1 = new CompanyAuction;
$event1->setData('auction');
$org->addEvent($event1);
$event2 = new CompanyRaffle;
$event2->setData('raffle');
$org->addEvent($event2);
$this->_em->persist($org);
$this->_em->flush();
$this->_em->clear();
$orgId = $org->getId();
$q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyOrganization a where a.id = ?1');
$q->setParameter(1, $orgId);
$result = $q->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyOrganization', $result[0]);
$this->assertNull($result[0]->getMainEvent());
$events = $result[0]->getEvents();
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $events);
$this->assertFalse($events->isInitialized());
$this->assertEquals(2, count($events));
if ($events[0] instanceof CompanyAuction) {
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyRaffle', $events[1]);
} else {
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyRaffle', $events[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $events[1]);
}
}
public function testLazyLoading2()
{
$org = new CompanyOrganization;
$event1 = new CompanyAuction;
$event1->setData('auction');
$org->setMainEvent($event1);
$this->_em->persist($org);
$this->_em->flush();
$this->_em->clear();
$q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyEvent a where a.id = ?1');
$q->setParameter(1, $event1->getId());
$result = $q->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $result[0], sprintf("Is of class %s",get_class($result[0])));
$this->_em->clear();
$q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyOrganization a where a.id = ?1');
$q->setParameter(1, $org->getId());
$result = $q->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyOrganization', $result[0]);
$mainEvent = $result[0]->getMainEvent();
// mainEvent should have been loaded because it can't be lazy
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $mainEvent);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $mainEvent);
}
/**
* @group DDC-368
*/
public function testBulkUpdateIssueDDC368()
{
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.salary = 1';
$this->_em->createQuery($dql)->execute();
$this->assertTrue(count($this->_em->createQuery(
'SELECT count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p WHERE p.salary = 1')
->getResult()) > 0);
}
/**
* @group DDC-1341
*/
public function testBulkUpdateNonScalarParameterDDC1341()
{
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.startDate = ?0 WHERE p.department = ?1';
$query = $this->_em->createQuery($dql)
->setParameter(0, new \DateTime())
->setParameter(1, 'IT');
$result = $query->execute();
}
/**
* @group DDC-130
*/
public function testDeleteJoinTableRecords()
{
#$this->markTestSkipped('Nightmare! friends adds both ID 6-7 and 7-6 into two rows of the join table. How to detect this?');
$employee1 = new CompanyEmployee();
$employee1->setName('gblanco');
$employee1->setSalary(0);
$employee1->setDepartment('IT');
$employee2 = new CompanyEmployee();
$employee2->setName('jwage');
$employee2->setSalary(0);
$employee2->setDepartment('IT');
$employee1->addFriend($employee2);
$this->_em->persist($employee1);
$this->_em->persist($employee2);
$this->_em->flush();
$employee1Id = $employee1->getId();
$this->_em->remove($employee1);
$this->_em->flush();
$this->assertNull($this->_em->find(get_class($employee1), $employee1Id));
}
/**
* @group DDC-728
*/
public function testQueryForInheritedSingleValuedAssociation()
{
$manager = new CompanyManager();
$manager->setName('gblanco');
$manager->setSalary(1234);
$manager->setTitle('Awesome!');
$manager->setDepartment('IT');
$person = new CompanyPerson();
$person->setName('spouse');
$manager->setSpouse($person);
$this->_em->persist($manager);
$this->_em->persist($person);
$this->_em->flush();
$this->_em->clear();
$dql = "SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m WHERE m.spouse = ?1";
$dqlManager = $this->_em->createQuery($dql)->setParameter(1, $person->getId())->getSingleResult();
$this->assertEquals($manager->getId(), $dqlManager->getId());
$this->assertEquals($person->getId(), $dqlManager->getSpouse()->getId());
}
/**
* @group DDC-817
*/
public function testFindByAssociation()
{
$manager = new CompanyManager();
$manager->setName('gblanco');
$manager->setSalary(1234);
$manager->setTitle('Awesome!');
$manager->setDepartment('IT');
$person = new CompanyPerson();
$person->setName('spouse');
$manager->setSpouse($person);
$this->_em->persist($manager);
$this->_em->persist($person);
$this->_em->flush();
$this->_em->clear();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyManager');
$pmanager = $repos->findOneBy(array('spouse' => $person->getId()));
$this->assertEquals($manager->getId(), $pmanager->getId());
$repos = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyPerson');
$pmanager = $repos->findOneBy(array('spouse' => $person->getId()));
$this->assertEquals($manager->getId(), $pmanager->getId());
}
/**
* @group DDC-834
*/
public function testGetReferenceEntityWithSubclasses()
{
$manager = new CompanyManager();
$manager->setName('gblanco');
$manager->setSalary(1234);
$manager->setTitle('Awesome!');
$manager->setDepartment('IT');
$this->_em->persist($manager);
$this->_em->flush();
$this->_em->clear();
$ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyPerson', $manager->getId());
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "Cannot Request a proxy from a class that has subclasses.");
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $ref);
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $ref, "Direct fetch of the reference has to load the child class Emplyoee directly.");
$this->_em->clear();
$ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId());
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "A proxy can be generated only if no subclasses exists for the requested reference.");
}
/**
* @group DDC-992
*/
public function testGetSubClassManyToManyCollection()
{
$manager = new CompanyManager();
$manager->setName('gblanco');
$manager->setSalary(1234);
$manager->setTitle('Awesome!');
$manager->setDepartment('IT');
$person = new CompanyPerson();
$person->setName('friend');
$manager->addFriend($person);
$this->_em->persist($manager);
$this->_em->persist($person);
$this->_em->flush();
$this->_em->clear();
$manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId());
$this->assertEquals(1, count($manager->getFriends()));
}
/**
* @group DDC-1777
*/
public function testExistsSubclass()
{
$manager = new CompanyManager();
$manager->setName('gblanco');
$manager->setSalary(1234);
$manager->setTitle('Awesome!');
$manager->setDepartment('IT');
$this->assertFalse($this->_em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager));
$this->_em->persist($manager);
$this->_em->flush();
$this->assertTrue($this->_em->getUnitOfWork()->getEntityPersister(get_class($manager))->exists($manager));
}
}

View File

@@ -0,0 +1,176 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional tests for the Class Table Inheritance mapping strategy.
*
* @author robo
*/
class ClassTableInheritanceTest2 extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIParent'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIChild'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIRelated'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIRelated2')
));
} catch (\Exception $ignored) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
public function testOneToOneAssocToBaseTypeBidirectional()
{
$child = new CTIChild;
$child->setData('hello');
$related = new CTIRelated;
$related->setCTIParent($child);
$this->_em->persist($related);
$this->_em->persist($child);
$this->_em->flush();
$this->_em->clear();
$relatedId = $related->getId();
$related2 = $this->_em->find('Doctrine\Tests\ORM\Functional\CTIRelated', $relatedId);
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIRelated', $related2);
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIChild', $related2->getCTIParent());
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $related2->getCTIParent());
$this->assertEquals('hello', $related2->getCTIParent()->getData());
$this->assertSame($related2, $related2->getCTIParent()->getRelated());
}
public function testManyToManyToCTIHierarchy()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$mmrel = new CTIRelated2;
$child = new CTIChild;
$child->setData('child');
$mmrel->addCTIChild($child);
$this->_em->persist($mmrel);
$this->_em->persist($child);
$this->_em->flush();
$this->_em->clear();
$mmrel2 = $this->_em->find(get_class($mmrel), $mmrel->getId());
$this->assertFalse($mmrel2->getCTIChildren()->isInitialized());
$this->assertEquals(1, count($mmrel2->getCTIChildren()));
$this->assertTrue($mmrel2->getCTIChildren()->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIChild', $mmrel2->getCTIChildren()->get(0));
}
}
/**
* @Entity @Table(name="cti_parents")
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="type", type="string")
* @DiscriminatorMap({"parent" = "CTIParent", "child" = "CTIChild"})
*/
class CTIParent {
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/** @OneToOne(targetEntity="CTIRelated", mappedBy="ctiParent") */
private $related;
public function getId() {
return $this->id;
}
public function getRelated() {
return $this->related;
}
public function setRelated($related) {
$this->related = $related;
$related->setCTIParent($this);
}
}
/**
* @Entity @Table(name="cti_children")
*/
class CTIChild extends CTIParent {
/**
* @Column(type="string")
*/
private $data;
public function getData() {
return $this->data;
}
public function setData($data) {
$this->data = $data;
}
}
/** @Entity */
class CTIRelated {
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @OneToOne(targetEntity="CTIParent")
* @JoinColumn(name="ctiparent_id", referencedColumnName="id")
*/
private $ctiParent;
public function getId() {
return $this->id;
}
public function getCTIParent() {
return $this->ctiParent;
}
public function setCTIParent($ctiParent) {
$this->ctiParent = $ctiParent;
}
}
/** @Entity */
class CTIRelated2
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @ManyToMany(targetEntity="CTIChild") */
private $ctiChildren;
public function __construct() {
$this->ctiChildren = new \Doctrine\Common\Collections\ArrayCollection;
}
public function getId() {
return $this->id;
}
public function addCTIChild(CTIChild $child) {
$this->ctiChildren->add($child);
}
public function getCTIChildren() {
return $this->ctiChildren;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Event\OnClearEventArgs;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* ClearEventTest
*
* @author Michael Ridgway <mcridgway@gmail.com>
*/
class ClearEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
}
public function testEventIsCalledOnClear()
{
$listener = new OnClearListener;
$this->_em->getEventManager()->addEventListener(Events::onClear, $listener);
$this->_em->clear();
$this->assertTrue($listener->called);
}
}
class OnClearListener
{
public $called = false;
public function onClear(OnClearEventArgs $args)
{
$this->called = true;
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\Navigation\NavCountry;
use Doctrine\Tests\Models\Navigation\NavPointOfInterest;
use Doctrine\Tests\Models\Navigation\NavTour;
use Doctrine\Tests\Models\Navigation\NavPhotos;
require_once __DIR__ . '/../../TestInit.php';
class CompositePrimaryKeyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('navigation');
parent::setUp();
}
public function putGermanysBrandenburderTor()
{
$country = new NavCountry("Germany");
$this->_em->persist($country);
$poi = new NavPointOfInterest(100, 200, "Brandenburger Tor", $country);
$this->_em->persist($poi);
$this->_em->flush();
$this->_em->clear();
}
public function putTripAroundEurope()
{
$poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200));
$tour = new NavTour("Trip around Europe");
$tour->addPointOfInterest($poi);
$this->_em->persist($tour);
$this->_em->flush();
$this->_em->clear();
return $tour;
}
public function testPersistCompositePkEntity()
{
$this->putGermanysBrandenburderTor();
$poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200));
$this->assertInstanceOf('Doctrine\Tests\Models\Navigation\NavPointOfInterest', $poi);
$this->assertEquals(100, $poi->getLat());
$this->assertEquals(200, $poi->getLong());
$this->assertEquals('Brandenburger Tor', $poi->getName());
}
/**
* @group DDC-1651
*/
public function testSetParameterCompositeKeyObject()
{
$this->putGermanysBrandenburderTor();
$poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200));
$photo = new NavPhotos($poi, "asdf");
$this->_em->persist($photo);
$this->_em->flush();
$this->_em->clear();
$dql = 'SELECT t FROM Doctrine\Tests\Models\Navigation\NavPhotos t WHERE t.poi = ?1';
$this->setExpectedException('Doctrine\ORM\Query\QueryException', 'A single-valued association path expression to an entity with a composite primary key is not supported.');
$sql = $this->_em->createQuery($dql)->getSQL();
}
public function testManyToManyCompositeRelation()
{
$this->putGermanysBrandenburderTor();
$tour = $this->putTripAroundEurope();
$tour = $this->_em->find('Doctrine\Tests\Models\Navigation\NavTour', $tour->getId());
$this->assertEquals(1, count($tour->getPointOfInterests()));
}
public function testCompositeDqlEagerFetching()
{
$this->putGermanysBrandenburderTor();
$this->putTripAroundEurope();
$dql = 'SELECT t, p, c FROM Doctrine\Tests\Models\Navigation\NavTour t ' .
'INNER JOIN t.pois p INNER JOIN p.country c';
$tours = $this->_em->createQuery($dql)->getResult();
$this->assertEquals(1, count($tours));
$pois = $tours[0]->getPointOfInterests();
$this->assertEquals(1, count($pois));
$this->assertEquals('Brandenburger Tor', $pois[0]->getName());
}
public function testCompositeCollectionMemberExpression()
{
$this->markTestSkipped('How to test this?');
$this->putGermanysBrandenburderTor();
$this->putTripAroundEurope();
$dql = 'SELECT t FROM Doctrine\Tests\Models\Navigation\NavTour t, Doctrine\Tests\Models\Navigation\NavPointOfInterest p ' .
'WHERE p MEMBER OF t.pois';
$tours = $this->_em->createQuery($dql)
->getResult();
$this->assertEquals(1, count($tours));
}
public function testSpecifiyUnknownIdentifierPrimaryKeyFails()
{
$this->setExpectedException('Doctrine\ORM\ORMException', 'The identifier long is missing for a query of Doctrine\Tests\Models\Navigation\NavPointOfInterest');
$poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('key1' => 100));
}
}

View File

@@ -0,0 +1,157 @@
<?php
/*
* 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\Tests\ORM\Functional;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Test case for custom AST walking and modification.
*
* @author Roman Borschel <roman@code-factory.org>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://www.doctrine-project.org
* @since 2.0
*/
class CustomTreeWalkersTest extends \Doctrine\Tests\OrmTestCase
{
private $_em;
protected function setUp()
{
$this->_em = $this->_getTestEntityManager();
}
public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed)
{
try {
$query = $this->_em->createQuery($dqlToBeTested);
$query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\Tests\ORM\Functional\CustomTreeWalker'))
->useQueryCache(false);
$this->assertEquals($sqlToBeConfirmed, $query->getSql());
$query->free();
} catch (\Exception $e) {
$this->fail($e->getMessage() . ' at "' . $e->getFile() . '" on line ' . $e->getLine());
}
}
public function testSupportsQueriesWithoutWhere()
{
$this->assertSqlGeneration(
'select u from Doctrine\Tests\Models\CMS\CmsUser u',
"SELECT c0_.id AS id0, c0_.status AS status1, c0_.username AS username2, c0_.name AS name3, c0_.email_id AS email_id4 FROM cms_users c0_ WHERE c0_.id = 1"
);
}
public function testSupportsQueriesWithMultipleConditionalExpressions()
{
$this->assertSqlGeneration(
'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name or u.name = :otherName',
"SELECT c0_.id AS id0, c0_.status AS status1, c0_.username AS username2, c0_.name AS name3, c0_.email_id AS email_id4 FROM cms_users c0_ WHERE (c0_.name = ? OR c0_.name = ?) AND c0_.id = 1"
);
}
public function testSupportsQueriesWithSimpleConditionalExpression()
{
$this->assertSqlGeneration(
'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name',
"SELECT c0_.id AS id0, c0_.status AS status1, c0_.username AS username2, c0_.name AS name3, c0_.email_id AS email_id4 FROM cms_users c0_ WHERE c0_.name = ? AND c0_.id = 1"
);
}
}
class CustomTreeWalker extends Query\TreeWalkerAdapter
{
public function walkSelectStatement(Query\AST\SelectStatement $selectStatement)
{
// Get the DQL aliases of all the classes we want to modify
$dqlAliases = array();
foreach ($this->_getQueryComponents() as $dqlAlias => $comp) {
// Hard-coded check just for demonstration: We want to modify the query if
// it involves the CmsUser class.
if ($comp['metadata']->name == 'Doctrine\Tests\Models\CMS\CmsUser') {
$dqlAliases[] = $dqlAlias;
}
}
// Create our conditions for all involved classes
$factors = array();
foreach ($dqlAliases as $alias) {
$pathExpr = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, $alias, 'id');
$pathExpr->type = Query\AST\PathExpression::TYPE_STATE_FIELD;
$comparisonExpr = new Query\AST\ComparisonExpression($pathExpr, '=', 1);
$condPrimary = new Query\AST\ConditionalPrimary;
$condPrimary->simpleConditionalExpression = $comparisonExpr;
$factor = new Query\AST\ConditionalFactor($condPrimary);
$factors[] = $factor;
}
if (($whereClause = $selectStatement->whereClause) !== null) {
// There is already a WHERE clause, so append the conditions
$condExpr = $whereClause->conditionalExpression;
// Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression
if ( ! ($condExpr instanceof Query\AST\ConditionalExpression)) {
$condExpr = new Query\AST\ConditionalExpression(array($condExpr));
$whereClause->conditionalExpression = $condExpr;
}
$existingTerms = $whereClause->conditionalExpression->conditionalTerms;
if (count($existingTerms) > 1) {
// More than one term, so we need to wrap all these terms in a single root term
// i.e: "WHERE u.name = :foo or u.other = :bar" => "WHERE (u.name = :foo or u.other = :bar) AND <our condition>"
$primary = new Query\AST\ConditionalPrimary;
$primary->conditionalExpression = new Query\AST\ConditionalExpression($existingTerms);
$existingFactor = new Query\AST\ConditionalFactor($primary);
$term = new Query\AST\ConditionalTerm(array_merge(array($existingFactor), $factors));
$selectStatement->whereClause->conditionalExpression->conditionalTerms = array($term);
} else {
// Just one term so we can simply append our factors to that term
$singleTerm = $selectStatement->whereClause->conditionalExpression->conditionalTerms[0];
// Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression
if ( ! ($singleTerm instanceof Query\AST\ConditionalTerm)) {
$singleTerm = new Query\AST\ConditionalTerm(array($singleTerm));
$selectStatement->whereClause->conditionalExpression->conditionalTerms[0] = $singleTerm;
}
$singleTerm->conditionalFactors = array_merge($singleTerm->conditionalFactors, $factors);
$selectStatement->whereClause->conditionalExpression->conditionalTerms = array($singleTerm);
}
} else {
// Create a new WHERE clause with our factors
$term = new Query\AST\ConditionalTerm($factors);
$condExpr = new Query\AST\ConditionalExpression(array($term));
$whereClause = new Query\AST\WhereClause($condExpr);
$selectStatement->whereClause = $whereClause;
}
}
}

View File

@@ -0,0 +1,166 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
use Doctrine\ORM\Mapping\ClassMetadataInfo,
Doctrine\Common\Util\Inflector;
class DatabaseDriverTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var \Doctrine\DBAL\Schema\AbstractSchemaManager
*/
protected $_sm = null;
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$this->_sm = $this->_em->getConnection()->getSchemaManager();
}
public function testLoadMetadataFromDatabase()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Platform does not support foreign keys.');
}
$table = new \Doctrine\DBAL\Schema\Table("dbdriver_foo");
$table->addColumn('id', 'integer');
$table->setPrimaryKey(array('id'));
$table->addColumn('bar', 'string', array('notnull' => false, 'length' => 200));
$this->_sm->dropAndCreateTable($table);
$metadatas = $this->extractClassMetadata(array("DbdriverFoo"));
$this->assertArrayHasKey('DbdriverFoo', $metadatas);
$metadata = $metadatas['DbdriverFoo'];
$this->assertArrayHasKey('id', $metadata->fieldMappings);
$this->assertEquals('id', $metadata->fieldMappings['id']['fieldName']);
$this->assertEquals('id', strtolower($metadata->fieldMappings['id']['columnName']));
$this->assertEquals('integer', (string)$metadata->fieldMappings['id']['type']);
$this->assertArrayHasKey('bar', $metadata->fieldMappings);
$this->assertEquals('bar', $metadata->fieldMappings['bar']['fieldName']);
$this->assertEquals('bar', strtolower($metadata->fieldMappings['bar']['columnName']));
$this->assertEquals('string', (string)$metadata->fieldMappings['bar']['type']);
$this->assertEquals(200, $metadata->fieldMappings['bar']['length']);
$this->assertTrue($metadata->fieldMappings['bar']['nullable']);
}
public function testLoadMetadataWithForeignKeyFromDatabase()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Platform does not support foreign keys.');
}
$tableB = new \Doctrine\DBAL\Schema\Table("dbdriver_bar");
$tableB->addColumn('id', 'integer');
$tableB->setPrimaryKey(array('id'));
$this->_sm->dropAndCreateTable($tableB);
$tableA = new \Doctrine\DBAL\Schema\Table("dbdriver_baz");
$tableA->addColumn('id', 'integer');
$tableA->setPrimaryKey(array('id'));
$tableA->addColumn('bar_id', 'integer');
$tableA->addForeignKeyConstraint('dbdriver_bar', array('bar_id'), array('id'));
$this->_sm->dropAndCreateTable($tableA);
$metadatas = $this->extractClassMetadata(array("DbdriverBar", "DbdriverBaz"));
$this->assertArrayHasKey('DbdriverBaz', $metadatas);
$bazMetadata = $metadatas['DbdriverBaz'];
$this->assertArrayNotHasKey('barId', $bazMetadata->fieldMappings, "The foreign Key field should not be inflected as 'barId' field, its an association.");
$this->assertArrayHasKey('id', $bazMetadata->fieldMappings);
$bazMetadata->associationMappings = \array_change_key_case($bazMetadata->associationMappings, \CASE_LOWER);
$this->assertArrayHasKey('bar', $bazMetadata->associationMappings);
$this->assertEquals(ClassMetadataInfo::MANY_TO_ONE, $bazMetadata->associationMappings['bar']['type']);
}
public function testDetectManyToManyTables()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped('Platform does not support foreign keys.');
}
$metadatas = $this->extractClassMetadata(array("CmsUsers", "CmsGroups"));
$this->assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.');
$this->assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.');
$this->assertEquals(2, count($metadatas['CmsUsers']->associationMappings));
$this->assertArrayHasKey('group', $metadatas['CmsUsers']->associationMappings);
$this->assertEquals(1, count($metadatas['CmsGroups']->associationMappings));
$this->assertArrayHasKey('user', $metadatas['CmsGroups']->associationMappings);
}
public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails()
{
$tableB = new \Doctrine\DBAL\Schema\Table("dbdriver_bar");
$tableB->addColumn('id', 'integer');
$tableB->setPrimaryKey(array('id'));
$tableA = new \Doctrine\DBAL\Schema\Table("dbdriver_baz");
$tableA->addColumn('id', 'integer');
$tableA->setPrimaryKey(array('id'));
$tableMany = new \Doctrine\DBAL\Schema\Table("dbdriver_bar_baz");
$tableMany->addColumn('bar_id', 'integer');
$tableMany->addColumn('baz_id', 'integer');
$tableMany->addForeignKeyConstraint('dbdriver_bar', array('bar_id'), array('id'));
$metadatas = $this->convertToClassMetadata(array($tableA, $tableB), array($tableMany));
$this->assertEquals(0, count($metadatas['DbdriverBaz']->associationMappings), "no association mappings should be detected.");
}
protected function convertToClassMetadata(array $entityTables, array $manyTables = array())
{
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->_sm);
$driver->setTables($entityTables, $manyTables);
$metadatas = array();
foreach ($driver->getAllClassNames() AS $className) {
$class = new ClassMetadataInfo($className);
$driver->loadMetadataForClass($className, $class);
$metadatas[$className] = $class;
}
return $metadatas;
}
/**
* @param string $className
* @return ClassMetadata
*/
protected function extractClassMetadata(array $classNames)
{
$classNames = array_map('strtolower', $classNames);
$metadatas = array();
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($this->_sm);
foreach ($driver->getAllClassNames() as $className) {
if (!in_array(strtolower($className), $classNames)) {
continue;
}
$class = new ClassMetadataInfo($className);
$driver->loadMetadataForClass($className, $class);
$metadatas[$className] = $class;
}
if (count($metadatas) != count($classNames)) {
$this->fail("Have not found all classes matching the names '" . implode(", ", $classNames) . "' only tables " . implode(", ", array_keys($metadatas)));
}
return $metadatas;
}
}

View File

@@ -0,0 +1,150 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests basic operations on entities with default values.
*
* @author robo
*/
class DefaultValuesTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\DefaultValueUser'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\DefaultValueAddress')
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
public function testSimpleDetachMerge() {
$user = new DefaultValueUser;
$user->name = 'romanb';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$userId = $user->id; // e.g. from $_REQUEST
$user2 = $this->_em->getReference(get_class($user), $userId);
$this->_em->flush();
$this->assertFalse($user2->__isInitialized__);
$a = new DefaultValueAddress;
$a->country = 'de';
$a->zip = '12345';
$a->city = 'Berlin';
$a->street = 'Sesamestreet';
$a->user = $user2;
$this->_em->persist($a);
$this->_em->flush();
$this->assertFalse($user2->__isInitialized__);
$this->_em->clear();
$a2 = $this->_em->find(get_class($a), $a->id);
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\DefaultValueUser', $a2->getUser());
$this->assertEquals($userId, $a2->getUser()->getId());
$this->assertEquals('Poweruser', $a2->getUser()->type);
}
/**
* @group DDC-1386
*/
public function testGetPartialReferenceWithDefaultValueNotEvalutedInFlush()
{
$user = new DefaultValueUser;
$user->name = 'romanb';
$user->type = 'Normaluser';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->getPartialReference('Doctrine\Tests\ORM\Functional\DefaultValueUser', $user->id);
$this->assertTrue($this->_em->getUnitOfWork()->isReadOnly($user));
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find('Doctrine\Tests\ORM\Functional\DefaultValueUser', $user->id);
$this->assertEquals('Normaluser', $user->type);
}
}
/**
* @Entity @Table(name="defaultvalueuser")
*/
class DefaultValueUser
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string")
*/
public $name = '';
/**
* @Column(type="string")
*/
public $type = 'Poweruser';
/**
* @OneToOne(targetEntity="DefaultValueAddress", mappedBy="user", cascade={"persist"})
*/
public $address;
public function getId() {return $this->id;}
}
/**
* CmsAddress
*
* @Entity @Table(name="defaultvalueaddresses")
*/
class DefaultValueAddress
{
/**
* @Column(type="integer")
* @Id @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=50)
*/
public $country;
/**
* @Column(type="string", length=50)
*/
public $zip;
/**
* @Column(type="string", length=50)
*/
public $city;
/**
* Testfield for Schema Updating Tests.
*/
public $street;
/**
* @OneToOne(targetEntity="DefaultValueUser")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
public $user;
public function getUser() {return $this->user;}
}

View File

@@ -0,0 +1,218 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\Tests\Models\CMS\CmsAddress;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../TestInit.php';
/**
* Description of DetachedEntityTest
*
* @author robo
*/
class DetachedEntityTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
}
public function testSimpleDetachMerge() {
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
// $user is now detached
$this->assertFalse($this->_em->contains($user));
$user->name = 'Roman B.';
//$this->assertEquals(UnitOfWork::STATE_DETACHED, $this->_em->getUnitOfWork()->getEntityState($user));
$user2 = $this->_em->merge($user);
$this->assertFalse($user === $user2);
$this->assertTrue($this->_em->contains($user2));
$this->assertEquals('Roman B.', $user2->name);
}
public function testSerializeUnserializeModifyMerge()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$ph1 = new CmsPhonenumber;
$ph1->phonenumber = "1234";
$user->addPhonenumber($ph1);
$this->_em->persist($user);
$this->_em->flush();
$this->assertTrue($this->_em->contains($user));
$this->assertTrue($user->phonenumbers->isInitialized());
$serialized = serialize($user);
$this->_em->clear();
$this->assertFalse($this->_em->contains($user));
unset($user);
$user = unserialize($serialized);
$this->assertEquals(1, count($user->getPhonenumbers()), "Pre-Condition: 1 Phonenumber");
$ph2 = new CmsPhonenumber;
$ph2->phonenumber = "56789";
$user->addPhonenumber($ph2);
$oldPhonenumbers = $user->getPhonenumbers();
$this->assertEquals(2, count($oldPhonenumbers), "Pre-Condition: 2 Phonenumbers");
$this->assertFalse($this->_em->contains($user));
$this->_em->persist($ph2);
// Merge back in
$user = $this->_em->merge($user); // merge cascaded to phonenumbers
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $user->phonenumbers[0]->user);
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $user->phonenumbers[1]->user);
$im = $this->_em->getUnitOfWork()->getIdentityMap();
$this->_em->flush();
$this->assertTrue($this->_em->contains($user), "Failed to assert that merged user is contained inside EntityManager persistence context.");
$phonenumbers = $user->getPhonenumbers();
$this->assertNotSame($oldPhonenumbers, $phonenumbers, "Merge should replace the Detached Collection with a new PersistentCollection.");
$this->assertEquals(2, count($phonenumbers), "Failed to assert that two phonenumbers are contained in the merged users phonenumber collection.");
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $phonenumbers[1]);
$this->assertTrue($this->_em->contains($phonenumbers[1]), "Failed to assert that second phonenumber in collection is contained inside EntityManager persistence context.");
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $phonenumbers[0]);
$this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($phonenumbers[0]));
$this->assertTrue($this->_em->contains($phonenumbers[0]), "Failed to assert that first phonenumber in collection is contained inside EntityManager persistence context.");
}
/**
* @group DDC-203
*/
public function testDetachedEntityThrowsExceptionOnFlush()
{
$ph = new CmsPhonenumber();
$ph->phonenumber = '12345';
$this->_em->persist($ph);
$this->_em->flush();
$this->_em->clear();
$this->_em->persist($ph);
try {
$this->_em->flush();
$this->fail();
} catch (\Exception $expected) {}
}
public function testUninitializedLazyAssociationsAreIgnoredOnMerge()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$address = new CmsAddress;
$address->city = 'Berlin';
$address->country = 'Germany';
$address->street = 'Sesamestreet';
$address->zip = 12345;
$address->setUser($user);
$this->_em->persist($address);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$address2 = $this->_em->find(get_class($address), $address->id);
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $address2->user);
$this->assertFalse($address2->user->__isInitialized__);
$detachedAddress2 = unserialize(serialize($address2));
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $detachedAddress2->user);
$this->assertFalse($detachedAddress2->user->__isInitialized__);
$managedAddress2 = $this->_em->merge($detachedAddress2);
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $managedAddress2->user);
$this->assertFalse($managedAddress2->user === $detachedAddress2->user);
$this->assertFalse($managedAddress2->user->__isInitialized__);
}
/**
* @group DDC-822
*/
public function testUseDetachedEntityAsQueryParameter()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->detach($user);
$dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1";
$query = $this->_em->createQuery($dql);
$query->setParameter(1, $user);
$newUser = $query->getSingleResult();
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $newUser);
$this->assertEquals('gblanco', $newUser->username);
}
/**
* @group DDC-920
*/
public function testDetachManagedUnpersistedEntity()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->detach($user);
$this->_em->flush();
$this->assertFalse($this->_em->contains($user));
$this->assertFalse($this->_em->getUnitOfWork()->isInIdentityMap($user));
}
/**
* @group DDC-1340
*/
public function testMergeArticleWrongVersion()
{
$article = new CmsArticle();
$article->topic = "test";
$article->text = "test";
$this->_em->persist($article);
$this->_em->flush();
$this->_em->detach($article);
$sql = "UPDATE cms_articles SET version = version+1 WHERE id = " . $article->id;
$this->_em->getConnection()->executeUpdate($sql);
$this->setExpectedException('Doctrine\ORM\OptimisticLockException', 'The optimistic lock failed, version 1 was expected, but is actually 2');
$this->_em->merge($article);
}
}

View File

@@ -0,0 +1,505 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsAddress;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
require_once __DIR__ . '/../../TestInit.php';
/**
* @author robo
*/
class EntityRepositoryTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
}
public function tearDown()
{
if ($this->_em) {
$this->_em->getConfiguration()->setEntityNamespaces(array());
}
parent::tearDown();
}
public function loadFixture()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'freak';
$this->_em->persist($user);
$user2 = new CmsUser;
$user2->name = 'Guilherme';
$user2->username = 'gblanco';
$user2->status = 'dev';
$this->_em->persist($user2);
$user3 = new CmsUser;
$user3->name = 'Benjamin';
$user3->username = 'beberlei';
$user3->status = null;
$this->_em->persist($user3);
$this->_em->flush();
$user1Id = $user->getId();
unset($user);
unset($user2);
unset($user3);
$this->_em->clear();
return $user1Id;
}
public function loadAssociatedFixture()
{
$address = new CmsAddress();
$address->city = "Berlin";
$address->country = "Germany";
$address->street = "Foostreet";
$address->zip = "12345";
$user = new CmsUser();
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'freak';
$user->setAddress($address);
$this->_em->persist($user);
$this->_em->persist($address);
$this->_em->flush();
$this->_em->clear();
return array($user->id, $address->id);
}
public function buildUser($name, $username, $status, $address)
{
$user = new CmsUser();
$user->name = $name;
$user->username = $username;
$user->status = $status;
$user->setAddress($address);
$this->_em->persist($user);
$this->_em->flush();
return $user;
}
public function buildAddress($country, $city, $street, $zip)
{
$address = new CmsAddress();
$address->country = $country;
$address->city = $city;
$address->street = $street;
$address->zip = $zip;
$this->_em->persist($address);
$this->_em->flush();
return $address;
}
public function testBasicFind()
{
$user1Id = $this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$user = $repos->find($user1Id);
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$user);
$this->assertEquals('Roman', $user->name);
$this->assertEquals('freak', $user->status);
}
public function testFindByField()
{
$user1Id = $this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findBy(array('status' => 'dev'));
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$users[0]);
$this->assertEquals('Guilherme', $users[0]->name);
$this->assertEquals('dev', $users[0]->status);
}
public function testFindByAssociationWithIntegerAsParameter()
{
$address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456');
$user1 = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1);
$address2 = $this->buildAddress('Brazil', 'São Paulo', 'Bar st.', '654321');
$user2 = $this->buildUser('Guilherme', 'guilhermeblanco', 'freak', $address2);
$address3 = $this->buildAddress('USA', 'Nashville', 'Woo st.', '321654');
$user3 = $this->buildUser('Jonathan', 'jwage', 'dev', $address3);
unset($address1);
unset($address2);
unset($address3);
$this->_em->clear();
$repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$addresses = $repository->findBy(array('user' => array($user1->getId(), $user2->getId())));
$this->assertEquals(2, count($addresses));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress',$addresses[0]);
}
public function testFindByAssociationWithObjectAsParameter()
{
$address1 = $this->buildAddress('Germany', 'Berlim', 'Foo st.', '123456');
$user1 = $this->buildUser('Benjamin', 'beberlei', 'dev', $address1);
$address2 = $this->buildAddress('Brazil', 'São Paulo', 'Bar st.', '654321');
$user2 = $this->buildUser('Guilherme', 'guilhermeblanco', 'freak', $address2);
$address3 = $this->buildAddress('USA', 'Nashville', 'Woo st.', '321654');
$user3 = $this->buildUser('Jonathan', 'jwage', 'dev', $address3);
unset($address1);
unset($address2);
unset($address3);
$this->_em->clear();
$repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$addresses = $repository->findBy(array('user' => array($user1, $user2)));
$this->assertEquals(2, count($addresses));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress',$addresses[0]);
}
public function testFindFieldByMagicCall()
{
$user1Id = $this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findByStatus('dev');
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$users[0]);
$this->assertEquals('Guilherme', $users[0]->name);
$this->assertEquals('dev', $users[0]->status);
}
public function testFindAll()
{
$user1Id = $this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findAll();
$this->assertEquals(3, count($users));
}
public function testFindByAlias()
{
$user1Id = $this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS');
$repos = $this->_em->getRepository('CMS:CmsUser');
$users = $repos->findAll();
$this->assertEquals(3, count($users));
}
/**
* @expectedException \Doctrine\ORM\ORMException
*/
public function testExceptionIsThrownWhenCallingFindByWithoutParameter() {
$this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')
->findByStatus();
}
/**
* @expectedException \Doctrine\ORM\ORMException
*/
public function testExceptionIsThrownWhenUsingInvalidFieldName() {
$this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')
->findByThisFieldDoesNotExist('testvalue');
}
/**
* @group locking
* @group DDC-178
*/
public function testPessimisticReadLockWithoutTransaction_ThrowsException()
{
$this->setExpectedException('Doctrine\ORM\TransactionRequiredException');
$this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')
->find(1, \Doctrine\DBAL\LockMode::PESSIMISTIC_READ);
}
/**
* @group locking
* @group DDC-178
*/
public function testPessimisticWriteLockWithoutTransaction_ThrowsException()
{
$this->setExpectedException('Doctrine\ORM\TransactionRequiredException');
$this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')
->find(1, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE);
}
/**
* @group locking
* @group DDC-178
*/
public function testOptimisticLockUnversionedEntity_ThrowsException()
{
$this->setExpectedException('Doctrine\ORM\OptimisticLockException');
$this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')
->find(1, \Doctrine\DBAL\LockMode::OPTIMISTIC);
}
/**
* @group locking
* @group DDC-178
*/
public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsException()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'freak';
$this->_em->persist($user);
$this->_em->flush();
$userId = $user->id;
$this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId);
$this->setExpectedException('Doctrine\ORM\OptimisticLockException');
$this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId, \Doctrine\DBAL\LockMode::OPTIMISTIC);
}
/**
* @group DDC-819
*/
public function testFindMagicCallByNullValue()
{
$this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findByStatus(null);
$this->assertEquals(1, count($users));
}
/**
* @group DDC-819
*/
public function testInvalidMagicCall()
{
$this->setExpectedException('BadMethodCallException');
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$repos->foo();
}
/**
* @group DDC-817
*/
public function testFindByAssociationKey_ExceptionOnInverseSide()
{
list($userId, $addressId) = $this->loadAssociatedFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$this->setExpectedException('Doctrine\ORM\ORMException', "You cannot search for the association field 'Doctrine\Tests\Models\CMS\CmsUser#address', because it is the inverse side of an association. Find methods only work on owning side associations.");
$user = $repos->findBy(array('address' => $addressId));
}
/**
* @group DDC-817
*/
public function testFindOneByAssociationKey()
{
list($userId, $addressId) = $this->loadAssociatedFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$address = $repos->findOneBy(array('user' => $userId));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $address);
$this->assertEquals($addressId, $address->id);
}
/**
* @group DDC-817
*/
public function testFindByAssociationKey()
{
list($userId, $addressId) = $this->loadAssociatedFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$addresses = $repos->findBy(array('user' => $userId));
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsAddress', $addresses);
$this->assertEquals(1, count($addresses));
$this->assertEquals($addressId, $addresses[0]->id);
}
/**
* @group DDC-817
*/
public function testFindAssociationByMagicCall()
{
list($userId, $addressId) = $this->loadAssociatedFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$addresses = $repos->findByUser($userId);
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsAddress', $addresses);
$this->assertEquals(1, count($addresses));
$this->assertEquals($addressId, $addresses[0]->id);
}
/**
* @group DDC-817
*/
public function testFindOneAssociationByMagicCall()
{
list($userId, $addressId) = $this->loadAssociatedFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress');
$address = $repos->findOneByUser($userId);
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $address);
$this->assertEquals($addressId, $address->id);
}
public function testValidNamedQueryRetrieval()
{
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$query = $repos->createNamedQuery('all');
$this->assertInstanceOf('Doctrine\ORM\Query', $query);
$this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL());
}
public function testInvalidNamedQueryRetrieval()
{
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
$repos->createNamedQuery('invalidNamedQuery');
}
/**
* @group DDC-1087
*/
public function testIsNullCriteriaDoesNotGenerateAParameter()
{
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findBy(array('status' => null, 'username' => 'romanb'));
$params = $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'];
$this->assertEquals(1, count($params), "Should only execute with one parameter.");
$this->assertEquals(array('romanb'), $params);
}
public function testIsNullCriteria()
{
$this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users = $repos->findBy(array('status' => null));
$this->assertEquals(1, count($users));
}
/**
* @group DDC-1094
*/
public function testFindByLimitOffset()
{
$this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$users1 = $repos->findBy(array(), null, 1, 0);
$users2 = $repos->findBy(array(), null, 1, 1);
$this->assertEquals(3, count($repos->findBy(array())));
$this->assertEquals(1, count($users1));
$this->assertEquals(1, count($users2));
$this->assertNotSame($users1[0], $users2[0]);
}
/**
* @group DDC-1094
*/
public function testFindByOrderBy()
{
$this->loadFixture();
$repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$usersAsc = $repos->findBy(array(), array("username" => "ASC"));
$usersDesc = $repos->findBy(array(), array("username" => "DESC"));
$this->assertEquals(3, count($usersAsc), "Pre-condition: only three users in fixture");
$this->assertEquals(3, count($usersDesc), "Pre-condition: only three users in fixture");
$this->assertSame($usersAsc[0], $usersDesc[2]);
$this->assertSame($usersAsc[2], $usersDesc[0]);
}
/**
* @group DDC-753
*/
public function testDefaultRepositoryClassName()
{
$this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository");
$this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\Tests\Models\DDC753\DDC753DefaultRepository");
$this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\Tests\Models\DDC753\DDC753DefaultRepository");
$repos = $this->_em->getRepository('Doctrine\Tests\Models\DDC753\DDC753EntityWithDefaultCustomRepository');
$this->assertInstanceOf("Doctrine\Tests\Models\DDC753\DDC753DefaultRepository", $repos);
$this->assertTrue($repos->isDefaultRepository());
$repos = $this->_em->getRepository('Doctrine\Tests\Models\DDC753\DDC753EntityWithCustomRepository');
$this->assertInstanceOf("Doctrine\Tests\Models\DDC753\DDC753CustomRepository", $repos);
$this->assertTrue($repos->isCustomRepository());
$this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\Tests\Models\DDC753\DDC753DefaultRepository");
$this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\ORM\EntityRepository");
$this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository");
}
/**
* @group DDC-753
* @expectedException Doctrine\ORM\ORMException
* @expectedExceptionMessage Invalid repository class 'Doctrine\Tests\Models\DDC753\DDC753InvalidRepository'. it must be a Doctrine\ORM\EntityRepository.
*/
public function testSetDefaultRepositoryInvalidClassError()
{
$this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository");
$this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\Tests\Models\DDC753\DDC753InvalidRepository");
}
/**
* @group DDC-1500
*/
public function testInvalidOrientation()
{
$this->setExpectedException('Doctrine\ORM\ORMException', 'Invalid order by orientation specified for Doctrine\Tests\Models\CMS\CmsUser#username');
$repo = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser');
$repo->findBy(array('status' => 'test'), array('username' => 'INVALID'));
}
}

View File

@@ -0,0 +1,583 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
require_once __DIR__ . '/../../TestInit.php';
/**
* Description of ExtraLazyCollectionTest
*
* @author beberlei
*/
class ExtraLazyCollectionTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $userId;
private $groupId;
private $articleId;
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
$class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup');
$class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$this->loadFixture();
}
public function tearDown()
{
parent::tearDown();
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
$class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
$class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup');
$class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
}
/**
* @group DDC-546
*/
public function testCountNotInitializesCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->groups->isInitialized());
$this->assertEquals(3, count($user->groups));
$this->assertFalse($user->groups->isInitialized());
foreach ($user->groups AS $group) { }
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration.");
}
/**
* @group DDC-546
*/
public function testCountWhenNewEntityPresent()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$newGroup = new \Doctrine\Tests\Models\CMS\CmsGroup();
$newGroup->name = "Test4";
$user->addGroup($newGroup);
$this->_em->persist($newGroup);
$this->assertFalse($user->groups->isInitialized());
$this->assertEquals(4, count($user->groups));
$this->assertFalse($user->groups->isInitialized());
}
/**
* @group DDC-546
*/
public function testCountWhenInitialized()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
foreach ($user->groups AS $group) { }
$this->assertTrue($user->groups->isInitialized());
$this->assertEquals(3, count($user->groups));
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Should only execute one query to initialize colleciton, no extra query for count() more.");
}
/**
* @group DDC-546
*/
public function testCountInverseCollection()
{
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$this->assertFalse($group->users->isInitialized(), "Pre-Condition");
$this->assertEquals(4, count($group->users));
$this->assertFalse($group->users->isInitialized(), "Extra Lazy collection should not be initialized by counting the collection.");
}
/**
* @group DDC-546
*/
public function testCountOneToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->groups->isInitialized(), "Pre-Condition");
$this->assertEquals(2, count($user->articles));
}
/**
* @group DDC-546
*/
public function testFullSlice()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized.");
$someGroups = $user->groups->slice(null);
$this->assertEquals(3, count($someGroups));
}
/**
* @group DDC-546
*/
public function testSlice()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized.");
$queryCount = $this->getCurrentQueryCount();
$someGroups = $user->groups->slice(0, 2);
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsGroup', $someGroups);
$this->assertEquals(2, count($someGroups));
$this->assertFalse($user->groups->isInitialized(), "Slice should not initialize the collection if it wasn't before!");
$otherGroup = $user->groups->slice(2, 1);
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsGroup', $otherGroup);
$this->assertEquals(1, count($otherGroup));
$this->assertFalse($user->groups->isInitialized());
foreach ($user->groups AS $group) { }
$this->assertTrue($user->groups->isInitialized());
$this->assertEquals(3, count($user->groups));
$this->assertEquals($queryCount + 3, $this->getCurrentQueryCount());
}
/**
* @group DDC-546
*/
public function testSliceInitializedCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
foreach ($user->groups AS $group) { }
$someGroups = $user->groups->slice(0, 2);
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());
$this->assertEquals(2, count($someGroups));
$this->assertTrue($user->groups->contains($someGroups[0]));
$this->assertTrue($user->groups->contains($someGroups[1]));
}
/**
* @group DDC-546
*/
public function testSliceInverseCollection()
{
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$this->assertFalse($group->users->isInitialized(), "Pre-Condition");
$queryCount = $this->getCurrentQueryCount();
$someUsers = $group->users->slice(0, 2);
$otherUsers = $group->users->slice(2, 2);
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsUser', $someUsers);
$this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsUser', $otherUsers);
$this->assertEquals(2, count($someUsers));
$this->assertEquals(2, count($otherUsers));
// +2 queries executed by slice
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Slicing two parts should only execute two additional queries.");
}
/**
* @group DDC-546
*/
public function testSliceOneToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized.");
$queryCount = $this->getCurrentQueryCount();
$someArticle = $user->articles->slice(0, 1);
$otherArticle = $user->articles->slice(1, 1);
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount());
}
/**
* @group DDC-546
*/
public function testContainsOneToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized.");
// Test One to Many existance retrieved from DB
$article = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId);
$queryCount = $this->getCurrentQueryCount();
$this->assertTrue($user->articles->contains($article));
$this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized.");
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());
// Test One to Many existance with state new
$article = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article->topic = "Testnew";
$article->text = "blub";
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->articles->contains($article));
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed.");
// Test One to Many existance with state clear
$this->_em->persist($article);
$this->_em->flush();
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->articles->contains($article));
$this->assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed.");
$this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test One to Many existance with state managed
$article = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article->topic = "How to not fail anymore on tests";
$article->text = "That is simple! Just write more tests!";
$this->_em->persist($article);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->articles->contains($article));
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed.");
$this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized.");
}
/**
* @group DDC-546
*/
public function testContainsManyToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized.");
// Test Many to Many existance retrieved from DB
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$queryCount = $this->getCurrentQueryCount();
$this->assertTrue($user->groups->contains($group));
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many existance with state new
$group = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group->name = "A New group!";
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->groups->contains($group));
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many existance with state clear
$this->_em->persist($group);
$this->_em->flush();
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->groups->contains($group));
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Checking for contains of persisted entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many existance with state managed
$group = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group->name = "My managed group";
$this->_em->persist($group);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->groups->contains($group));
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of managed entity (but not persisted) should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
}
/**
* @group DDC-546
*/
public function testContainsManyToManyInverse()
{
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized.");
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$this->assertTrue($group->users->contains($user));
$this->assertEquals($queryCount+1, $this->getCurrentQueryCount(), "Checking for contains of managed entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
$newUser = new \Doctrine\Tests\Models\CMS\CmsUser();
$newUser->name = "A New group!";
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($group->users->contains($newUser));
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Checking for contains of new entity should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
}
/**
*
*/
public function testRemoveElementOneToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized.");
// Test One to Many removal with Entity retrieved from DB
$article = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId);
$queryCount = $this->getCurrentQueryCount();
$user->articles->removeElement($article);
$this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized.");
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount());
// Test One to Many removal with Entity state as new
$article = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article->topic = "Testnew";
$article->text = "blub";
$queryCount = $this->getCurrentQueryCount();
$user->articles->removeElement($article);
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed.");
// Test One to Many removal with Entity state as clean
$this->_em->persist($article);
$this->_em->flush();
$queryCount = $this->getCurrentQueryCount();
$user->articles->removeElement($article);
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed.");
$this->assertFalse($user->articles->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test One to Many removal with Entity state as managed
$article = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article->topic = "How to not fail anymore on tests";
$article->text = "That is simple! Just write more tests!";
$this->_em->persist($article);
$queryCount = $this->getCurrentQueryCount();
$user->articles->removeElement($article);
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed.");
}
/**
*
*/
public function testRemoveElementManyToMany()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized.");
// Test Many to Many removal with Entity retrieved from DB
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$queryCount = $this->getCurrentQueryCount();
$user->groups->removeElement($group);
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many removal with Entity state as new
$group = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group->name = "A New group!";
$queryCount = $this->getCurrentQueryCount();
$user->groups->removeElement($group);
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing new entity should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many removal with Entity state as clean
$this->_em->persist($group);
$this->_em->flush();
$queryCount = $this->getCurrentQueryCount();
$user->groups->removeElement($group);
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
// Test Many to Many removal with Entity state as managed
$group = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group->name = "A New group!";
$this->_em->persist($group);
$queryCount = $this->getCurrentQueryCount();
$user->groups->removeElement($group);
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a managed entity should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
}
/**
*
*/
public function testRemoveElementManyToManyInverse()
{
$group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId);
$this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized.");
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$group->users->removeElement($user);
$this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a managed entity should cause one query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
$newUser = new \Doctrine\Tests\Models\CMS\CmsUser();
$newUser->name = "A New group!";
$queryCount = $this->getCurrentQueryCount();
$group->users->removeElement($newUser);
$this->assertEquals($queryCount, $this->getCurrentQueryCount(), "Removing a new entity should cause no query to be executed.");
$this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized.");
}
/**
* @group DDC-1399
*/
public function testCountAfterAddThenFlush()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$newGroup = new \Doctrine\Tests\Models\CMS\CmsGroup();
$newGroup->name = "Test4";
$user->addGroup($newGroup);
$this->_em->persist($newGroup);
$this->assertFalse($user->groups->isInitialized());
$this->assertEquals(4, count($user->groups));
$this->assertFalse($user->groups->isInitialized());
$this->_em->flush();
$this->assertEquals(4, count($user->groups));
}
/**
* @group DDC-1462
*/
public function testSliceOnDirtyCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
/* @var $user CmsUser */
$newGroup = new \Doctrine\Tests\Models\CMS\CmsGroup();
$newGroup->name = "Test4";
$user->addGroup($newGroup);
$this->_em->persist($newGroup);
$qc = $this->getCurrentQueryCount();
$groups = $user->groups->slice(0, 10);
$this->assertEquals(4, count($groups));
$this->assertEquals($qc + 1, $this->getCurrentQueryCount());
}
private function loadFixture()
{
$user1 = new \Doctrine\Tests\Models\CMS\CmsUser();
$user1->username = "beberlei";
$user1->name = "Benjamin";
$user1->status = "active";
$user2 = new \Doctrine\Tests\Models\CMS\CmsUser();
$user2->username = "jwage";
$user2->name = "Jonathan";
$user2->status = "active";
$user3 = new \Doctrine\Tests\Models\CMS\CmsUser();
$user3->username = "romanb";
$user3->name = "Roman";
$user3->status = "active";
$user4 = new \Doctrine\Tests\Models\CMS\CmsUser();
$user4->username = "gblanco";
$user4->name = "Guilherme";
$user4->status = "active";
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->persist($user3);
$this->_em->persist($user4);
$group1 = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group1->name = "Test1";
$group2 = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group2->name = "Test2";
$group3 = new \Doctrine\Tests\Models\CMS\CmsGroup();
$group3->name = "Test3";
$user1->addGroup($group1);
$user1->addGroup($group2);
$user1->addGroup($group3);
$user2->addGroup($group1);
$user3->addGroup($group1);
$user4->addGroup($group1);
$this->_em->persist($group1);
$this->_em->persist($group2);
$this->_em->persist($group3);
$article1 = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article1->topic = "Test";
$article1->text = "Test";
$article1->setAuthor($user1);
$article2 = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article2->topic = "Test";
$article2->text = "Test";
$article2->setAuthor($user1);
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$this->articleId = $article1->id;
$this->userId = $user1->getId();
$this->groupId = $group1->id;
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* FlushEventTest
*
* @author robo
*/
class FlushEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
}
public function testPersistNewEntitiesOnPreFlush()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener);
$user = new CmsUser;
$user->username = 'romanb';
$user->name = 'Roman';
$user->status = 'Dev';
$this->_em->persist($user);
$this->assertEquals(0, $user->phonenumbers->count());
$this->_em->flush();
$this->assertEquals(1, $user->phonenumbers->count());
$this->assertTrue($this->_em->contains($user->phonenumbers->get(0)));
$this->assertTrue($user->phonenumbers->get(0)->getUser() === $user);
$this->assertFalse($user->phonenumbers->isDirty());
// Can be used together with SQL Logging to check that a subsequent flush has
// nothing to do. This proofs the correctness of the changes that happened in onFlush.
//echo "SECOND FLUSH";
//$this->_em->flush();
}
}
class OnFlushListener
{
public function onFlush(OnFlushEventArgs $args)
{
//echo "---preFlush".PHP_EOL;
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof CmsUser) {
// Adds a phonenumber to every newly persisted CmsUser ...
$phone = new CmsPhonenumber;
$phone->phonenumber = 12345;
// Update object model
$entity->addPhonenumber($phone);
// Invoke regular persist call
$em->persist($phone);
// Explicitly calculate the changeset since onFlush is raised
// after changeset calculation!
$uow->computeChangeSet($em->getClassMetadata(get_class($phone)), $phone);
// Take a snapshot because the UoW wont do this for us, because
// the UoW did not visit this collection.
// Alternatively we could provide an ->addVisitedCollection() method
// on the UoW.
$entity->getPhonenumbers()->takeSnapshot();
}
/*foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
list ($old, $new) = $change;
var_dump($old);
}*/
}
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\OrmFunctionalTestCase;
use Doctrine\Tests\Models\Cms\CmsUser;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\Common\Cache\ArrayCache;
/**
* @group DDC-1766
*/
class HydrationCacheTest extends OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$user = new CmsUser;
$user->name = "Benjamin";
$user->username = "beberlei";
$user->status = 'active';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
}
public function testHydrationCache()
{
$cache = new ArrayCache();
$dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u";
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))
->getResult();
$c = $this->getCurrentQueryCount();
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))
->getResult();
$this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!");
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))
->getArrayResult();
$this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration is part of cache key.");
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))
->getArrayResult();
$this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration now cached");
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache))
->getArrayResult();
$this->assertTrue($cache->contains('cachekey'), 'Explicit cache key');
$users = $this->_em->createQuery($dql)
->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache))
->getArrayResult();
$this->assertEquals($c + 2, $this->getCurrentQueryCount(), "Hydration now cached");
}
public function testHydrationParametersSerialization()
{
$cache = new ArrayCache();
$user = new CmsUser();
$user->id = 1;
$dql = "SELECT u FROM Doctrine\Tests\Models\Cms\CmsUser u WHERE u.id = ?1";
$query = $this->_em->createQuery($dql)
->setParameter(1, $user)
->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache));
$query->getResult();
$c = $this->getCurrentQueryCount();
$query->getResult();
$this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!");
}
}

View File

@@ -0,0 +1,288 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\Tests\Models\CMS\CmsAddress,
Doctrine\Tests\Models\CMS\CmsPhonenumber,
Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* IdentityMapTest
*
* Tests correct behavior and usage of the identity map. Local values and associations
* that are already fetched always prevail, unless explicitly refreshed.
*
* @author Roman Borschel <roman@code-factory.org>
*/
class IdentityMapTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
}
public function testBasicIdentityManagement()
{
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$address = new CmsAddress;
$address->country = 'de';
$address->zip = 1234;
$address->city = 'Berlin';
$user->setAddress($address);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$user2 = $this->_em->find(get_class($user), $user->getId());
$this->assertTrue($user2 !== $user);
$user3 = $this->_em->find(get_class($user), $user->getId());
$this->assertTrue($user2 === $user3);
$address2 = $this->_em->find(get_class($address), $address->getId());
$this->assertTrue($address2 !== $address);
$address3 = $this->_em->find(get_class($address), $address->getId());
$this->assertTrue($address2 === $address3);
$this->assertTrue($user2->getAddress() === $address2); // !!!
}
public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh()
{
$address = new CmsAddress;
$address->country = 'de';
$address->zip = '12345';
$address->city = 'Berlin';
$user1 = new CmsUser;
$user1->status = 'dev';
$user1->username = 'romanb';
$user1->name = 'Roman B.';
$user2 = new CmsUser;
$user2->status = 'dev';
$user2->username = 'gblanco';
$user2->name = 'Guilherme Blanco';
$address->setUser($user1);
$this->_em->persist($address);
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->flush();
$this->assertSame($user1, $address->user);
//external update to CmsAddress
$this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', array($user2->getId()));
// But we want to have this external change!
// Solution 1: refresh(), broken atm!
$this->_em->refresh($address);
// Now the association should be "correct", referencing $user2
$this->assertSame($user2, $address->user);
$this->assertSame($user2->address, $address); // check back reference also
// Attention! refreshes can result in broken bidirectional associations! this is currently expected!
// $user1 still points to $address!
$this->assertSame($user1->address, $address);
}
public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery()
{
$address = new CmsAddress;
$address->country = 'de';
$address->zip = '12345';
$address->city = 'Berlin';
$user1 = new CmsUser;
$user1->status = 'dev';
$user1->username = 'romanb';
$user1->name = 'Roman B.';
$user2 = new CmsUser;
$user2->status = 'dev';
$user2->username = 'gblanco';
$user2->name = 'Guilherme Blanco';
$address->setUser($user1);
$this->_em->persist($address);
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->flush();
$this->assertSame($user1, $address->user);
//external update to CmsAddress
$this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', array($user2->getId()));
//select
$q = $this->_em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u');
$address2 = $q->getSingleResult();
$this->assertSame($address, $address2);
// Should still be $user1
$this->assertSame($user1, $address2->user);
$this->assertTrue($user2->address === null);
// But we want to have this external change!
// Solution 2: Alternatively, a refresh query should work
$q = $this->_em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u');
$q->setHint(Query::HINT_REFRESH, true);
$address3 = $q->getSingleResult();
$this->assertSame($address, $address3); // should still be the same, always from identity map
// Now the association should be "correct", referencing $user2
$this->assertSame($user2, $address2->user);
$this->assertSame($user2->address, $address2); // check back reference also
// Attention! refreshes can result in broken bidirectional associations! this is currently expected!
// $user1 still points to $address2!
$this->assertSame($user1->address, $address2);
}
public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQuery()
{
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$phone1 = new CmsPhonenumber;
$phone1->phonenumber = 123;
$phone2 = new CmsPhonenumber;
$phone2->phonenumber = 234;
$phone3 = new CmsPhonenumber;
$phone3->phonenumber = 345;
$user->addPhonenumber($phone1);
$user->addPhonenumber($phone2);
$user->addPhonenumber($phone3);
$this->_em->persist($user); // cascaded to phone numbers
$this->_em->flush();
$this->assertEquals(3, count($user->getPhonenumbers()));
$this->assertFalse($user->getPhonenumbers()->isDirty());
//external update to CmsAddress
$this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', array(999, $user->getId()));
//select
$q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p');
$user2 = $q->getSingleResult();
$this->assertSame($user, $user2);
// Should still be the same 3 phonenumbers
$this->assertEquals(3, count($user2->getPhonenumbers()));
// But we want to have this external change!
// Solution 1: refresh().
//$this->_em->refresh($user2); broken atm!
// Solution 2: Alternatively, a refresh query should work
$q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p');
$q->setHint(Query::HINT_REFRESH, true);
$user3 = $q->getSingleResult();
$this->assertSame($user, $user3); // should still be the same, always from identity map
// Now the collection should be refreshed with correct count
$this->assertEquals(4, count($user3->getPhonenumbers()));
}
public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh()
{
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$phone1 = new CmsPhonenumber;
$phone1->phonenumber = 123;
$phone2 = new CmsPhonenumber;
$phone2->phonenumber = 234;
$phone3 = new CmsPhonenumber;
$phone3->phonenumber = 345;
$user->addPhonenumber($phone1);
$user->addPhonenumber($phone2);
$user->addPhonenumber($phone3);
$this->_em->persist($user); // cascaded to phone numbers
$this->_em->flush();
$this->assertEquals(3, count($user->getPhonenumbers()));
//external update to CmsAddress
$this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', array(999, $user->getId()));
//select
$q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p');
$user2 = $q->getSingleResult();
$this->assertSame($user, $user2);
// Should still be the same 3 phonenumbers
$this->assertEquals(3, count($user2->getPhonenumbers()));
// But we want to have this external change!
// Solution 1: refresh().
$this->_em->refresh($user2);
$this->assertSame($user, $user2); // should still be the same, always from identity map
// Now the collection should be refreshed with correct count
$this->assertEquals(4, count($user2->getPhonenumbers()));
}
public function testReusedSplObjectHashDoesNotConfuseUnitOfWork()
{
$hash1 = $this->subRoutine($this->_em);
// Make sure cycles are collected NOW, because a PersistentCollection references
// its owner, hence without forcing gc on cycles now the object will not (yet)
// be garbage collected and thus the object hash is not reused.
// This is not a memory leak!
gc_collect_cycles();
$user1 = new CmsUser;
$user1->status = 'dev';
$user1->username = 'jwage';
$user1->name = 'Jonathan W.';
$hash2 = spl_object_hash($user1);
$this->assertEquals($hash1, $hash2); // Hash reused!
$this->_em->persist($user1);
$this->_em->flush();
}
private function subRoutine($em) {
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$em->persist($user);
$em->flush();
$em->remove($user);
$em->flush();
return spl_object_hash($user);
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\StockExchange\Stock;
use Doctrine\Tests\Models\StockExchange\Market;
use Doctrine\Tests\Models\StockExchange\Bond;
require_once __DIR__ . '/../../TestInit.php';
/**
* @group DDC-250
*/
class IndexByAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var Doctrine\Tests\Models\StockExchange\Market
*/
private $market;
private $bond;
public function setUp()
{
$this->useModelSet('stockexchange');
parent::setUp();
$this->loadFixture();
}
public function loadFixture()
{
$this->market = new Market("Some Exchange");
$stock1 = new Stock("AAPL", 10, $this->market);
$stock2 = new Stock("GOOG", 20, $this->market);
$this->bond = new Bond("MyBond");
$this->bond->addStock($stock1);
$this->bond->addStock($stock2);
$this->_em->persist($this->market);
$this->_em->persist($stock1);
$this->_em->persist($stock2);
$this->_em->persist($this->bond);
$this->_em->flush();
$this->_em->clear();
}
public function testManyToOneFinder()
{
/* @var $market Doctrine\Tests\Models\StockExchange\Market */
$market = $this->_em->find('Doctrine\Tests\Models\StockExchange\Market', $this->market->getId());
$this->assertEquals(2, count($market->stocks));
$this->assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed assocation.");
$this->assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed assocation.");
$this->assertEquals("AAPL", $market->stocks['AAPL']->getSymbol());
$this->assertEquals("GOOG", $market->stocks['GOOG']->getSymbol());
}
public function testManyToOneDQL()
{
$dql = "SELECT m, s FROM Doctrine\Tests\Models\StockExchange\Market m JOIN m.stocks s WHERE m.id = ?1";
$market = $this->_em->createQuery($dql)->setParameter(1, $this->market->getId())->getSingleResult();
$this->assertEquals(2, count($market->stocks));
$this->assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed assocation.");
$this->assertTrue(isset($market->stocks['GOOG']), "GOOG symbol has to be key in indexed assocation.");
$this->assertEquals("AAPL", $market->stocks['AAPL']->getSymbol());
$this->assertEquals("GOOG", $market->stocks['GOOG']->getSymbol());
}
public function testManyToMany()
{
$bond = $this->_em->find('Doctrine\Tests\Models\StockExchange\Bond', $this->bond->getId());
$this->assertEquals(2, count($bond->stocks));
$this->assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed assocation.");
$this->assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed assocation.");
$this->assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol());
$this->assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol());
}
public function testManytoManyDQL()
{
$dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s WHERE b.id = ?1";
$bond = $this->_em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult();
$this->assertEquals(2, count($bond->stocks));
$this->assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed assocation.");
$this->assertTrue(isset($bond->stocks['GOOG']), "GOOG symbol has to be key in indexed assocation.");
$this->assertEquals("AAPL", $bond->stocks['AAPL']->getSymbol());
$this->assertEquals("GOOG", $bond->stocks['GOOG']->getSymbol());
}
public function testDqlOverrideIndexBy()
{
$dql = "SELECT b, s FROM Doctrine\Tests\Models\StockExchange\Bond b JOIN b.stocks s INDEX BY s.id WHERE b.id = ?1";
$bond = $this->_em->createQuery($dql)->setParameter(1, $this->bond->getId())->getSingleResult();
$this->assertEquals(2, count($bond->stocks));
$this->assertFalse(isset($bond->stocks['AAPL']), "AAPL symbol not exists in re-indexed assocation.");
$this->assertFalse(isset($bond->stocks['GOOG']), "GOOG symbol not exists in re-indexed assocation.");
}
}

View File

@@ -0,0 +1,311 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Event\PreUpdateEventArgs;
require_once __DIR__ . '/../../TestInit.php';
class LifecycleCallbackTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestUser'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackCascader'),
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
public function testPreSavePostSaveCallbacksAreInvoked()
{
$entity = new LifecycleCallbackTestEntity;
$entity->value = 'hello';
$this->_em->persist($entity);
$this->_em->flush();
$this->assertTrue($entity->prePersistCallbackInvoked);
$this->assertTrue($entity->postPersistCallbackInvoked);
$this->_em->clear();
$query = $this->_em->createQuery("select e from Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity e");
$result = $query->getResult();
$this->assertTrue($result[0]->postLoadCallbackInvoked);
$result[0]->value = 'hello again';
$this->_em->flush();
$this->assertEquals('changed from preUpdate callback!', $result[0]->value);
}
public function testPreFlushCallbacksAreInvoked()
{
$entity = new LifecycleCallbackTestEntity;
$entity->value = 'hello';
$this->_em->persist($entity);
$this->_em->flush();
$this->assertTrue($entity->prePersistCallbackInvoked);
$this->assertTrue($entity->preFlushCallbackInvoked);
$entity->preFlushCallbackInvoked = false;
$this->_em->flush();
$this->assertTrue($entity->preFlushCallbackInvoked);
$entity->value = 'bye';
$entity->preFlushCallbackInvoked = false;
$this->_em->flush();
$this->assertTrue($entity->preFlushCallbackInvoked);
}
public function testChangesDontGetLost()
{
$user = new LifecycleCallbackTestUser;
$user->setName('Bob');
$user->setValue('value');
$this->_em->persist($user);
$this->_em->flush();
$user->setName('Alice');
$this->_em->flush(); // Triggers preUpdate
$this->_em->clear();
$user2 = $this->_em->find(get_class($user), $user->getId());
$this->assertEquals('Alice', $user2->getName());
$this->assertEquals('Hello World', $user2->getValue());
}
/**
* @group DDC-194
*/
public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger()
{
$entity = new LifecycleCallbackTestEntity;
$entity->value = 'hello';
$this->_em->persist($entity);
$this->_em->flush();
$id = $entity->getId();
$this->_em->clear();
$reference = $this->_em->getReference('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity', $id);
$this->assertFalse($reference->postLoadCallbackInvoked);
$reference->getValue(); // trigger proxy load
$this->assertTrue($reference->postLoadCallbackInvoked);
}
/**
* @group DDC-958
*/
public function testPostLoadTriggeredOnRefresh()
{
$entity = new LifecycleCallbackTestEntity;
$entity->value = 'hello';
$this->_em->persist($entity);
$this->_em->flush();
$id = $entity->getId();
$this->_em->clear();
$reference = $this->_em->find('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity', $id);
$this->assertTrue($reference->postLoadCallbackInvoked);
$reference->postLoadCallbackInvoked = false;
$this->_em->refresh($reference);
$this->assertTrue($reference->postLoadCallbackInvoked, "postLoad should be invoked when refresh() is called.");
}
/**
* @group DDC-113
*/
public function testCascadedEntitiesCallsPrePersist()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$e1 = new LifecycleCallbackTestEntity;
$e2 = new LifecycleCallbackTestEntity;
$c = new LifecycleCallbackCascader();
$this->_em->persist($c);
$c->entities[] = $e1;
$c->entities[] = $e2;
$e1->cascader = $c;
$e2->cascader = $c;
//$this->_em->persist($c);
$this->_em->flush();
$this->assertTrue($e1->prePersistCallbackInvoked);
$this->assertTrue($e2->prePersistCallbackInvoked);
}
public function testLifecycleCallbacksGetInherited()
{
$childMeta = $this->_em->getClassMetadata(__NAMESPACE__ . '\LifecycleCallbackChildEntity');
$this->assertEquals(array('prePersist' => array(0 => 'doStuff')), $childMeta->lifecycleCallbacks);
}
public function testLifecycleListener_ChangeUpdateChangeSet()
{
$listener = new LifecycleListenerPreUpdate;
$this->_em->getEventManager()->addEventListener(array('preUpdate'), $listener);
$user = new LifecycleCallbackTestUser;
$user->setName('Bob');
$user->setValue('value');
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$dql = "SELECT u FROM Doctrine\Tests\ORM\Functional\LifecycleCallbackTestUser u WHERE u.name = 'Bob'";
$bob = $this->_em->createQuery($dql)->getSingleResult();
$bob->setName('Alice');
$this->_em->flush(); // preUpdate reverts Alice to Bob
$this->_em->clear();
$this->_em->getEventManager()->removeEventListener(array('preUpdate'), $listener);
$bob = $this->_em->createQuery($dql)->getSingleResult();
$this->assertEquals('Bob', $bob->getName());
}
}
/** @Entity @HasLifecycleCallbacks */
class LifecycleCallbackTestUser {
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column(type="string") */
private $value;
/** @Column(type="string") */
private $name;
public function getId() {return $this->id;}
public function getValue() {return $this->value;}
public function setValue($value) {$this->value = $value;}
public function getName() {return $this->name;}
public function setName($name) {$this->name = $name;}
/** @PreUpdate */
public function testCallback() {$this->value = 'Hello World';}
}
/**
* @Entity
* @HasLifecycleCallbacks
* @Table(name="lc_cb_test_entity")
*/
class LifecycleCallbackTestEntity
{
/* test stuff */
public $prePersistCallbackInvoked = false;
public $postPersistCallbackInvoked = false;
public $postLoadCallbackInvoked = false;
public $preFlushCallbackInvoked = false;
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string", nullable=true)
*/
public $value;
/**
* @ManyToOne(targetEntity="LifecycleCallbackCascader")
* @JoinColumn(name="cascader_id", referencedColumnName="id")
*/
public $cascader;
public function getId() {
return $this->id;
}
public function getValue() {
return $this->value;
}
/** @PrePersist */
public function doStuffOnPrePersist() {
$this->prePersistCallbackInvoked = true;
}
/** @PostPersist */
public function doStuffOnPostPersist() {
$this->postPersistCallbackInvoked = true;
}
/** @PostLoad */
public function doStuffOnPostLoad() {
$this->postLoadCallbackInvoked = true;
}
/** @PreUpdate */
public function doStuffOnPreUpdate() {
$this->value = 'changed from preUpdate callback!';
}
/** @PreFlush */
public function doStuffOnPreFlush() {
$this->preFlushCallbackInvoked = true;
}
}
/**
* @Entity
* @Table(name="lc_cb_test_cascade")
*/
class LifecycleCallbackCascader
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @OneToMany(targetEntity="LifecycleCallbackTestEntity", mappedBy="cascader", cascade={"persist"})
*/
public $entities;
public function __construct()
{
$this->entities = new \Doctrine\Common\Collections\ArrayCollection();
}
}
/** @MappedSuperclass @HasLifecycleCallbacks */
class LifecycleCallbackParentEntity {
/** @PrePersist */
function doStuff() {
}
}
/** @Entity @Table(name="lc_cb_childentity") */
class LifecycleCallbackChildEntity extends LifecycleCallbackParentEntity {
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
}
class LifecycleListenerPreUpdate
{
public function preUpdate(PreUpdateEventArgs $eventArgs)
{
$eventArgs->setNewValue('name', 'Bob');
}
}

View File

@@ -0,0 +1,180 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Locking;
use Doctrine\Tests\Models\CMS\CmsArticle,
Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\DBAL\LockMode,
Doctrine\ORM\EntityManager;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group locking_functional
*/
class GearmanLockTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $gearman = null;
private $maxRunTime = 0;
private $articleId;
protected function setUp()
{
if (!class_exists('GearmanClient', false)) {
$this->markTestSkipped('pecl/gearman is required for this test to run.');
}
$this->useModelSet('cms');
parent::setUp();
$this->tasks = array();
$this->gearman = new \GearmanClient();
$this->gearman->addServer();
$this->gearman->setCompleteCallback(array($this, "gearmanTaskCompleted"));
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->articleId = $article->id;
}
public function gearmanTaskCompleted($task)
{
$this->maxRunTime = max($this->maxRunTime, $task->data());
}
public function testFindWithLock()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockWorked();
}
public function testFindWithWriteThenReadLock()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ);
$this->assertLockWorked();
}
public function testFindWithReadThenWriteLock()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ);
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockWorked();
}
public function testFindWithOneLock()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::NONE);
$this->assertLockDoesNotBlock();
}
public function testDqlWithLock()
{
$this->asyncDqlWithLock('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a', array(), LockMode::PESSIMISTIC_WRITE);
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockWorked();
}
public function testLock()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockWorked();
}
public function testLock2()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ);
$this->assertLockWorked();
}
public function testLock3()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ);
$this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockWorked();
}
public function testLock4()
{
$this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::NONE);
$this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE);
$this->assertLockDoesNotBlock();
}
protected function assertLockDoesNotBlock()
{
$this->assertLockWorked($onlyForSeconds = 1);
}
protected function assertLockWorked($forTime = 2, $notLongerThan = null)
{
if ($notLongerThan === null) {
$notLongerThan = $forTime + 1;
}
$this->gearman->runTasks();
$this->assertTrue($this->maxRunTime > $forTime,
"Because of locking this tests should have run at least " . $forTime . " seconds, ".
"but only did for " . $this->maxRunTime . " seconds.");
$this->assertTrue($this->maxRunTime < $notLongerThan,
"The longest task should not run longer than " . $notLongerThan . " seconds, ".
"but did for " . $this->maxRunTime . " seconds."
);
}
protected function asyncFindWithLock($entityName, $entityId, $lockMode)
{
$this->startJob('findWithLock', array(
'entityName' => $entityName,
'entityId' => $entityId,
'lockMode' => $lockMode,
));
}
protected function asyncDqlWithLock($dql, $params, $lockMode)
{
$this->startJob('dqlWithLock', array(
'dql' => $dql,
'dqlParams' => $params,
'lockMode' => $lockMode,
));
}
protected function asyncLock($entityName, $entityId, $lockMode)
{
$this->startJob('lock', array(
'entityName' => $entityName,
'entityId' => $entityId,
'lockMode' => $lockMode,
));
}
protected function startJob($fn, $fixture)
{
$this->gearman->addTask($fn, serialize(array(
'conn' => $this->_em->getConnection()->getParams(),
'fixture' => $fixture
)));
$this->assertEquals(GEARMAN_SUCCESS, $this->gearman->returnCode());
}
}

View File

@@ -0,0 +1,112 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Locking;
require_once __DIR__ . "/../../../TestInit.php";
class LockAgentWorker
{
private $em;
static public function run()
{
$lockAgent = new LockAgentWorker();
$worker = new \GearmanWorker();
$worker->addServer();
$worker->addFunction("findWithLock", array($lockAgent, "findWithLock"));
$worker->addFunction("dqlWithLock", array($lockAgent, "dqlWithLock"));
$worker->addFunction('lock', array($lockAgent, 'lock'));
while($worker->work()) {
if ($worker->returnCode() != GEARMAN_SUCCESS) {
echo "return_code: " . $worker->returnCode() . "\n";
break;
}
}
}
protected function process($job, \Closure $do)
{
$fixture = $this->processWorkload($job);
$s = microtime(true);
$this->em->beginTransaction();
$do($fixture, $this->em);
sleep(1);
$this->em->rollback();
$this->em->clear();
$this->em->close();
$this->em->getConnection()->close();
return (microtime(true) - $s);
}
public function findWithLock($job)
{
return $this->process($job, function($fixture, $em) {
$entity = $em->find($fixture['entityName'], $fixture['entityId'], $fixture['lockMode']);
});
}
public function dqlWithLock($job)
{
return $this->process($job, function($fixture, $em) {
/* @var $query Doctrine\ORM\Query */
$query = $em->createQuery($fixture['dql']);
$query->setLockMode($fixture['lockMode']);
$query->setParameters($fixture['dqlParams']);
$result = $query->getResult();
});
}
public function lock($job)
{
return $this->process($job, function($fixture, $em) {
$entity = $em->find($fixture['entityName'], $fixture['entityId']);
$em->lock($entity, $fixture['lockMode']);
});
}
protected function processWorkload($job)
{
echo "Received job: " . $job->handle() . " for function " . $job->functionName() . "\n";
$workload = $job->workload();
$workload = unserialize($workload);
if (!isset($workload['conn']) || !is_array($workload['conn'])) {
throw new \InvalidArgumentException("Missing Database parameters");
}
$this->em = $this->createEntityManager($workload['conn']);
if (!isset($workload['fixture'])) {
throw new \InvalidArgumentException("Missing Fixture parameters");
}
return $workload['fixture'];
}
protected function createEntityManager($conn)
{
$config = new \Doctrine\ORM\Configuration();
$config->setProxyDir(__DIR__ . '/../../../Proxies');
$config->setProxyNamespace('MyProject\Proxies');
$config->setAutoGenerateProxyClasses(true);
$annotDriver = $config->newDefaultAnnotationDriver(array(__DIR__ . '/../../../Models/'));
$config->setMetadataDriverImpl($annotDriver);
$cache = new \Doctrine\Common\Cache\ArrayCache();
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$em = \Doctrine\ORM\EntityManager::create($conn, $config);
return $em;
}
}
LockAgentWorker::run();

View File

@@ -0,0 +1,184 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Locking;
use Doctrine\Tests\Models\CMS\CmsArticle,
Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\DBAL\LockMode,
Doctrine\ORM\EntityManager;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group locking
*/
class LockTest extends \Doctrine\Tests\OrmFunctionalTestCase {
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
$this->handles = array();
}
/**
* @group DDC-178
* @group locking
*/
public function testLockVersionedEntity() {
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->_em->lock($article, LockMode::OPTIMISTIC, $article->version);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockVersionedEntity_MissmatchThrowsException() {
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->setExpectedException('Doctrine\ORM\OptimisticLockException');
$this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockUnversionedEntity_ThrowsException() {
$user = new CmsUser();
$user->name = "foo";
$user->status = "active";
$user->username = "foo";
$this->_em->persist($user);
$this->_em->flush();
$this->setExpectedException('Doctrine\ORM\OptimisticLockException');
$this->_em->lock($user, LockMode::OPTIMISTIC);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockUnmanagedEntity_ThrowsException() {
$article = new CmsArticle();
$this->setExpectedException('InvalidArgumentException', 'Entity Doctrine\Tests\Models\CMS\CmsArticle');
$this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockPessimisticRead_NoTransaction_ThrowsException() {
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->setExpectedException('Doctrine\ORM\TransactionRequiredException');
$this->_em->lock($article, LockMode::PESSIMISTIC_READ);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockPessimisticWrite_NoTransaction_ThrowsException() {
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->setExpectedException('Doctrine\ORM\TransactionRequiredException');
$this->_em->lock($article, LockMode::PESSIMISTIC_WRITE);
}
/**
* @group DDC-178
* @group locking
*/
public function testLockPessimisticWrite() {
$writeLockSql = $this->_em->getConnection()->getDatabasePlatform()->getWriteLockSql();
if (strlen($writeLockSql) == 0) {
$this->markTestSkipped('Database Driver has no Write Lock support.');
}
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->_em->beginTransaction();
try {
$this->_em->lock($article, LockMode::PESSIMISTIC_WRITE);
$this->_em->commit();
} catch (\Exception $e) {
$this->_em->rollback();
throw $e;
}
$query = array_pop( $this->_sqlLoggerStack->queries );
$this->assertContains($writeLockSql, $query['sql']);
}
/**
* @group DDC-178
*/
public function testLockPessimisticRead() {
$readLockSql = $this->_em->getConnection()->getDatabasePlatform()->getReadLockSql();
if (strlen($readLockSql) == 0) {
$this->markTestSkipped('Database Driver has no Write Lock support.');
}
$article = new CmsArticle();
$article->text = "my article";
$article->topic = "Hello";
$this->_em->persist($article);
$this->_em->flush();
$this->_em->beginTransaction();
try {
$this->_em->lock($article, LockMode::PESSIMISTIC_READ);
$this->_em->commit();
} catch (\Exception $e) {
$this->_em->rollback();
throw $e;
}
$query = array_pop( $this->_sqlLoggerStack->queries );
$this->assertContains($readLockSql, $query['sql']);
}
/**
* @group DDC-1693
*/
public function testLockOptimisticNonVersionedThrowsExceptionInDQL()
{
$dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'";
$this->setExpectedException('Doctrine\ORM\OptimisticLockException', 'The optimistic lock on an entity failed.');
$sql = $this->_em->createQuery($dql)->setHint(
\Doctrine\ORM\Query::HINT_LOCK_MODE, \Doctrine\DBAL\LockMode::OPTIMISTIC
)->getSQL();
}
}

View File

@@ -0,0 +1,277 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Locking;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\Common\EventManager;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\Tests\TestUtil;
require_once __DIR__ . '/../../../TestInit.php';
class OptimisticTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp')
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
$this->_conn = $this->_em->getConnection();
}
public function testJoinedChildInsertSetsInitialVersionValue()
{
$test = new OptimisticJoinedChild();
$test->name = 'child';
$test->whatever = 'whatever';
$this->_em->persist($test);
$this->_em->flush();
$this->assertEquals(1, $test->version);
return $test;
}
/**
* @depends testJoinedChildInsertSetsInitialVersionValue
*/
public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $child)
{
$q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild t WHERE t.id = :id');
$q->setParameter('id', $child->id);
$test = $q->getSingleResult();
// Manually update/increment the version so we can try and save the same
// $test and make sure the exception is thrown saying the record was
// changed or updated since you read it
$this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', array(2, $test->id));
// Now lets change a property and try and save it again
$test->whatever = 'ok';
try {
$this->_em->flush();
} catch (OptimisticLockException $e) {
$this->assertSame($test, $e->getEntity());
}
}
public function testJoinedParentInsertSetsInitialVersionValue()
{
$test = new OptimisticJoinedParent();
$test->name = 'parent';
$this->_em->persist($test);
$this->_em->flush();
$this->assertEquals(1, $test->version);
return $test;
}
/**
* @depends testJoinedParentInsertSetsInitialVersionValue
*/
public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $parent)
{
$q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent t WHERE t.id = :id');
$q->setParameter('id', $parent->id);
$test = $q->getSingleResult();
// Manually update/increment the version so we can try and save the same
// $test and make sure the exception is thrown saying the record was
// changed or updated since you read it
$this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', array(2, $test->id));
// Now lets change a property and try and save it again
$test->name = 'WHATT???';
try {
$this->_em->flush();
} catch (OptimisticLockException $e) {
$this->assertSame($test, $e->getEntity());
}
}
public function testMultipleFlushesDoIncrementalUpdates()
{
$test = new OptimisticStandard();
for ($i = 0; $i < 5; $i++) {
$test->name = 'test' . $i;
$this->_em->persist($test);
$this->_em->flush();
$this->assertInternalType('int', $test->getVersion());
$this->assertEquals($i + 1, $test->getVersion());
}
}
public function testStandardInsertSetsInitialVersionValue()
{
$test = new OptimisticStandard();
$test->name = 'test';
$this->_em->persist($test);
$this->_em->flush();
$this->assertInternalType('int', $test->getVersion());
$this->assertEquals(1, $test->getVersion());
return $test;
}
/**
* @depends testStandardInsertSetsInitialVersionValue
*/
public function testStandardFailureThrowsException(OptimisticStandard $entity)
{
$q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard t WHERE t.id = :id');
$q->setParameter('id', $entity->id);
$test = $q->getSingleResult();
// Manually update/increment the version so we can try and save the same
// $test and make sure the exception is thrown saying the record was
// changed or updated since you read it
$this->_conn->executeQuery('UPDATE optimistic_standard SET version = ? WHERE id = ?', array(2, $test->id));
// Now lets change a property and try and save it again
$test->name = 'WHATT???';
try {
$this->_em->flush();
} catch (OptimisticLockException $e) {
$this->assertSame($test, $e->getEntity());
}
}
public function testOptimisticTimestampSetsDefaultValue()
{
$test = new OptimisticTimestamp();
$test->name = 'Testing';
$this->assertNull($test->version, "Pre-Condition");
$this->_em->persist($test);
$this->_em->flush();
$this->assertInstanceOf('DateTime', $test->version);
return $test;
}
/**
* @depends testOptimisticTimestampSetsDefaultValue
*/
public function testOptimisticTimestampFailureThrowsException(OptimisticTimestamp $entity)
{
$q = $this->_em->createQuery('SELECT t FROM Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp t WHERE t.id = :id');
$q->setParameter('id', $entity->id);
$test = $q->getSingleResult();
$this->assertInstanceOf('DateTime', $test->version);
// Manually increment the version datetime column
$format = $this->_em->getConnection()->getDatabasePlatform()->getDateTimeFormatString();
$this->_conn->executeQuery('UPDATE optimistic_timestamp SET version = ? WHERE id = ?', array(date($format, strtotime($test->version->format($format)) + 3600), $test->id));
// Try and update the record and it should throw an exception
$test->name = 'Testing again';
try {
$this->_em->flush();
} catch (OptimisticLockException $e) {
$this->assertSame($test, $e->getEntity());
}
}
}
/**
* @Entity
* @Table(name="optimistic_joined_parent")
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"parent" = "OptimisticJoinedParent", "child" = "OptimisticJoinedChild"})
*/
class OptimisticJoinedParent
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=255)
*/
public $name;
/**
* @Version @Column(type="integer")
*/
public $version;
}
/**
* @Entity
* @Table(name="optimistic_joined_child")
*/
class OptimisticJoinedChild extends OptimisticJoinedParent
{
/**
* @Column(type="string", length=255)
*/
public $whatever;
}
/**
* @Entity
* @Table(name="optimistic_standard")
*/
class OptimisticStandard
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=255)
*/
public $name;
/**
* @Version @Column(type="integer")
*/
private $version;
function getVersion() {return $this->version;}
}
/**
* @Entity
* @Table(name="optimistic_timestamp")
*/
class OptimisticTimestamp
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=255)
*/
public $name;
/**
* @Version @Column(type="datetime")
*/
public $version;
}

View File

@@ -0,0 +1,380 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\Tests\Models\CMS\CmsGroup,
Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../TestInit.php';
/**
* Basic many-to-many association tests.
* ("Working with associations")
*
* @author robo
*/
class ManyToManyBasicAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testUnsetManyToMany()
{
$user = $this->addCmsUserGblancoWithGroups(1);
unset($user->groups[0]->users[0]); // inverse side
unset($user->groups[0]); // owning side!
$this->_em->flush();
// Check that the link in the association table has been deleted
$this->assertGblancoGroupCountIs(0);
}
public function testBasicManyToManyJoin()
{
$user = $this->addCmsUserGblancoWithGroups(1);
$this->_em->clear();
$this->assertEquals(0, $this->_em->getUnitOfWork()->size());
$query = $this->_em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g");
$result = $query->getResult();
$this->assertEquals(2, $this->_em->getUnitOfWork()->size());
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]);
$this->assertEquals('Guilherme', $result[0]->name);
$this->assertEquals(1, $result[0]->getGroups()->count());
$groups = $result[0]->getGroups();
$this->assertEquals('Developers_0', $groups[0]->getName());
$this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($result[0]));
$this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($groups[0]));
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $groups);
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $groups[0]->getUsers());
$groups[0]->getUsers()->clear();
$groups->clear();
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select u, g from Doctrine\Tests\Models\CMS\CmsUser u join u.groups g");
$this->assertEquals(0, count($query->getResult()));
}
public function testManyToManyAddRemove()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$this->_em->clear();
$uRep = $this->_em->getRepository(get_class($user));
// Get user
$user = $uRep->findOneById($user->getId());
$this->assertNotNull($user, "Has to return exactly one entry.");
$this->assertFalse($user->getGroups()->isInitialized());
// Check groups
$this->assertEquals(2, $user->getGroups()->count());
$this->assertTrue($user->getGroups()->isInitialized());
// Remove first group
unset($user->groups[0]);
//$user->getGroups()->remove(0);
$this->_em->flush();
$this->_em->clear();
// Reload same user
$user2 = $uRep->findOneById($user->getId());
// Check groups
$this->assertEquals(1, $user2->getGroups()->count());
}
public function testManyToManyInverseSideIgnored()
{
$user = $this->addCmsUserGblancoWithGroups(0);
$group = new CmsGroup;
$group->name = 'Humans';
// modify directly, addUser() would also (properly) set the owning side
$group->users[] = $user;
$this->_em->persist($user);
$this->_em->persist($group);
$this->_em->flush();
$this->_em->clear();
// Association should not exist
$user2 = $this->_em->find(get_class($user), $user->getId());
$this->assertNotNull($user2, "Has to return exactly one entry.");
$this->assertEquals(0, $user2->getGroups()->count());
}
public function testManyToManyCollectionClearing()
{
$user = $this->addCmsUserGblancoWithGroups($groupCount = 10);
// Check that there are indeed 10 links in the association table
$this->assertGblancoGroupCountIs($groupCount);
$user->groups->clear();
$this->_em->flush();
// Check that the links in the association table have been deleted
$this->assertGblancoGroupCountIs(0);
}
public function testManyToManyCollectionClearAndAdd()
{
$user = $this->addCmsUserGblancoWithGroups($groupCount = 10);
$groups = $user->groups->toArray();
$user->groups->clear();
foreach ($groups AS $group) {
$user->groups[] = $group;
}
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->groups);
$this->assertTrue($user->groups->isDirty());
$this->assertEquals($groupCount, count($user->groups), "There should be 10 groups in the collection.");
$this->_em->flush();
$this->assertGblancoGroupCountIs($groupCount);
}
/**
* @param int $expectedGroupCount
*/
public function assertGblancoGroupCountIs($expectedGroupCount)
{
$countDql = "SELECT count(g.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g WHERE u.username = 'gblanco'";
$this->assertEquals(
$expectedGroupCount,
$this->_em->createQuery($countDql)->getSingleScalarResult(),
"Failed to verify that CmsUser with username 'gblanco' has a group count of 10 with a DQL count query."
);
}
public function testRetrieveManyToManyAndAddMore()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$group = new CmsGroup();
$group->name = 'Developers_Fresh';
$this->_em->persist($group);
$this->_em->flush();
$this->_em->clear();
/* @var $freshUser CmsUser */
$freshUser = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->getId());
$newGroup = new CmsGroup();
$newGroup->setName('12Monkeys');
$freshUser->addGroup($newGroup);
$this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test.");
$this->_em->flush();
$this->assertFalse($freshUser->groups->isInitialized(), "CmsUser::groups Collection has to be uninitialized for this test.");
$this->assertEquals(3, count($freshUser->getGroups()));
$this->assertEquals(3, count($freshUser->getGroups()->getSnapshot()), "Snapshot of CmsUser::groups should contain 3 entries.");
$this->_em->clear();
$freshUser = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->getId());
$this->assertEquals(3, count($freshUser->getGroups()));
}
/**
* @group DDC-130
*/
public function testRemoveUserWithManyGroups()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$userId = $user->getId();
$this->_em->remove($user);
$this->_em->flush();
$newUser = $this->_em->find(get_class($user), $userId);
$this->assertNull($newUser);
}
/**
* @group DDC-130
*/
public function testRemoveGroupWithUser()
{
$user = $this->addCmsUserGblancoWithGroups(2);
foreach ($user->getGroups() AS $group) {
$this->_em->remove($group);
}
$this->_em->flush();
$this->_em->clear();
$newUser = $this->_em->find(get_class($user), $user->getId());
$this->assertEquals(0, count($newUser->getGroups()));
}
public function testDereferenceCollectionDelete()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$user->groups = null;
$this->_em->flush();
$this->_em->clear();
$newUser = $this->_em->find(get_class($user), $user->getId());
$this->assertEquals(0, count($newUser->getGroups()));
}
/**
* @group DDC-839
*/
public function testWorkWithDqlHydratedEmptyCollection()
{
$user = $this->addCmsUserGblancoWithGroups(0);
$group = new CmsGroup();
$group->name = "Developers0";
$this->_em->persist($group);
$this->_em->flush();
$this->_em->clear();
$newUser = $this->_em->createQuery('SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.groups g WHERE u.id = ?1')
->setParameter(1, $user->getId())
->getSingleResult();
$this->assertEquals(0, count($newUser->groups));
$this->assertInternalType('array', $newUser->groups->getMapping());
$newUser->addGroup($group);
$this->_em->flush();
$this->_em->clear();
$newUser = $this->_em->find(get_class($user), $user->getId());
$this->assertEquals(1, count($newUser->groups));
}
/**
* @param int $groupCount
* @return CmsUser
*/
public function addCmsUserGblancoWithGroups($groupCount = 1)
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
for ($i=0; $i < $groupCount; ++$i) {
$group = new CmsGroup;
$group->name = 'Developers_' . $i;
$user->addGroup($group);
}
$this->_em->persist($user);
$this->_em->flush();
$this->assertNotNull($user->getId(), "User 'gblanco' should have an ID assigned after the persist()/flush() operation.");
return $user;
}
/**
* @group DDC-980
*/
public function testUpdateDeleteSizeSubselectQueries()
{
$this->_em->createQuery("DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) = 10")->execute();
$this->_em->createQuery("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10")->execute();
}
/**
* @group DDC-978
*/
public function testClearAndResetCollection()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$group1 = new CmsGroup;
$group1->name = 'Developers_New1';
$group2 = new CmsGroup;
$group2->name = 'Developers_New2';
$this->_em->persist($group1);
$this->_em->persist($group2);
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find(get_class($user), $user->id);
$coll = new ArrayCollection(array($group1, $group2));
$user->groups = $coll;
$this->_em->flush();
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->groups,
"UnitOfWork should have replaced ArrayCollection with PersistentCollection.");
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find(get_class($user), $user->id);
$this->assertEquals(2, count($user->groups));
$this->assertEquals('Developers_New1', $user->groups[0]->name);
$this->assertEquals('Developers_New2', $user->groups[1]->name);
}
/**
* @group DDC-733
*/
public function testInitializePersistentCollection()
{
$user = $this->addCmsUserGblancoWithGroups(2);
$this->_em->clear();
$user = $this->_em->find(get_class($user), $user->id);
$this->assertFalse($user->groups->isInitialized(), "Pre-condition: lazy collection");
$this->_em->getUnitOfWork()->initializeObject($user->groups);
$this->assertTrue($user->groups->isInitialized(), "Collection should be initialized after calling UnitOfWork::initializeObject()");
}
/**
* @group DDC-1189
* @group DDC-956
*/
public function testClearBeforeLazyLoad()
{
$user = $this->addCmsUserGblancoWithGroups(4);
$this->_em->clear();
$user = $this->_em->find(get_class($user), $user->id);
$user->groups->clear();
$this->assertEquals(0, count($user->groups));
$this->_em->flush();
$user = $this->_em->find(get_class($user), $user->id);
$this->assertEquals(0, count($user->groups));
}
}

View File

@@ -0,0 +1,202 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceCategory;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional many-to-many association mapping (without inheritance).
* Owning side is ECommerceProduct, inverse side is ECommerceCategory.
*/
class ManyToManyBidirectionalAssociationTest extends AbstractManyToManyAssociationTestCase
{
protected $_firstField = 'product_id';
protected $_secondField = 'category_id';
protected $_table = 'ecommerce_products_categories';
private $firstProduct;
private $secondProduct;
private $firstCategory;
private $secondCategory;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->firstProduct = new ECommerceProduct();
$this->firstProduct->setName("First Product");
$this->secondProduct = new ECommerceProduct();
$this->secondProduct->setName("Second Product");
$this->firstCategory = new ECommerceCategory();
$this->firstCategory->setName("Business");
$this->secondCategory = new ECommerceCategory();
$this->secondCategory->setName("Home");
}
public function testSavesAManyToManyAssociationWithCascadeSaveSet()
{
$this->firstProduct->addCategory($this->firstCategory);
$this->firstProduct->addCategory($this->secondCategory);
$this->_em->persist($this->firstProduct);
$this->_em->flush();
$this->assertForeignKeysContain($this->firstProduct->getId(), $this->firstCategory->getId());
$this->assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId());
}
public function testRemovesAManyToManyAssociation()
{
$this->firstProduct->addCategory($this->firstCategory);
$this->firstProduct->addCategory($this->secondCategory);
$this->_em->persist($this->firstProduct);
$this->firstProduct->removeCategory($this->firstCategory);
$this->_em->flush();
$this->assertForeignKeysNotContain($this->firstProduct->getId(), $this->firstCategory->getId());
$this->assertForeignKeysContain($this->firstProduct->getId(), $this->secondCategory->getId());
$this->firstProduct->getCategories()->remove(1);
$this->_em->flush();
$this->assertForeignKeysNotContain($this->firstProduct->getId(), $this->secondCategory->getId());
}
public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_createLoadingFixture();
$categories = $this->_findCategories();
$this->assertLazyLoadFromOwningSide($categories);
}
public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_createLoadingFixture();
$products = $this->_findProducts();
$this->assertLazyLoadFromInverseSide($products);
}
private function _createLoadingFixture()
{
$this->firstProduct->addCategory($this->firstCategory);
$this->firstProduct->addCategory($this->secondCategory);
$this->secondProduct->addCategory($this->firstCategory);
$this->secondProduct->addCategory($this->secondCategory);
$this->_em->persist($this->firstProduct);
$this->_em->persist($this->secondProduct);
$this->_em->flush();
$this->_em->clear();
}
protected function _findProducts()
{
$query = $this->_em->createQuery('SELECT p, c FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p LEFT JOIN p.categories c ORDER BY p.id, c.id');
//$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$result = $query->getResult();
$this->assertEquals(2, count($result));
$cats1 = $result[0]->getCategories();
$cats2 = $result[1]->getCategories();
$this->assertTrue($cats1->isInitialized());
$this->assertTrue($cats2->isInitialized());
$this->assertFalse($cats1[0]->getProducts()->isInitialized());
$this->assertFalse($cats2[0]->getProducts()->isInitialized());
return $result;
}
protected function _findCategories()
{
$query = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\ECommerce\ECommerceCategory c LEFT JOIN c.products p ORDER BY c.id, p.id');
//$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$result = $query->getResult();
$this->assertEquals(2, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $result[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $result[1]);
$prods1 = $result[0]->getProducts();
$prods2 = $result[1]->getProducts();
$this->assertTrue($prods1->isInitialized());
$this->assertTrue($prods2->isInitialized());
$this->assertFalse($prods1[0]->getCategories()->isInitialized());
$this->assertFalse($prods2[0]->getCategories()->isInitialized());
return $result;
}
public function assertLazyLoadFromInverseSide($products)
{
list ($firstProduct, $secondProduct) = $products;
$firstProductCategories = $firstProduct->getCategories();
$secondProductCategories = $secondProduct->getCategories();
$this->assertEquals(2, count($firstProductCategories));
$this->assertEquals(2, count($secondProductCategories));
$this->assertTrue($firstProductCategories[0] === $secondProductCategories[0]);
$this->assertTrue($firstProductCategories[1] === $secondProductCategories[1]);
$firstCategoryProducts = $firstProductCategories[0]->getProducts();
$secondCategoryProducts = $firstProductCategories[1]->getProducts();
$this->assertFalse($firstCategoryProducts->isInitialized());
$this->assertFalse($secondCategoryProducts->isInitialized());
$this->assertEquals(0, $firstCategoryProducts->unwrap()->count());
$this->assertEquals(0, $secondCategoryProducts->unwrap()->count());
$this->assertEquals(2, count($firstCategoryProducts)); // lazy-load
$this->assertTrue($firstCategoryProducts->isInitialized());
$this->assertFalse($secondCategoryProducts->isInitialized());
$this->assertEquals(2, count($secondCategoryProducts)); // lazy-load
$this->assertTrue($secondCategoryProducts->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstCategoryProducts[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstCategoryProducts[1]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondCategoryProducts[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondCategoryProducts[1]);
$this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts);
}
public function assertLazyLoadFromOwningSide($categories)
{
list ($firstCategory, $secondCategory) = $categories;
$firstCategoryProducts = $firstCategory->getProducts();
$secondCategoryProducts = $secondCategory->getProducts();
$this->assertEquals(2, count($firstCategoryProducts));
$this->assertEquals(2, count($secondCategoryProducts));
$this->assertTrue($firstCategoryProducts[0] === $secondCategoryProducts[0]);
$this->assertTrue($firstCategoryProducts[1] === $secondCategoryProducts[1]);
$firstProductCategories = $firstCategoryProducts[0]->getCategories();
$secondProductCategories = $firstCategoryProducts[1]->getCategories();
$this->assertFalse($firstProductCategories->isInitialized());
$this->assertFalse($secondProductCategories->isInitialized());
$this->assertEquals(0, $firstProductCategories->unwrap()->count());
$this->assertEquals(0, $secondProductCategories->unwrap()->count());
$this->assertEquals(2, count($firstProductCategories)); // lazy-load
$this->assertTrue($firstProductCategories->isInitialized());
$this->assertFalse($secondProductCategories->isInitialized());
$this->assertEquals(2, count($secondProductCategories)); // lazy-load
$this->assertTrue($secondProductCategories->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $firstProductCategories[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $firstProductCategories[1]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $secondProductCategories[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $secondProductCategories[1]);
$this->assertCollectionEquals($firstProductCategories, $secondProductCategories);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsGroup;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* ManyToManyEventTest
*
* @author Francisco Facioni <fran6co@gmail.com>
*/
class ManyToManyEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var PostUpdateListener
*/
private $listener;
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$this->listener = new PostUpdateListener();
$evm = $this->_em->getEventManager();
$evm->addEventListener(Events::postUpdate, $this->listener);
}
public function testListenerShouldBeNotifiedOnlyWhenUpdating()
{
$user = $this->createNewValidUser();
$this->_em->persist($user);
$this->_em->flush();
$this->assertFalse($this->listener->wasNotified);
$group = new CmsGroup();
$group->name = "admins";
$user->addGroup($group);
$this->_em->persist($user);
$this->_em->flush();
$this->assertTrue($this->listener->wasNotified);
}
/**
* @return CmsUser
*/
private function createNewValidUser()
{
$user = new CmsUser();
$user->username = 'fran6co';
$user->name = 'Francisco Facioni';
$group = new CmsGroup();
$group->name = "users";
$user->addGroup($group);
return $user;
}
}
class PostUpdateListener
{
/**
* @var bool
*/
public $wasNotified = false;
/**
* @param $args
*/
public function postUpdate($args)
{
$this->wasNotified = true;
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a self referential many-to-many association mapping (from a model to the same model, without inheritance).
* For simplicity the relation duplicates entries in the association table
* to remain simmetrical.
*/
class ManyToManySelfReferentialAssociationTest extends AbstractManyToManyAssociationTestCase
{
protected $_firstField = 'product_id';
protected $_secondField = 'related_id';
protected $_table = 'ecommerce_products_related';
private $firstProduct;
private $secondProduct;
private $firstRelated;
private $secondRelated;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->firstProduct = new ECommerceProduct();
$this->secondProduct = new ECommerceProduct();
$this->firstRelated = new ECommerceProduct();
$this->firstRelated->setName("Business");
$this->secondRelated = new ECommerceProduct();
$this->secondRelated->setName("Home");
}
public function testSavesAManyToManyAssociationWithCascadeSaveSet()
{
$this->firstProduct->addRelated($this->firstRelated);
$this->firstProduct->addRelated($this->secondRelated);
$this->_em->persist($this->firstProduct);
$this->_em->flush();
$this->assertForeignKeysContain($this->firstProduct->getId(),
$this->firstRelated->getId());
$this->assertForeignKeysContain($this->firstProduct->getId(),
$this->secondRelated->getId());
}
public function testRemovesAManyToManyAssociation()
{
$this->firstProduct->addRelated($this->firstRelated);
$this->firstProduct->addRelated($this->secondRelated);
$this->_em->persist($this->firstProduct);
$this->firstProduct->removeRelated($this->firstRelated);
$this->_em->flush();
$this->assertForeignKeysNotContain($this->firstProduct->getId(),
$this->firstRelated->getId());
$this->assertForeignKeysContain($this->firstProduct->getId(),
$this->secondRelated->getId());
}
public function testEagerLoadsOwningSide()
{
$this->_createLoadingFixture();
$products = $this->_findProducts();
$this->assertLoadingOfOwningSide($products);
}
public function testLazyLoadsOwningSide()
{
$this->_createLoadingFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$metadata->associationMappings['related']['fetch'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$products = $query->getResult();
$this->assertLoadingOfOwningSide($products);
}
public function assertLoadingOfOwningSide($products)
{
list ($firstProduct, $secondProduct) = $products;
$this->assertEquals(2, count($firstProduct->getRelated()));
$this->assertEquals(2, count($secondProduct->getRelated()));
$categories = $firstProduct->getRelated();
$firstRelatedBy = $categories[0]->getRelated();
$secondRelatedBy = $categories[1]->getRelated();
$this->assertEquals(2, count($firstRelatedBy));
$this->assertEquals(2, count($secondRelatedBy));
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstRelatedBy[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstRelatedBy[1]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondRelatedBy[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondRelatedBy[1]);
$this->assertCollectionEquals($firstRelatedBy, $secondRelatedBy);
}
protected function _createLoadingFixture()
{
$this->firstProduct->addRelated($this->firstRelated);
$this->firstProduct->addRelated($this->secondRelated);
$this->secondProduct->addRelated($this->firstRelated);
$this->secondProduct->addRelated($this->secondRelated);
$this->_em->persist($this->firstProduct);
$this->_em->persist($this->secondProduct);
$this->_em->flush();
$this->_em->clear();
}
protected function _findProducts()
{
$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->getResult();
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a unidirectional many-to-many association mapping (without inheritance).
* Inverse side is not present.
*/
class ManyToManyUnidirectionalAssociationTest extends AbstractManyToManyAssociationTestCase
{
protected $_firstField = 'cart_id';
protected $_secondField = 'product_id';
protected $_table = 'ecommerce_carts_products';
private $firstProduct;
private $secondProduct;
private $firstCart;
private $secondCart;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->firstProduct = new ECommerceProduct();
$this->firstProduct->setName('Doctrine 1.x Manual');
$this->secondProduct = new ECommerceProduct();
$this->secondProduct->setName('Doctrine 2.x Manual');
$this->firstCart = new ECommerceCart();
$this->secondCart = new ECommerceCart();
}
public function testSavesAManyToManyAssociationWithCascadeSaveSet()
{
$this->firstCart->addProduct($this->firstProduct);
$this->firstCart->addProduct($this->secondProduct);
$this->_em->persist($this->firstCart);
$this->_em->flush();
$this->assertForeignKeysContain($this->firstCart->getId(), $this->firstProduct->getId());
$this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId());
}
public function testRemovesAManyToManyAssociation()
{
$this->firstCart->addProduct($this->firstProduct);
$this->firstCart->addProduct($this->secondProduct);
$this->_em->persist($this->firstCart);
$this->firstCart->removeProduct($this->firstProduct);
$this->_em->flush();
$this->assertForeignKeysNotContain($this->firstCart->getId(), $this->firstProduct->getId());
$this->assertForeignKeysContain($this->firstCart->getId(), $this->secondProduct->getId());
}
public function testEagerLoad()
{
$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->getResult();
$firstCart = $result[0];
$products = $firstCart->getProducts();
$secondCart = $result[1];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[1]);
$this->assertCollectionEquals($products, $secondCart->getProducts());
//$this->assertEquals("Doctrine 1.x Manual", $products[0]->getName());
//$this->assertEquals("Doctrine 2.x Manual", $products[1]->getName());
}
public function testLazyLoadsCollection()
{
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart');
$metadata->associationMappings['products']['fetch'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c');
$result = $query->getResult();
$firstCart = $result[0];
$products = $firstCart->getProducts();
$secondCart = $result[1];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[0]);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[1]);
$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();
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
/**
* MappedSuperclassTest
*
* @author robo
*/
class MappedSuperclassTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
$this->useModelSet('directorytree');
parent::setUp();
}
public function testCRUD()
{
$root = new \Doctrine\Tests\Models\DirectoryTree\Directory();
$root->setName('Root');
$root->setPath('/root');
$directory = new \Doctrine\Tests\Models\DirectoryTree\Directory($root);
$directory->setName('TestA');
$directory->setPath('/root/dir');
$file = new \Doctrine\Tests\Models\DirectoryTree\File($directory);
$file->setName('test-b.html');
$this->_em->persist($root);
$this->_em->persist($directory);
$this->_em->persist($file);
$this->_em->flush();
$this->_em->clear();
$cleanFile = $this->_em->find(get_class($file), $file->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\DirectoryTree\Directory', $cleanFile->getParent());
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $cleanFile->getParent());
$this->assertEquals($directory->getId(), $cleanFile->getParent()->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\DirectoryTree\Directory', $cleanFile->getParent()->getParent());
$this->assertEquals($root->getId(), $cleanFile->getParent()->getParent()->getId());
}
}

View File

@@ -0,0 +1,333 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\Tests\Models\CMS\CmsAddress;
use Doctrine\Tests\Models\Company\CompanyFixContract;
use Doctrine\Tests\Models\Company\CompanyEmployee;
require_once __DIR__ . '/../../TestInit.php';
/**
* NativeQueryTest
*
* @author robo
*/
class NativeQueryTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $platform = null;
protected function setUp() {
$this->useModelSet('cms');
parent::setUp();
$this->platform = $this->_em->getConnection()->getDatabasePlatform();
}
public function testBasicNativeQuery()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name');
$query = $this->_em->createNativeQuery('SELECT id, name FROM cms_users WHERE username = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals('Roman', $users[0]->name);
}
public function testBasicNativeQueryWithMetaResult()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$addr = new CmsAddress;
$addr->country = 'germany';
$addr->zip = 10827;
$addr->city = 'Berlin';
$user->setAddress($addr);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsAddress', 'a');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('id'), 'id');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('city'), 'city');
$rsm->addMetaResult('a', $this->platform->getSQLResultCasing('user_id'), 'user_id');
$query = $this->_em->createNativeQuery('SELECT a.id, a.country, a.zip, a.city, a.user_id FROM cms_addresses a WHERE a.id = ?', $rsm);
$query->setParameter(1, $addr->id);
$addresses = $query->getResult();
$this->assertEquals(1, count($addresses));
$this->assertTrue($addresses[0] instanceof CmsAddress);
$this->assertEquals($addr->country, $addresses[0]->country);
$this->assertEquals($addr->zip, $addresses[0]->zip);
$this->assertEquals($addr->city, $addresses[0]->city);
$this->assertEquals($addr->street, $addresses[0]->street);
$this->assertTrue($addresses[0]->user instanceof CmsUser);
}
public function testJoinedOneToManyNativeQuery()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$phone = new CmsPhonenumber;
$phone->phonenumber = 424242;
$user->addPhonenumber($phone);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('status'), 'status');
$rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers');
$rsm->addFieldResult('p', $this->platform->getSQLResultCasing('phonenumber'), 'phonenumber');
$query = $this->_em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals('Roman', $users[0]->name);
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers());
$this->assertTrue($users[0]->getPhonenumbers()->isInitialized());
$this->assertEquals(1, count($users[0]->getPhonenumbers()));
$phones = $users[0]->getPhonenumbers();
$this->assertEquals(424242, $phones[0]->phonenumber);
$this->assertTrue($phones[0]->getUser() === $users[0]);
}
public function testJoinedOneToOneNativeQuery()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$addr = new CmsAddress;
$addr->country = 'germany';
$addr->zip = 10827;
$addr->city = 'Berlin';
$user->setAddress($addr);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name');
$rsm->addFieldResult('u', $this->platform->getSQLResultCasing('status'), 'status');
$rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('a_id'), 'id');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip');
$rsm->addFieldResult('a', $this->platform->getSQLResultCasing('city'), 'city');
$query = $this->_em->createNativeQuery('SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals('Roman', $users[0]->name);
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers());
$this->assertFalse($users[0]->getPhonenumbers()->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $users[0]->getAddress());
$this->assertTrue($users[0]->getAddress()->getUser() == $users[0]);
$this->assertEquals('germany', $users[0]->getAddress()->getCountry());
$this->assertEquals(10827, $users[0]->getAddress()->getZipCode());
$this->assertEquals('Berlin', $users[0]->getAddress()->getCity());
}
public function testFluentInterface()
{
$rsm = new ResultSetMapping;
$q = $this->_em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm);
$q2 = $q->setSql('foo', $rsm)
->setResultSetMapping($rsm)
->expireResultCache(true)
->setHint('foo', 'bar')
->setParameter(1, 'foo')
->setParameters(array(2 => 'bar'))
->setResultCacheDriver(null)
->setResultCacheLifetime(3500);
$this->assertSame($q, $q2);
}
public function testJoinedOneToManyNativeQueryWithRSMBuilder()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$phone = new CmsPhonenumber;
$phone->phonenumber = 424242;
$user->addPhonenumber($phone);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers');
$query = $this->_em->createNativeQuery('SELECT u.*, p.* FROM cms_users u LEFT JOIN cms_phonenumbers p ON u.id = p.user_id WHERE username = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals('Roman', $users[0]->name);
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers());
$this->assertTrue($users[0]->getPhonenumbers()->isInitialized());
$this->assertEquals(1, count($users[0]->getPhonenumbers()));
$phones = $users[0]->getPhonenumbers();
$this->assertEquals(424242, $phones[0]->phonenumber);
$this->assertTrue($phones[0]->getUser() === $users[0]);
$this->_em->clear();
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p');
$query = $this->_em->createNativeQuery('SELECT p.* FROM cms_phonenumbers p WHERE p.phonenumber = ?', $rsm);
$query->setParameter(1, $phone->phonenumber);
$phone = $query->getSingleResult();
$this->assertNotNull($phone->getUser());
$this->assertEquals($user->name, $phone->getUser()->getName());
}
public function testJoinedOneToOneNativeQueryWithRSMBuilder()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$addr = new CmsAddress;
$addr->country = 'germany';
$addr->zip = 10827;
$addr->city = 'Berlin';
$user->setAddress($addr);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address', array('id' => 'a_id'));
$query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals('Roman', $users[0]->name);
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers());
$this->assertFalse($users[0]->getPhonenumbers()->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $users[0]->getAddress());
$this->assertTrue($users[0]->getAddress()->getUser() == $users[0]);
$this->assertEquals('germany', $users[0]->getAddress()->getCountry());
$this->assertEquals(10827, $users[0]->getAddress()->getZipCode());
$this->assertEquals('Berlin', $users[0]->getAddress()->getCity());
$this->_em->clear();
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a');
$query = $this->_em->createNativeQuery('SELECT a.* FROM cms_addresses a WHERE a.id = ?', $rsm);
$query->setParameter(1, $addr->getId());
$address = $query->getSingleResult();
$this->assertNotNull($address->getUser());
$this->assertEquals($user->name, $address->getUser()->getName());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRSMBuilderThrowsExceptionOnColumnConflict()
{
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address');
}
/**
* @group PR-39
*/
public function testUnknownParentAliasThrowsException()
{
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u');
$rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'un', 'address', array('id' => 'a_id'));
$query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm);
$query->setParameter(1, 'romanb');
$this->setExpectedException(
"Doctrine\ORM\Internal\Hydration\HydrationException",
"The parent object of entity result with alias 'a' was not found. The parent alias is 'un'."
);
$users = $query->getResult();
}
}

View File

@@ -0,0 +1,173 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Collections\ArrayCollection,
Doctrine\Common\NotifyPropertyChanged,
Doctrine\Common\PropertyChangedListener;
require_once __DIR__ . '/../../TestInit.php';
/**
* NativeQueryTest
*
* @author robo
*/
class NotifyPolicyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\NotifyUser'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\NotifyGroup')
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
public function testChangeTracking()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$user = new NotifyUser();
$group = new NotifyGroup();
$user->setName('roman');
$group->setName('dev');
$user->getGroups()->add($group);
$group->getUsers()->add($user);
$this->_em->persist($user);
$this->_em->persist($group);
$this->assertEquals(1, count($user->listeners));
$this->assertEquals(1, count($group->listeners));
$this->_em->flush();
$this->_em->clear();
$this->assertEquals(1, count($user->listeners));
$this->assertEquals(1, count($group->listeners));
$userId = $user->getId();
$groupId = $group->getId();
unset($user, $group);
$user = $this->_em->find(__NAMESPACE__.'\NotifyUser', $userId);
$this->assertEquals(1, $user->getGroups()->count());
$group = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $groupId);
$this->assertEquals(1, $group->getUsers()->count());
$this->assertEquals(1, count($user->listeners));
$this->assertEquals(1, count($group->listeners));
$group2 = new NotifyGroup();
$group2->setName('nerds');
$this->_em->persist($group2);
$user->getGroups()->add($group2);
$group2->getUsers()->add($user);
$group->setName('geeks');
$this->_em->flush();
$this->_em->clear();
$this->assertEquals(1, count($user->listeners));
$this->assertEquals(1, count($group->listeners));
$group2Id = $group2->getId();
unset($group2, $user);
$user = $this->_em->find(__NAMESPACE__.'\NotifyUser', $userId);
$this->assertEquals(2, $user->getGroups()->count());
$group2 = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $group2Id);
$this->assertEquals(1, $group2->getUsers()->count());
$group = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $groupId);
$this->assertEquals(1, $group->getUsers()->count());
$this->assertEquals('geeks', $group->getName());
}
}
class NotifyBaseEntity implements NotifyPropertyChanged {
public $listeners = array();
public function addPropertyChangedListener(PropertyChangedListener $listener) {
$this->listeners[] = $listener;
}
protected function onPropertyChanged($propName, $oldValue, $newValue) {
if ($this->listeners) {
foreach ($this->listeners as $listener) {
$listener->propertyChanged($this, $propName, $oldValue, $newValue);
}
}
}
}
/** @Entity @ChangeTrackingPolicy("NOTIFY") */
class NotifyUser extends NotifyBaseEntity {
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column */
private $name;
/** @ManyToMany(targetEntity="NotifyGroup") */
private $groups;
function __construct() {
$this->groups = new ArrayCollection;
}
function getId() {
return $this->id;
}
function getName() {
return $this->name;
}
function setName($name) {
$this->onPropertyChanged('name', $this->name, $name);
$this->name = $name;
}
function getGroups() {
return $this->groups;
}
}
/** @Entity */
class NotifyGroup extends NotifyBaseEntity {
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column */
private $name;
/** @ManyToMany(targetEntity="NotifyUser", mappedBy="groups") */
private $users;
function __construct() {
$this->users = new ArrayCollection;
}
function getId() {
return $this->id;
}
function getName() {
return $this->name;
}
function setName($name) {
$this->onPropertyChanged('name', $this->name, $name);
$this->name = $name;
}
function getUsers() {
return $this->users;
}
}

View File

@@ -0,0 +1,171 @@
<?php
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';
/**
* Tests a bidirectional one-to-one association mapping (without inheritance).
*/
class OneToManyBidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $product;
private $firstFeature;
private $secondFeature;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->product = new ECommerceProduct();
$this->product->setName('Doctrine Cookbook');
$this->firstFeature = new ECommerceFeature();
$this->firstFeature->setDescription('Model writing tutorial');
$this->secondFeature = new ECommerceFeature();
$this->secondFeature->setDescription('Annotations examples');
}
public function testSavesAOneToManyAssociationWithCascadeSaveSet() {
$this->product->addFeature($this->firstFeature);
$this->product->addFeature($this->secondFeature);
$this->_em->persist($this->product);
$this->_em->flush();
$this->assertFeatureForeignKeyIs($this->product->getId(), $this->firstFeature);
$this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature);
}
public function testSavesAnEmptyCollection()
{
$this->_em->persist($this->product);
$this->_em->flush();
$this->assertEquals(0, count($this->product->getFeatures()));
}
public function testDoesNotSaveAnInverseSideSet() {
$this->product->brokenAddFeature($this->firstFeature);
$this->_em->persist($this->product);
$this->_em->flush();
$this->assertFeatureForeignKeyIs(null, $this->firstFeature);
}
public function testRemovesOneToOneAssociation()
{
$this->product->addFeature($this->firstFeature);
$this->product->addFeature($this->secondFeature);
$this->_em->persist($this->product);
$this->product->removeFeature($this->firstFeature);
$this->_em->flush();
$this->assertFeatureForeignKeyIs(null, $this->firstFeature);
$this->assertFeatureForeignKeyIs($this->product->getId(), $this->secondFeature);
}
public function testEagerLoadsOneToManyAssociation()
{
$this->_createFixture();
$query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\ECommerce\ECommerceProduct p join p.features f');
$result = $query->getResult();
$product = $result[0];
$features = $product->getFeatures();
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[0]);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $features[0]->getProduct());
$this->assertSame($product, $features[0]->getProduct());
$this->assertEquals('Model writing tutorial', $features[0]->getDescription());
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[1]);
$this->assertSame($product, $features[1]->getProduct());
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $features[1]->getProduct());
$this->assertEquals('Annotations examples', $features[1]->getDescription());
}
public function testLazyLoadsObjectsOnTheOwningSide()
{
$this->_createFixture();
$query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$result = $query->getResult();
$product = $result[0];
$features = $product->getFeatures();
$this->assertFalse($features->isInitialized());
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[0]);
$this->assertTrue($features->isInitialized());
$this->assertSame($product, $features[0]->getProduct());
$this->assertEquals('Model writing tutorial', $features[0]->getDescription());
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[1]);
$this->assertSame($product, $features[1]->getProduct());
$this->assertEquals('Annotations examples', $features[1]->getDescription());
}
public function testLazyLoadsObjectsOnTheInverseSide()
{
$this->_createFixture();
$query = $this->_em->createQuery('select f from Doctrine\Tests\Models\ECommerce\ECommerceFeature f');
$features = $query->getResult();
$product = $features[0]->getProduct();
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $product);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $product);
$this->assertFalse($product->__isInitialized__);
$this->assertSame('Doctrine Cookbook', $product->getName());
$this->assertTrue($product->__isInitialized__);
}
public function testLazyLoadsObjectsOnTheInverseSide2()
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_createFixture();
$query = $this->_em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p');
$features = $query->getResult();
$product = $features[0]->getProduct();
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $product);
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $product);
$this->assertSame('Doctrine Cookbook', $product->getName());
$this->assertFalse($product->getFeatures()->isInitialized());
// This would trigger lazy-load
//$this->assertEquals(2, $product->getFeatures()->count());
//$this->assertTrue($product->getFeatures()->contains($features[0]));
//$this->assertTrue($product->getFeatures()->contains($features[1]));
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(null);
}
public function testJoinFromOwningSide()
{
$query = $this->_em->createQuery('select f,p from Doctrine\Tests\Models\ECommerce\ECommerceFeature f join f.product p');
$features = $query->getResult();
$this->assertEquals(0, count($features));
}
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()->executeQuery(
'SELECT product_id FROM ecommerce_features WHERE id=?',
array($feature->getId())
)->fetchColumn();
$this->assertEquals($value, $foreignKey);
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\Tests\Models\CMS\CmsAddress,
Doctrine\Tests\Models\CMS\CmsPhonenumber;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional one-to-many association mapping with orphan removal.
*/
class OneToManyOrphanRemovalTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected $userId;
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$phone = new CmsPhonenumber;
$phone->phonenumber = '123456';
$user->addPhonenumber($phone);
$this->_em->persist($user);
$this->_em->flush();
$this->userId = $user->getId();
$this->_em->clear();
}
public function testOrphanRemoval()
{
$userProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$this->_em->remove($userProxy);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsUser should be removed by EntityManager');
$query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval');
}
/**
* @group DDC-1496
*/
public function testOrphanRemovalUnitializedCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId);
$user->phonenumbers->clear();
$this->_em->flush();
$query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsPhonenumber should be removed by orphanRemoval');
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCategory;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional one-to-one association mapping (without inheritance).
*/
class OneToManySelfReferentialAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $parent;
private $firstChild;
private $secondChild;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->parent = new ECommerceCategory();
$this->parent->setName('Programming languages books');
$this->firstChild = new ECommerceCategory();
$this->firstChild->setName('Java books');
$this->secondChild = new ECommerceCategory();
$this->secondChild->setName('Php books');
}
public function testSavesAOneToManyAssociationWithCascadeSaveSet() {
$this->parent->addChild($this->firstChild);
$this->parent->addChild($this->secondChild);
$this->_em->persist($this->parent);
$this->_em->flush();
$this->assertForeignKeyIs($this->parent->getId(), $this->firstChild);
$this->assertForeignKeyIs($this->parent->getId(), $this->secondChild);
}
public function testSavesAnEmptyCollection()
{
$this->_em->persist($this->parent);
$this->_em->flush();
$this->assertEquals(0, count($this->parent->getChildren()));
}
public function testDoesNotSaveAnInverseSideSet() {
$this->parent->brokenAddChild($this->firstChild);
$this->_em->persist($this->parent);
$this->_em->flush();
$this->assertForeignKeyIs(null, $this->firstChild);
}
public function testRemovesOneToManyAssociation()
{
$this->parent->addChild($this->firstChild);
$this->parent->addChild($this->secondChild);
$this->_em->persist($this->parent);
$this->parent->removeChild($this->firstChild);
$this->_em->flush();
$this->assertForeignKeyIs(null, $this->firstChild);
$this->assertForeignKeyIs($this->parent->getId(), $this->secondChild);
}
public function testEagerLoadsOneToManyAssociation()
{
$this->_createFixture();
$query = $this->_em->createQuery('select c1, c2 from Doctrine\Tests\Models\ECommerce\ECommerceCategory c1 join c1.children c2');
$result = $query->getResult();
$this->assertEquals(1, count($result));
$parent = $result[0];
$children = $parent->getChildren();
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[0]);
$this->assertSame($parent, $children[0]->getParent());
$this->assertEquals(' books', strstr($children[0]->getName(), ' books'));
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[1]);
$this->assertSame($parent, $children[1]->getParent());
$this->assertEquals(' books', strstr($children[1]->getName(), ' books'));
}
public function testLazyLoadsOneToManyAssociation()
{
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCategory');
$metadata->associationMappings['children']['fetch'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc');
$result = $query->getResult();
$parent = $result[0];
$children = $parent->getChildren();
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[0]);
$this->assertSame($parent, $children[0]->getParent());
$this->assertEquals(' books', strstr($children[0]->getName(), ' books'));
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[1]);
$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()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', array($child->getId()))->fetchColumn();
$this->assertEquals($value, $foreignKey);
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\Routing\RoutingRoute;
use Doctrine\Tests\Models\Routing\RoutingLocation;
use Doctrine\Tests\Models\Routing\RoutingLeg;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional one-to-one association mapping (without inheritance).
*/
class OneToManyUnidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected $locations = array();
public function setUp()
{
$this->useModelSet('routing');
parent::setUp();
$locations = array("Berlin", "Bonn", "Brasilia", "Atlanta");
foreach ($locations AS $locationName) {
$location = new RoutingLocation();
$location->name = $locationName;
$this->_em->persist($location);
$this->locations[$locationName] = $location;
}
$this->_em->flush();
}
public function testPersistOwning_InverseCascade()
{
$leg = new RoutingLeg();
$leg->fromLocation = $this->locations['Berlin'];
$leg->toLocation = $this->locations['Bonn'];
$leg->departureDate = new \DateTime("now");
$leg->arrivalDate = new \DateTime("now +5 hours");
$route = new RoutingRoute();
$route->legs[] = $leg;
$this->_em->persist($route);
$this->_em->flush();
$this->_em->clear();
$routes = $this->_em->createQuery(
"SELECT r, l, f, t FROM Doctrine\Tests\Models\Routing\RoutingRoute r ".
"JOIN r.legs l JOIN l.fromLocation f JOIN l.toLocation t"
)->getSingleResult();
$this->assertEquals(1, count($routes->legs));
$this->assertEquals("Berlin", $routes->legs[0]->fromLocation->name);
$this->assertEquals("Bonn", $routes->legs[0]->toLocation->name);
}
public function testLegsAreUniqueToRoutes()
{
$leg = new RoutingLeg();
$leg->fromLocation = $this->locations['Berlin'];
$leg->toLocation = $this->locations['Bonn'];
$leg->departureDate = new \DateTime("now");
$leg->arrivalDate = new \DateTime("now +5 hours");
$routeA = new RoutingRoute();
$routeA->legs[] = $leg;
$routeB = new RoutingRoute();
$routeB->legs[] = $leg;
$this->_em->persist($routeA);
$this->_em->persist($routeB);
$exceptionThrown = false;
try {
// exception depending on the underyling Database Driver
$this->_em->flush();
} catch(\Exception $e) {
$exceptionThrown = true;
}
$this->assertTrue($exceptionThrown, "The underlying database driver throws an exception.");
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
use Doctrine\Tests\Models\ECommerce\ECommerceCustomer;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional one-to-one association mapping (without inheritance).
*/
class OneToOneBidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $customer;
private $cart;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->customer = new ECommerceCustomer();
$this->customer->setName('John Doe');
$this->cart = new ECommerceCart();
$this->cart->setPayment('Credit card');
}
public function testSavesAOneToOneAssociationWithCascadeSaveSet() {
$this->customer->setCart($this->cart);
$this->_em->persist($this->customer);
$this->_em->flush();
$this->assertCartForeignKeyIs($this->customer->getId());
}
public function testDoesNotSaveAnInverseSideSet() {
$this->customer->brokenSetCart($this->cart);
$this->_em->persist($this->customer);
$this->_em->flush();
$this->assertCartForeignKeyIs(null);
}
public function testRemovesOneToOneAssociation()
{
$this->customer->setCart($this->cart);
$this->_em->persist($this->customer);
$this->customer->removeCart();
$this->_em->flush();
$this->assertCartForeignKeyIs(null);
}
public function testEagerLoad()
{
$this->_createFixture();
$query = $this->_em->createQuery('select c, ca from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c join c.cart ca');
$result = $query->getResult();
$customer = $result[0];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $customer->getCart());
$this->assertEquals('paypal', $customer->getCart()->getPayment());
}
public function testLazyLoadsObjectsOnTheOwningSide() {
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart');
$metadata->associationMappings['customer']['fetchMode'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCart c');
$result = $query->getResult();
$cart = $result[0];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart->getCustomer());
$this->assertEquals('Giorgio', $cart->getCustomer()->getName());
}
public function testInverseSideIsNeverLazy()
{
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCustomer');
$metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_EAGER;
$query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c');
$result = $query->getResult();
$customer = $result[0];
$this->assertNull($customer->getMentor());
$this->assertInstanceOF('Doctrine\Tests\Models\ECommerce\ECommerceCart', $customer->getCart());
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $customer->getCart());
$this->assertEquals('paypal', $customer->getCart()->getPayment());
}
public function testUpdateWithProxyObject()
{
$cust = new ECommerceCustomer;
$cust->setName('Roman');
$cart = new ECommerceCart;
$cart->setPayment('CARD');
$cust->setCart($cart);
$this->_em->persist($cust);
$this->_em->flush();
$this->_em->clear();
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $cust->getCart());
$this->assertEquals('Roman', $cust->getName());
$this->assertSame($cust, $cart->getCustomer());
$query = $this->_em->createQuery('select ca from Doctrine\Tests\Models\ECommerce\ECommerceCart ca where ca.id =?1');
$query->setParameter(1, $cart->getId());
$cart2 = $query->getSingleResult();
$cart2->setPayment('CHEQUE');
$this->_em->flush();
$this->_em->clear();
$query2 = $this->_em->createQuery('select ca, c from Doctrine\Tests\Models\ECommerce\ECommerceCart ca left join ca.customer c where ca.id =?1');
$query2->setParameter(1, $cart->getId());
$cart3 = $query2->getSingleResult();
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart3->getCustomer());
$this->assertEquals('Roman', $cart3->getCustomer()->getName());
}
protected function _createFixture()
{
$customer = new ECommerceCustomer;
$customer->setName('Giorgio');
$cart = new ECommerceCart;
$cart->setPayment('paypal');
$customer->setCart($cart);
$this->_em->persist($customer);
$this->_em->flush();
$this->_em->clear();
}
public function assertCartForeignKeyIs($value) {
$foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', array($this->cart->getId()))->fetchColumn();
$this->assertEquals($value, $foreignKey);
}
}

View File

@@ -0,0 +1,307 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../TestInit.php';
/**
* @group DDC-952
*/
class OneToOneEagerLoadingTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
$schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->_em);
try {
$schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Train'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\TrainDriver'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\TrainOwner'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Waggon'),
));
} catch(\Exception $e) {}
}
public function testEagerLoadOneToOneOwningSide()
{
$train = new Train(new TrainOwner("Alexander"));
$driver = new TrainDriver("Benjamin");
$waggon = new Waggon();
$train->setDriver($driver);
$train->addWaggon($waggon);
$this->_em->persist($train); // cascades
$this->_em->flush();
$this->_em->clear();
$sqlCount = count($this->_sqlLoggerStack->queries);
$train = $this->_em->find(get_class($train), $train->id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $train->driver);
$this->assertEquals("Benjamin", $train->driver->name);
$this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries));
}
public function testEagerLoadOneToOneNullOwningSide()
{
$train = new Train(new TrainOwner("Alexander"));
$this->_em->persist($train); // cascades
$this->_em->flush();
$this->_em->clear();
$sqlCount = count($this->_sqlLoggerStack->queries);
$train = $this->_em->find(get_class($train), $train->id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $train->driver);
$this->assertNull($train->driver);
$this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries));
}
public function testEagerLoadOneToOneInverseSide()
{
$owner = new TrainOwner("Alexander");
$train = new Train($owner);
$this->_em->persist($train); // cascades
$this->_em->flush();
$this->_em->clear();
$sqlCount = count($this->_sqlLoggerStack->queries);
$driver = $this->_em->find(get_class($owner), $owner->id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $owner->train);
$this->assertNotNull($owner->train);
$this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries));
}
public function testEagerLoadOneToOneNullInverseSide()
{
$driver = new TrainDriver("Dagny Taggert");
$this->_em->persist($driver);
$this->_em->flush();
$this->_em->clear();
$this->assertNull($driver->train);
$sqlCount = count($this->_sqlLoggerStack->queries);
$driver = $this->_em->find(get_class($driver), $driver->id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $driver->train);
$this->assertNull($driver->train);
$this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries));
}
public function testEagerLoadManyToOne()
{
$train = new Train(new TrainOwner("Alexander"));
$waggon = new Waggon();
$train->addWaggon($waggon);
$this->_em->persist($train); // cascades
$this->_em->flush();
$this->_em->clear();
$waggon = $this->_em->find(get_class($waggon), $waggon->id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $waggon->train);
$this->assertNotNull($waggon->train);
}
public function testEagerLoadWithNullableColumnsGeneratesLeftJoinOnBothSides()
{
$train = new Train(new TrainOwner("Alexander"));
$driver = new TrainDriver("Benjamin");
$train->setDriver($driver);
$this->_em->persist($train);
$this->_em->flush();
$this->_em->clear();
$train = $this->_em->find(get_class($train), $train->id);
$this->assertSQLEquals(
"SELECT t0.id AS id1, t0.driver_id AS driver_id2, t3.id AS id4, t3.name AS name5, t0.owner_id AS owner_id6, t7.id AS id8, t7.name AS name9 FROM Train t0 LEFT JOIN TrainDriver t3 ON t0.driver_id = t3.id INNER JOIN TrainOwner t7 ON t0.owner_id = t7.id WHERE t0.id = ?",
$this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql']
);
$this->_em->clear();
$driver = $this->_em->find(get_class($driver), $driver->id);
$this->assertSQLEquals(
"SELECT t0.id AS id1, t0.name AS name2, t3.id AS id4, t3.driver_id AS driver_id5, t3.owner_id AS owner_id6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id IN (?)",
$this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql']
);
}
public function testEagerLoadWithNonNullableColumnsGeneratesInnerJoinOnOwningSide()
{
$waggon = new Waggon();
// It should have a train
$train = new Train(new TrainOwner("Alexander"));
$train->addWaggon($waggon);
$this->_em->persist($train);
$this->_em->flush();
$this->_em->clear();
$waggon = $this->_em->find(get_class($waggon), $waggon->id);
// The last query is the eager loading of the owner of the train
$this->assertSQLEquals(
"SELECT t0.id AS id1, t0.name AS name2, t3.id AS id4, t3.driver_id AS driver_id5, t3.owner_id AS owner_id6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id IN (?)",
$this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql']
);
// The one before is the fetching of the waggon and train
$this->assertSQLEquals(
"SELECT t0.id AS id1, t0.train_id AS train_id2, t3.id AS id4, t3.driver_id AS driver_id5, t3.owner_id AS owner_id6 FROM Waggon t0 INNER JOIN Train t3 ON t0.train_id = t3.id WHERE t0.id = ?",
$this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery - 1]['sql']
);
}
public function testEagerLoadWithNonNullableColumnsGeneratesLeftJoinOnNonOwningSide()
{
$owner = new TrainOwner('Alexander');
$train = new Train($owner);
$this->_em->persist($train);
$this->_em->flush();
$this->_em->clear();
$waggon = $this->_em->find(get_class($owner), $owner->id);
$this->assertSQLEquals(
"SELECT t0.id AS id1, t0.name AS name2, t3.id AS id4, t3.driver_id AS driver_id5, t3.owner_id AS owner_id6 FROM TrainOwner t0 LEFT JOIN Train t3 ON t3.owner_id = t0.id WHERE t0.id = ?",
$this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql']
);
}
}
/**
* @Entity
*/
class Train
{
/**
* @id @column(type="integer") @generatedValue
* @var int
*/
public $id;
/**
* Owning side
* @OneToOne(targetEntity="TrainDriver", inversedBy="train", fetch="EAGER", cascade={"persist"})
* @JoinColumn(nullable=true)
*/
public $driver;
/**
* Owning side
* @OneToOne(targetEntity="TrainOwner", inversedBy="train", fetch="EAGER", cascade={"persist"})
* @JoinColumn(nullable=false)
*/
public $owner;
/**
* @oneToMany(targetEntity="Waggon", mappedBy="train", cascade={"persist"})
*/
public $waggons;
public function __construct(TrainOwner $owner)
{
$this->waggons = new \Doctrine\Common\Collections\ArrayCollection();
$this->setOwner($owner);
}
public function setDriver(TrainDriver $driver)
{
$this->driver = $driver;
$driver->setTrain($this);
}
public function setOwner(TrainOwner $owner)
{
$this->owner = $owner;
$owner->setTrain($this);
}
public function addWaggon(Waggon $w)
{
$w->setTrain($this);
$this->waggons[] = $w;
}
}
/**
* @Entity
*/
class TrainDriver
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/** @column(type="string") */
public $name;
/**
* Inverse side
* @OneToOne(targetEntity="Train", mappedBy="driver", fetch="EAGER")
*/
public $train;
public function __construct($name)
{
$this->name = $name;
}
public function setTrain(Train $t)
{
$this->train = $t;
}
}
/**
* @Entity
*/
class TrainOwner
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/** @column(type="string") */
public $name;
/**
* Inverse side
* @OneToOne(targetEntity="Train", mappedBy="owner", fetch="EAGER")
*/
public $train;
public function __construct($name)
{
$this->name = $name;
}
public function setTrain(Train $t)
{
$this->train = $t;
}
}
/**
* @Entity
*/
class Waggon
{
/** @id @generatedValue @column(type="integer") */
public $id;
/**
* @ManyToOne(targetEntity="Train", inversedBy="waggons", fetch="EAGER")
* @JoinColumn(nullable=false)
*/
public $train;
public function setTrain($train)
{
$this->train = $train;
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\Tests\Models\CMS\CmsEmail,
Doctrine\Tests\Models\CMS\CmsAddress,
Doctrine\Tests\Models\CMS\CmsPhonenumber;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a bidirectional one-to-one association mapping with orphan removal.
*/
class OneToOneOrphanRemovalTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testOrphanRemoval()
{
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'romanb';
$user->name = 'Roman B.';
$address = new CmsAddress;
$address->country = 'de';
$address->zip = 1234;
$address->city = 'Berlin';
$user->setAddress($address);
$this->_em->persist($user);
$this->_em->flush();
$userId = $user->getId();
$this->_em->clear();
$userProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $userId);
$this->_em->remove($userProxy);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsUser should be removed by EntityManager');
$query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsAddress should be removed by orphanRemoval');
}
public function testOrphanRemovalWhenUnlink()
{
$user = new CmsUser;
$user->status = 'dev';
$user->username = 'beberlei';
$user->name = 'Bejamin Eberlei';
$email = new CmsEmail;
$email->email = 'beberlei@domain.com';
$user->setEmail($email);
$this->_em->persist($user);
$this->_em->flush();
$userId = $user->getId();
$this->_em->clear();
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId);
$user->setEmail(null);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('SELECT e FROM Doctrine\Tests\Models\CMS\CmsEmail e');
$result = $query->getResult();
$this->assertEquals(0, count($result), 'CmsEmail should be removed by orphanRemoval');
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCustomer;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a self referential one-to-one association mapping (without inheritance).
* Relation is defined as the mentor that a customer choose. The mentor could
* help only one other customer, while a customer can choose only one mentor
* for receiving support.
* Inverse side is not present.
*/
class OneToOneSelfReferentialAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $customer;
private $mentor;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->customer = new ECommerceCustomer();
$this->customer->setName('Anakin Skywalker');
$this->mentor = new ECommerceCustomer();
$this->mentor->setName('Obi-wan Kenobi');
}
public function testSavesAOneToOneAssociationWithCascadeSaveSet() {
$this->customer->setMentor($this->mentor);
$this->_em->persist($this->customer);
$this->_em->flush();
$this->assertForeignKeyIs($this->mentor->getId());
}
public function testRemovesOneToOneAssociation()
{
$this->customer->setMentor($this->mentor);
$this->_em->persist($this->customer);
$this->customer->removeMentor();
$this->_em->flush();
$this->assertForeignKeyIs(null);
}
public function testFind()
{
$id = $this->_createFixture();
$customer = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $id);
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $customer->getMentor());
}
public function testEagerLoadsAssociation()
{
$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->getResult();
$customer = $result[0];
$this->assertLoadingOfAssociation($customer);
}
/**
* @group mine
* @return unknown_type
*/
public function testLazyLoadsAssociation()
{
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCustomer');
$metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery("select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c where c.name='Luke Skywalker'");
$result = $query->getResult();
$customer = $result[0];
$this->assertLoadingOfAssociation($customer);
}
public function testMultiSelfReference()
{
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\MultiSelfReference')
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
$entity1 = new MultiSelfReference();
$this->_em->persist($entity1);
$entity1->setOther1($entity2 = new MultiSelfReference);
$entity1->setOther2($entity3 = new MultiSelfReference);
$this->_em->flush();
$this->_em->clear();
$entity2 = $this->_em->find(get_class($entity1), $entity1->getId());
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\MultiSelfReference', $entity2->getOther1());
$this->assertInstanceOf('Doctrine\Tests\ORM\Functional\MultiSelfReference', $entity2->getOther2());
$this->assertNull($entity2->getOther1()->getOther1());
$this->assertNull($entity2->getOther1()->getOther2());
$this->assertNull($entity2->getOther2()->getOther1());
$this->assertNull($entity2->getOther2()->getOther2());
}
public function assertLoadingOfAssociation($customer)
{
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $customer->getMentor());
$this->assertEquals('Obi-wan Kenobi', $customer->getMentor()->getName());
}
public function assertForeignKeyIs($value) {
$foreignKey = $this->_em->getConnection()->executeQuery('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();
return $customer->getId();
}
}
/**
* @Entity
*/
class MultiSelfReference {
/** @Id @GeneratedValue(strategy="AUTO") @Column(type="integer") */
private $id;
/**
* @OneToOne(targetEntity="MultiSelfReference", cascade={"persist"})
* @JoinColumn(name="other1", referencedColumnName="id")
*/
private $other1;
/**
* @OneToOne(targetEntity="MultiSelfReference", cascade={"persist"})
* @JoinColumn(name="other2", referencedColumnName="id")
*/
private $other2;
public function getId() {return $this->id;}
public function setOther1($other1) {$this->other1 = $other1;}
public function getOther1() {return $this->other1;}
public function setOther2($other2) {$this->other2 = $other2;}
public function getOther2() {return $this->other2;}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceShipping;
use Doctrine\ORM\Mapping\AssociationMapping;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests a unidirectional one-to-one association mapping (without inheritance).
* Inverse side is not present.
*/
class OneToOneUnidirectionalAssociationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $product;
private $shipping;
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->product = new ECommerceProduct();
$this->product->setName('Doctrine 2 Manual');
$this->shipping = new ECommerceShipping();
$this->shipping->setDays('5');
}
public function testSavesAOneToOneAssociationWithCascadeSaveSet() {
$this->product->setShipping($this->shipping);
$this->_em->persist($this->product);
$this->_em->flush();
$this->assertForeignKeyIs($this->shipping->getId());
}
public function testRemovesOneToOneAssociation()
{
$this->product->setShipping($this->shipping);
$this->_em->persist($this->product);
$this->product->removeShipping();
$this->_em->flush();
$this->assertForeignKeyIs(null);
}
public function _testEagerLoad()
{
$this->_createFixture();
$query = $this->_em->createQuery('select p, s from Doctrine\Tests\Models\ECommerce\ECommerceProduct p left join p.shipping s');
$result = $query->getResult();
$product = $result[0];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceShipping', $product->getShipping());
$this->assertEquals(1, $product->getShipping()->getDays());
}
public function testLazyLoadsObjects() {
$this->_createFixture();
$metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct');
$metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY;
$query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$result = $query->getResult();
$product = $result[0];
$this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceShipping', $product->getShipping());
$this->assertEquals(1, $product->getShipping()->getDays());
}
public function testDoesNotLazyLoadObjectsIfConfigurationDoesNotAllowIt() {
$this->_createFixture();
$query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p');
$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$result = $query->getResult();
$product = $result[0];
$this->assertNull($product->getShipping());
}
protected function _createFixture()
{
$product = new ECommerceProduct;
$product->setName('Php manual');
$shipping = new ECommerceShipping;
$shipping->setDays('1');
$product->setShipping($shipping);
$this->_em->persist($product);
$this->_em->flush();
$this->_em->clear();
}
public function assertForeignKeyIs($value) {
$foreignKey = $this->_em->getConnection()->executeQuery(
'SELECT shipping_id FROM ecommerce_products WHERE id=?',
array($this->product->getId())
)->fetchColumn();
$this->assertEquals($value, $foreignKey);
}
/**
* @group DDC-762
*/
public function testNullForeignKey()
{
$product = new ECommerceProduct();
$product->setName('Doctrine 2 Manual');
$this->_em->persist($product);
$this->_em->flush();
$product = $this->_em->find(get_class($product), $product->getId());
$this->assertNull($product->getShipping());
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\Routing\RoutingRoute;
use Doctrine\Tests\Models\Routing\RoutingLocation;
use Doctrine\Tests\Models\Routing\RoutingLeg;
use Doctrine\Tests\Models\Routing\RoutingRouteBooking;
require_once __DIR__ . '/../../TestInit.php';
class OrderedCollectionTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected $locations = array();
public function setUp()
{
$this->useModelSet('routing');
parent::setUp();
$locations = array("Berlin", "Bonn", "Brasilia", "Atlanta");
foreach ($locations AS $locationName) {
$location = new RoutingLocation();
$location->name = $locationName;
$this->_em->persist($location);
$this->locations[$locationName] = $location;
}
$this->_em->flush();
}
public function createPersistedRouteWithLegs()
{
$route = new RoutingRoute();
$leg1 = new RoutingLeg();
$leg1->fromLocation = $this->locations['Berlin'];
$leg1->toLocation = $this->locations['Bonn'];
$leg1->departureDate = new \DateTime("now");
$leg1->arrivalDate = new \DateTime("now +5 hours");
$leg2 = new RoutingLeg();
$leg2->fromLocation = $this->locations['Bonn'];
$leg2->toLocation = $this->locations['Brasilia'];
$leg2->departureDate = new \DateTime("now +6 hours");
$leg2->arrivalDate = new \DateTime("now +24 hours");
$route->legs[] = $leg2;
$route->legs[] = $leg1;
$this->_em->persist($route);
$this->_em->flush();
$routeId = $route->id;
$this->_em->clear();
return $routeId;
}
public function testLazyManyToManyCollection_IsRetrievedWithOrderByClause()
{
$routeId = $this->createPersistedRouteWithLegs();
$route = $this->_em->find('Doctrine\Tests\Models\Routing\RoutingRoute', $routeId);
$this->assertEquals(2, count($route->legs));
$this->assertEquals("Berlin", $route->legs[0]->fromLocation->getName());
$this->assertEquals("Bonn", $route->legs[1]->fromLocation->getName());
}
public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause()
{
$route = new RoutingRoute();
$this->_em->persist($route);
$this->_em->flush();
$routeId = $route->id;
$booking1 = new RoutingRouteBooking();
$booking1->passengerName = "Guilherme";
$booking2 = new RoutingRouteBooking();
$booking2->passengerName = "Benjamin";
$route->bookings[] = $booking1;
$booking1->route = $route;
$route->bookings[] = $booking2;
$booking2->route = $route;
$this->_em->persist($booking1);
$this->_em->persist($booking2);
$this->_em->flush();
$this->_em->clear();
$route = $this->_em->find('Doctrine\Tests\Models\Routing\RoutingRoute', $routeId);
$this->assertEquals(2, count($route->bookings));
$this->assertEquals('Benjamin', $route->bookings[0]->getPassengerName());
$this->assertEquals('Guilherme', $route->bookings[1]->getPassengerName());
}
public function testOrderedResultFromDqlQuery()
{
$routeId = $this->createPersistedRouteWithLegs();
$route = $this->_em->createQuery("SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l WHERE r.id = ?1")
->setParameter(1, $routeId)
->getSingleResult();
$this->assertEquals(2, count($route->legs));
$this->assertEquals("Berlin", $route->legs[0]->fromLocation->getName());
$this->assertEquals("Bonn", $route->legs[1]->fromLocation->getName());
}
}

View File

@@ -0,0 +1,133 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional tests for the Single Table Inheritance mapping strategy.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class OrderedJoinedTableInheritanceCollectionTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Pet'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Cat'),
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Dog'),
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
$dog = new OJTIC_Dog();
$dog->name = "Poofy";
$dog1 = new OJTIC_Dog();
$dog1->name = "Zampa";
$dog2 = new OJTIC_Dog();
$dog2->name = "Aari";
$dog1->mother = $dog;
$dog2->mother = $dog;
$dog->children[] = $dog1;
$dog->children[] = $dog2;
$this->_em->persist($dog);
$this->_em->persist($dog1);
$this->_em->persist($dog2);
$this->_em->flush();
$this->_em->clear();
}
public function testOrderdOneToManyCollection()
{
$poofy = $this->_em->createQuery("SELECT p FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p WHERE p.name = 'Poofy'")->getSingleResult();
$this->assertEquals('Aari', $poofy->children[0]->getName());
$this->assertEquals('Zampa', $poofy->children[1]->getName());
$this->_em->clear();
$result = $this->_em->createQuery(
"SELECT p, c FROM Doctrine\Tests\ORM\Functional\OJTIC_Pet p JOIN p.children c WHERE p.name = 'Poofy'")
->getResult();
$this->assertEquals(1, count($result));
$poofy = $result[0];
$this->assertEquals('Aari', $poofy->children[0]->getName());
$this->assertEquals('Zampa', $poofy->children[1]->getName());
}
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({
* "cat" = "OJTIC_Cat",
* "dog" = "OJTIC_Dog"})
*/
abstract class OJTIC_Pet
{
/**
* @Id
* @column(type="integer")
* @generatedValue(strategy="AUTO")
*/
public $id;
/**
*
* @Column
*/
public $name;
/**
* @ManyToOne(targetEntity="OJTIC_PET")
*/
public $mother;
/**
* @OneToMany(targetEntity="OJTIC_Pet", mappedBy="mother")
* @OrderBy({"name" = "ASC"})
*/
public $children;
/**
* @ManyToMany(targetEntity="OJTIC_Pet")
* @JoinTable(name="OTJIC_Pet_Friends",
* joinColumns={@JoinColumn(name="pet_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="friend_id", referencedColumnName="id")})
* @OrderBy({"name" = "ASC"})
*/
public $friends;
public function getName()
{
return $this->name;
}
}
/**
* @Entity
*/
class OJTIC_Cat extends OJTIC_Pet
{
}
/**
* @Entity
*/
class OJTIC_Dog extends OJTIC_Pet
{
}

View File

@@ -0,0 +1,105 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Query;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\Tests\Models\CMS\CmsAddress;
use Doctrine\Tests\Models\CMS\CmsGroup;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Tests\Models\CMS\CmsComment;
use Doctrine\ORM\Tools\Pagination\Paginator;
/**
* @group DDC-1613
*/
class PaginationTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$this->populate();
}
public function testCountSimpleWithoutJoin()
{
$dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u";
$query = $this->_em->createQuery($dql);
$paginator = new Paginator($query);
$this->assertEquals(3, count($paginator));
}
public function testCountWithFetchJoin()
{
$dql = "SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g";
$query = $this->_em->createQuery($dql);
$paginator = new Paginator($query);
$this->assertEquals(3, count($paginator));
}
public function testIterateSimpleWithoutJoinFetchJoinHandlingOff()
{
$dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u";
$query = $this->_em->createQuery($dql);
$paginator = new Paginator($query, false);
$data = array();
foreach ($paginator as $user) {
$data[] = $user;
}
$this->assertEquals(3, count($data));
}
public function testIterateSimpleWithoutJoinFetchJoinHandlingOn()
{
$dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u";
$query = $this->_em->createQuery($dql);
$paginator = new Paginator($query, true);
$data = array();
foreach ($paginator as $user) {
$data[] = $user;
}
$this->assertEquals(3, count($data));
}
public function testIterateWithFetchJoin()
{
$dql = "SELECT u,g FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.groups g";
$query = $this->_em->createQuery($dql);
$paginator = new Paginator($query, true);
$data = array();
foreach ($paginator as $user) {
$data[] = $user;
}
$this->assertEquals(3, count($data));
}
public function populate()
{
for ($i = 0; $i < 3; $i++) {
$user = new CmsUser();
$user->name = "Name$i";
$user->username = "username$i";
$user->status = "active";
$this->_em->persist($user);
for ($j = 0; $j < 3; $j++) {;
$group = new CmsGroup();
$group->name = "group$j";
$user->addGroup($group);
$this->_em->persist($group);
}
}
$this->_em->flush();
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Persistence\PersistentObject;
/**
*/
class PersistentCollectionTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\PersistentCollectionHolder'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\PersistentCollectionContent'),
));
} catch (\Exception $e) {
}
PersistentObject::setObjectManager($this->_em);
}
public function testPersist()
{
$collectionHolder = new PersistentCollectionHolder();
$content = new PersistentCollectionContent('first element');
$collectionHolder->addElement($content);
$this->_em->persist($collectionHolder);
$this->_em->flush();
$this->_em->clear();
$collectionHolder = $this->_em->find(__NAMESPACE__ . '\PersistentCollectionHolder', $collectionHolder->getId());
$collectionHolder->getCollection();
$content = new PersistentCollectionContent('second element');
$collectionHolder->addElement($content);
$this->assertEquals(2, $collectionHolder->getCollection()->count());
}
}
/**
* @Entity
*/
class PersistentCollectionHolder extends PersistentObject
{
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
protected $id;
/**
* @var \Doctrine\Common\Collections\Collection
* @ManyToMany(targetEntity="PersistentCollectionContent", cascade={"all"})
*/
protected $collection;
public function __construct()
{
$this->collection = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @param PersistentCollectionContent $element
*/
public function addElement(PersistentCollectionContent $element)
{
$this->collection->add($element);
}
/**
* @return \Doctrine\Common\Collections\Collection
*/
public function getCollection()
{
return clone $this->collection;
}
}
/**
* @Entity
*/
class PersistentCollectionContent extends PersistentObject
{
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
protected $id;
}

View File

@@ -0,0 +1,105 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Common\Persistence\PersistentObject;
/**
* Test that Doctrine ORM correctly works with the ObjectManagerAware and PersistentObject
* classes from Common.
*
* @group DDC-1448
*/
class PersistentObjectTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\PersistentEntity'),
));
} catch (\Exception $e) {
}
PersistentObject::setObjectManager($this->_em);
}
public function testPersist()
{
$entity = new PersistentEntity();
$entity->setName("test");
$this->_em->persist($entity);
$this->_em->flush();
}
public function testFind()
{
$entity = new PersistentEntity();
$entity->setName("test");
$this->_em->persist($entity);
$this->_em->flush();
$this->_em->clear();
$entity = $this->_em->find(__NAMESPACE__ . '\PersistentEntity', $entity->getId());
$this->assertEquals('test', $entity->getName());
$entity->setName('foobar');
$this->_em->flush();
}
public function testGetReference()
{
$entity = new PersistentEntity();
$entity->setName("test");
$this->_em->persist($entity);
$this->_em->flush();
$this->_em->clear();
$entity = $this->_em->getReference(__NAMESPACE__ . '\PersistentEntity', $entity->getId());
$this->assertEquals('test', $entity->getName());
}
public function testSetAssociation()
{
$entity = new PersistentEntity();
$entity->setName("test");
$entity->setParent($entity);
$this->_em->persist($entity);
$this->_em->flush();
$this->_em->clear();
$entity = $this->_em->getReference(__NAMESPACE__ . '\PersistentEntity', $entity->getId());
$this->assertSame($entity, $entity->getParent());
}
}
/**
* @Entity
*/
class PersistentEntity extends PersistentObject
{
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
protected $id;
/**
* @Column(type="string")
* @var string
*/
protected $name;
/**
* @ManyToOne(targetEntity="PersistentEntity")
* @var PersistentEntity
*/
protected $parent;
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* PostFlushEventTest
*
* @author Daniel Freudenberger <df@rebuy.de>
*/
class PostFlushEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var PostFlushListener
*/
private $listener;
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
$this->listener = new PostFlushListener();
$evm = $this->_em->getEventManager();
$evm->addEventListener(Events::postFlush, $this->listener);
}
public function testListenerShouldBeNotified()
{
$this->_em->persist($this->createNewValidUser());
$this->_em->flush();
$this->assertTrue($this->listener->wasNotified);
}
public function testListenerShouldNotBeNotifiedWhenFlushThrowsException()
{
$user = new CmsUser();
$user->username = 'dfreudenberger';
$this->_em->persist($user);
$exceptionRaised = false;
try {
$this->_em->flush();
} catch (\Exception $ex) {
$exceptionRaised = true;
}
$this->assertTrue($exceptionRaised);
$this->assertFalse($this->listener->wasNotified);
}
public function testListenerShouldReceiveEntityManagerThroughArgs()
{
$this->_em->persist($this->createNewValidUser());
$this->_em->flush();
$receivedEm = $this->listener->receivedArgs->getEntityManager();
$this->assertSame($this->_em, $receivedEm);
}
/**
* @return CmsUser
*/
private function createNewValidUser()
{
$user = new CmsUser();
$user->username = 'dfreudenberger';
$user->name = 'Daniel Freudenberger';
return $user;
}
}
class PostFlushListener
{
/**
* @var bool
*/
public $wasNotified = false;
/**
* @var PostFlushEventArgs
*/
public $receivedArgs;
/**
* @param PostFlushEventArgs $args
*/
public function postFlush(PostFlushEventArgs $args)
{
$this->wasNotified = true;
$this->receivedArgs = $args;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Event\PreUpdateEventArgs;
require_once __DIR__ . '/../../TestInit.php';
class PostgreSQLIdentityStrategyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
if ($this->_em->getConnection()->getDatabasePlatform()->getName() != 'postgresql') {
$this->markTestSkipped('This test is special to the PostgreSQL IDENTITY key generation strategy.');
} else {
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\PostgreSQLIdentityEntity'),
));
} catch (\Exception $e) {
// Swallow all exceptions. We do not test the schema tool here.
}
}
}
protected function tearDown() {
parent::tearDown();
// drop sequence manually due to dependency
$this->_em->getConnection()->exec('DROP SEQUENCE postgresqlidentityentity_id_seq CASCADE');
}
public function testPreSavePostSaveCallbacksAreInvoked()
{
$entity = new PostgreSQLIdentityEntity();
$entity->setValue('hello');
$this->_em->persist($entity);
$this->_em->flush();
$this->assertTrue(is_numeric($entity->getId()));
$this->assertTrue($entity->getId() > 0);
$this->assertTrue($this->_em->contains($entity));
}
}
/** @Entity */
class PostgreSQLIdentityEntity {
/** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */
private $id;
/** @Column(type="string") */
private $value;
public function getId() {return $this->id;}
public function getValue() {return $this->value;}
public function setValue($value) {$this->value = $value;}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Common\Cache\ArrayCache;
require_once __DIR__ . '/../../TestInit.php';
/**
* QueryCacheTest
*
* @author robo
*/
class QueryCacheTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var \ReflectionProperty
*/
private $cacheDataReflection;
protected function setUp() {
$this->cacheDataReflection = new \ReflectionProperty("Doctrine\Common\Cache\ArrayCache", "data");
$this->cacheDataReflection->setAccessible(true);
$this->useModelSet('cms');
parent::setUp();
}
/**
* @param ArrayCache $cache
* @return integer
*/
private function getCacheSize(ArrayCache $cache)
{
return sizeof($this->cacheDataReflection->getValue($cache));
}
public function testQueryCache_DependsOnHints()
{
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$cache = new ArrayCache();
$query->setQueryCacheDriver($cache);
$query->getResult();
$this->assertEquals(1, $this->getCacheSize($cache));
$query->setHint('foo', 'bar');
$query->getResult();
$this->assertEquals(2, $this->getCacheSize($cache));
return $query;
}
/**
* @param <type> $query
* @depends testQueryCache_DependsOnHints
*/
public function testQueryCache_DependsOnFirstResult($query)
{
$cache = $query->getQueryCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$query->setFirstResult(10);
$query->setMaxResults(9999);
$query->getResult();
$this->assertEquals($cacheCount + 1, $this->getCacheSize($cache));
}
/**
* @param <type> $query
* @depends testQueryCache_DependsOnHints
*/
public function testQueryCache_DependsOnMaxResults($query)
{
$cache = $query->getQueryCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$query->setMaxResults(10);
$query->getResult();
$this->assertEquals($cacheCount + 1, $this->getCacheSize($cache));
}
/**
* @param <type> $query
* @depends testQueryCache_DependsOnHints
*/
public function testQueryCache_DependsOnHydrationMode($query)
{
$cache = $query->getQueryCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$query->getArrayResult();
$this->assertEquals($cacheCount + 1, $this->getCacheSize($cache));
}
public function testQueryCache_NoHitSaveParserResult()
{
$this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache());
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$cache = $this->getMock('Doctrine\Common\Cache\ArrayCache', array('doFetch', 'doSave', 'doGetStats'));
$cache->expects($this->at(0))
->method('doFetch')
->with($this->isType('string'))
->will($this->returnValue(false));
$cache->expects($this->at(1))
->method('doSave')
->with($this->isType('string'), $this->isInstanceOf('Doctrine\ORM\Query\ParserResult'), $this->equalTo(null));
$query->setQueryCacheDriver($cache);
$users = $query->getResult();
}
public function testQueryCache_HitDoesNotSaveParserResult()
{
$this->_em->getConfiguration()->setQueryCacheImpl(new ArrayCache());
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$sqlExecMock = $this->getMock('Doctrine\ORM\Query\Exec\AbstractSqlExecutor', array('execute'));
$sqlExecMock->expects($this->once())
->method('execute')
->will($this->returnValue( 10 ));
$parserResultMock = $this->getMock('Doctrine\ORM\Query\ParserResult');
$parserResultMock->expects($this->once())
->method('getSqlExecutor')
->will($this->returnValue($sqlExecMock));
$cache = $this->getMock('Doctrine\Common\Cache\CacheProvider',
array('doFetch', 'doContains', 'doSave', 'doDelete', 'doFlush', 'doGetStats'));
$cache->expects($this->once())
->method('doFetch')
->with($this->isType('string'))
->will($this->returnValue($parserResultMock));
$cache->expects($this->never())
->method('doSave');
$query->setQueryCacheDriver($cache);
$users = $query->getResult();
}
}

View File

@@ -0,0 +1,401 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\Company\CompanyManager;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional Query tests.
*
* @author robo
*/
class QueryDqlFunctionTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('company');
parent::setUp();
$this->generateFixture();
}
public function testAggregateSum()
{
$salarySum = $this->_em->createQuery('SELECT SUM(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getSingleResult();
$this->assertEquals(1500000, $salarySum['salary']);
}
public function testAggregateAvg()
{
$salaryAvg = $this->_em->createQuery('SELECT AVG(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getSingleResult();
$this->assertEquals(375000, round($salaryAvg['salary'], 0));
}
public function testAggregateMin()
{
$salary = $this->_em->createQuery('SELECT MIN(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getSingleResult();
$this->assertEquals(100000, $salary['salary']);
}
public function testAggregateMax()
{
$salary = $this->_em->createQuery('SELECT MAX(m.salary) AS salary FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getSingleResult();
$this->assertEquals(800000, $salary['salary']);
}
public function testAggregateCount()
{
$managerCount = $this->_em->createQuery('SELECT COUNT(m.id) AS managers FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getSingleResult();
$this->assertEquals(4, $managerCount['managers']);
}
public function testFunctionAbs()
{
$result = $this->_em->createQuery('SELECT m, ABS(m.salary * -1) AS abs FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getResult();
$this->assertEquals(4, count($result));
$this->assertEquals(100000, $result[0]['abs']);
$this->assertEquals(200000, $result[1]['abs']);
$this->assertEquals(400000, $result[2]['abs']);
$this->assertEquals(800000, $result[3]['abs']);
}
public function testFunctionConcat()
{
$arg = $this->_em->createQuery('SELECT m, CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getArrayResult();
$this->assertEquals(4, count($arg));
$this->assertEquals('Roman B.IT', $arg[0]['namedep']);
$this->assertEquals('Benjamin E.HR', $arg[1]['namedep']);
$this->assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']);
$this->assertEquals('Jonathan W.Administration', $arg[3]['namedep']);
}
public function testFunctionLength()
{
$result = $this->_em->createQuery('SELECT m, LENGTH(CONCAT(m.name, m.department)) AS namedeplength FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals(10, $result[0]['namedeplength']);
$this->assertEquals(13, $result[1]['namedeplength']);
$this->assertEquals(32, $result[2]['namedeplength']);
$this->assertEquals(25, $result[3]['namedeplength']);
}
public function testFunctionLocate()
{
$dql = "SELECT m, LOCATE('e', LOWER(m.name)) AS loc, LOCATE('e', LOWER(m.name), 7) AS loc2 ".
"FROM Doctrine\Tests\Models\Company\CompanyManager m";
$result = $this->_em->createQuery($dql)
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals(0, $result[0]['loc']);
$this->assertEquals(2, $result[1]['loc']);
$this->assertEquals(6, $result[2]['loc']);
$this->assertEquals(0, $result[3]['loc']);
$this->assertEquals(0, $result[0]['loc2']);
$this->assertEquals(10, $result[1]['loc2']);
$this->assertEquals(9, $result[2]['loc2']);
$this->assertEquals(0, $result[3]['loc2']);
}
public function testFunctionLower()
{
$result = $this->_em->createQuery("SELECT m, LOWER(m.name) AS lowername FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals('roman b.', $result[0]['lowername']);
$this->assertEquals('benjamin e.', $result[1]['lowername']);
$this->assertEquals('guilherme b.', $result[2]['lowername']);
$this->assertEquals('jonathan w.', $result[3]['lowername']);
}
public function testFunctionMod()
{
$result = $this->_em->createQuery("SELECT m, MOD(m.salary, 3500) AS amod FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals(2000, $result[0]['amod']);
$this->assertEquals(500, $result[1]['amod']);
$this->assertEquals(1000, $result[2]['amod']);
$this->assertEquals(2000, $result[3]['amod']);
}
public function testFunctionSqrt()
{
$result = $this->_em->createQuery("SELECT m, SQRT(m.salary) AS sqrtsalary FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals(316, round($result[0]['sqrtsalary']));
$this->assertEquals(447, round($result[1]['sqrtsalary']));
$this->assertEquals(632, round($result[2]['sqrtsalary']));
$this->assertEquals(894, round($result[3]['sqrtsalary']));
}
public function testFunctionUpper()
{
$result = $this->_em->createQuery("SELECT m, UPPER(m.name) AS uppername FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals('ROMAN B.', $result[0]['uppername']);
$this->assertEquals('BENJAMIN E.', $result[1]['uppername']);
$this->assertEquals('GUILHERME B.', $result[2]['uppername']);
$this->assertEquals('JONATHAN W.', $result[3]['uppername']);
}
public function testFunctionSubstring()
{
$dql = "SELECT m, SUBSTRING(m.name, 1, 3) AS str1, SUBSTRING(m.name, 5) AS str2 ".
"FROM Doctrine\Tests\Models\Company\CompanyManager m";
$result = $this->_em->createQuery($dql)
->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals('Rom', $result[0]['str1']);
$this->assertEquals('Ben', $result[1]['str1']);
$this->assertEquals('Gui', $result[2]['str1']);
$this->assertEquals('Jon', $result[3]['str1']);
$this->assertEquals('n B.', $result[0]['str2']);
$this->assertEquals('amin E.', $result[1]['str2']);
$this->assertEquals('herme B.', $result[2]['str2']);
$this->assertEquals('than W.', $result[3]['str2']);
}
public function testFunctionTrim()
{
$dql = "SELECT m, TRIM(TRAILING '.' FROM m.name) AS str1, ".
" TRIM(LEADING '.' FROM m.name) AS str2, TRIM(CONCAT(' ', CONCAT(m.name, ' '))) AS str3 ".
"FROM Doctrine\Tests\Models\Company\CompanyManager m";
$result = $this->_em->createQuery($dql)->getArrayResult();
$this->assertEquals(4, count($result));
$this->assertEquals('Roman B', $result[0]['str1']);
$this->assertEquals('Benjamin E', $result[1]['str1']);
$this->assertEquals('Guilherme B', $result[2]['str1']);
$this->assertEquals('Jonathan W', $result[3]['str1']);
$this->assertEquals('Roman B.', $result[0]['str2']);
$this->assertEquals('Benjamin E.', $result[1]['str2']);
$this->assertEquals('Guilherme B.', $result[2]['str2']);
$this->assertEquals('Jonathan W.', $result[3]['str2']);
$this->assertEquals('Roman B.', $result[0]['str3']);
$this->assertEquals('Benjamin E.', $result[1]['str3']);
$this->assertEquals('Guilherme B.', $result[2]['str3']);
$this->assertEquals('Jonathan W.', $result[3]['str3']);
}
public function testOperatorAdd()
{
$result = $this->_em->createQuery('SELECT m, m.salary+2500 AS add FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getResult();
$this->assertEquals(4, count($result));
$this->assertEquals(102500, $result[0]['add']);
$this->assertEquals(202500, $result[1]['add']);
$this->assertEquals(402500, $result[2]['add']);
$this->assertEquals(802500, $result[3]['add']);
}
public function testOperatorSub()
{
$result = $this->_em->createQuery('SELECT m, m.salary-2500 AS sub FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getResult();
$this->assertEquals(4, count($result));
$this->assertEquals(97500, $result[0]['sub']);
$this->assertEquals(197500, $result[1]['sub']);
$this->assertEquals(397500, $result[2]['sub']);
$this->assertEquals(797500, $result[3]['sub']);
}
public function testOperatorMultiply()
{
$result = $this->_em->createQuery('SELECT m, m.salary*2 AS op FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getResult();
$this->assertEquals(4, count($result));
$this->assertEquals(200000, $result[0]['op']);
$this->assertEquals(400000, $result[1]['op']);
$this->assertEquals(800000, $result[2]['op']);
$this->assertEquals(1600000, $result[3]['op']);
}
/**
* @group test
*/
public function testOperatorDiv()
{
$result = $this->_em->createQuery('SELECT m, (m.salary/0.5) AS op FROM Doctrine\Tests\Models\Company\CompanyManager m')
->getResult();
$this->assertEquals(4, count($result));
$this->assertEquals(200000, $result[0]['op']);
$this->assertEquals(400000, $result[1]['op']);
$this->assertEquals(800000, $result[2]['op']);
$this->assertEquals(1600000, $result[3]['op']);
}
public function testConcatFunction()
{
$arg = $this->_em->createQuery('SELECT CONCAT(m.name, m.department) AS namedep FROM Doctrine\Tests\Models\Company\CompanyManager m order by namedep desc')
->getArrayResult();
$this->assertEquals(4, count($arg));
$this->assertEquals('Roman B.IT', $arg[0]['namedep']);
$this->assertEquals('Jonathan W.Administration', $arg[1]['namedep']);
$this->assertEquals('Guilherme B.Complaint Department', $arg[2]['namedep']);
$this->assertEquals('Benjamin E.HR', $arg[3]['namedep']);
}
/**
* @group DDC-1014
*/
public function testDateDiff()
{
$query = $this->_em->createQuery("SELECT DATE_DIFF(CURRENT_TIMESTAMP(), DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day')) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m");
$arg = $query->getArrayResult();
$this->assertEquals(-10, $arg[0]['diff'], "Should be roughly -10 (or -9)", 1);
$query = $this->_em->createQuery("SELECT DATE_DIFF(DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day'), CURRENT_TIMESTAMP()) AS diff FROM Doctrine\Tests\Models\Company\CompanyManager m");
$arg = $query->getArrayResult();
$this->assertEquals(10, $arg[0]['diff'], "Should be roughly 10 (or 9)", 1);
}
/**
* @group DDC-1014
*/
public function testDateAdd()
{
$arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertTrue(strtotime($arg[0]['add']) > 0);
$arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertTrue(strtotime($arg[0]['add']) > 0);
}
/**
* @group DDC-1014
*/
public function testDateSub()
{
$arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertTrue(strtotime($arg[0]['add']) > 0);
$arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m")
->getArrayResult();
$this->assertTrue(strtotime($arg[0]['add']) > 0);
}
/**
* @group DDC-1213
*/
public function testBitOrComparison()
{
$dql = 'SELECT m, ' .
'BIT_OR(4, 2) AS bit_or,' .
'BIT_OR( (m.salary/100000) , 2 ) AS salary_bit_or ' .
'FROM Doctrine\Tests\Models\Company\CompanyManager m ' .
'ORDER BY ' .
'm.id ' ;
$result = $this->_em->createQuery($dql)->getArrayResult();
$this->assertEquals(4 | 2, $result[0]['bit_or']);
$this->assertEquals(4 | 2, $result[1]['bit_or']);
$this->assertEquals(4 | 2, $result[2]['bit_or']);
$this->assertEquals(4 | 2, $result[3]['bit_or']);
$this->assertEquals(($result[0][0]['salary']/100000) | 2, $result[0]['salary_bit_or']);
$this->assertEquals(($result[1][0]['salary']/100000) | 2, $result[1]['salary_bit_or']);
$this->assertEquals(($result[2][0]['salary']/100000) | 2, $result[2]['salary_bit_or']);
$this->assertEquals(($result[3][0]['salary']/100000) | 2, $result[3]['salary_bit_or']);
}
/**
* @group DDC-1213
*/
public function testBitAndComparison()
{
$dql = 'SELECT m, ' .
'BIT_AND(4, 2) AS bit_and,' .
'BIT_AND( (m.salary/100000) , 2 ) AS salary_bit_and ' .
'FROM Doctrine\Tests\Models\Company\CompanyManager m ' .
'ORDER BY ' .
'm.id ' ;
$result = $this->_em->createQuery($dql)->getArrayResult();
$this->assertEquals(4 & 2, $result[0]['bit_and']);
$this->assertEquals(4 & 2, $result[1]['bit_and']);
$this->assertEquals(4 & 2, $result[2]['bit_and']);
$this->assertEquals(4 & 2, $result[3]['bit_and']);
$this->assertEquals(($result[0][0]['salary']/100000) & 2, $result[0]['salary_bit_and']);
$this->assertEquals(($result[1][0]['salary']/100000) & 2, $result[1]['salary_bit_and']);
$this->assertEquals(($result[2][0]['salary']/100000) & 2, $result[2]['salary_bit_and']);
$this->assertEquals(($result[3][0]['salary']/100000) & 2, $result[3]['salary_bit_and']);
}
protected function generateFixture()
{
$manager1 = new CompanyManager();
$manager1->setName('Roman B.');
$manager1->setTitle('Foo');
$manager1->setDepartment('IT');
$manager1->setSalary(100000);
$manager2 = new CompanyManager();
$manager2->setName('Benjamin E.');
$manager2->setTitle('Foo');
$manager2->setDepartment('HR');
$manager2->setSalary(200000);
$manager3 = new CompanyManager();
$manager3->setName('Guilherme B.');
$manager3->setTitle('Foo');
$manager3->setDepartment('Complaint Department');
$manager3->setSalary(400000);
$manager4 = new CompanyManager();
$manager4->setName('Jonathan W.');
$manager4->setTitle('Foo');
$manager4->setDepartment('Administration');
$manager4->setSalary(800000);
$this->_em->persist($manager1);
$this->_em->persist($manager2);
$this->_em->persist($manager3);
$this->_em->persist($manager4);
$this->_em->flush();
$this->_em->clear();
}
}

View File

@@ -0,0 +1,658 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\DBAL\Connection;
use Doctrine\Tests\Models\CMS\CmsUser,
Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional Query tests.
*
* @author robo
*/
class QueryTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testSimpleQueries()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select u, upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
$result = $query->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][0]);
$this->assertEquals('Guilherme', $result[0][0]->name);
$this->assertEquals('gblanco', $result[0][0]->username);
$this->assertEquals('developer', $result[0][0]->status);
$this->assertEquals('GUILHERME', $result[0][1]);
$resultArray = $query->getArrayResult();
$this->assertEquals(1, count($resultArray));
$this->assertTrue(is_array($resultArray[0][0]));
$this->assertEquals('Guilherme', $resultArray[0][0]['name']);
$this->assertEquals('gblanco', $resultArray[0][0]['username']);
$this->assertEquals('developer', $resultArray[0][0]['status']);
$this->assertEquals('GUILHERME', $resultArray[0][1]);
$scalarResult = $query->getScalarResult();
$this->assertEquals(1, count($scalarResult));
$this->assertEquals('Guilherme', $scalarResult[0]['u_name']);
$this->assertEquals('gblanco', $scalarResult[0]['u_username']);
$this->assertEquals('developer', $scalarResult[0]['u_status']);
$this->assertEquals('GUILHERME', $scalarResult[0][1]);
$query = $this->_em->createQuery("select upper(u.name) from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
$this->assertEquals('GUILHERME', $query->getSingleScalarResult());
}
public function testJoinQueries()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$article1 = new CmsArticle;
$article1->topic = "Doctrine 2";
$article1->text = "This is an introduction to Doctrine 2.";
$user->addArticle($article1);
$article2 = new CmsArticle;
$article2->topic = "Symfony 2";
$article2->text = "This is an introduction to Symfony 2.";
$user->addArticle($article2);
$this->_em->persist($user);
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.articles a ORDER BY a.topic");
$users = $query->getResult();
$this->assertEquals(1, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
$this->assertEquals(2, count($users[0]->articles));
$this->assertEquals('Doctrine 2', $users[0]->articles[0]->topic);
$this->assertEquals('Symfony 2', $users[0]->articles[1]->topic);
}
public function testUsingZeroBasedQueryParameterShouldWork()
{
$user = new CmsUser;
$user->name = 'Jonathan';
$user->username = 'jwage';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?0');
$q->setParameter(0, 'jwage');
$user = $q->getSingleResult();
$this->assertNotNull($user);
}
public function testUsingUnknownQueryParameterShouldThrowException()
{
$this->setExpectedException(
"Doctrine\ORM\Query\QueryException",
"Invalid parameter: token 2 is not defined in the query."
);
$q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1');
$q->setParameter(2, 'jwage');
$user = $q->getSingleResult();
}
public function testMismatchingParamExpectedParamCount()
{
$this->setExpectedException(
"Doctrine\ORM\Query\QueryException",
"Invalid parameter number: number of bound variables does not match number of tokens"
);
$q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1');
$q->setParameter(1, 'jwage');
$q->setParameter(2, 'jwage');
$user = $q->getSingleResult();
}
public function testInvalidInputParameterThrowsException()
{
$this->setExpectedException("Doctrine\ORM\Query\QueryException");
$q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?');
$q->setParameter(1, 'jwage');
$user = $q->getSingleResult();
}
public function testSetParameters()
{
$q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1 AND u.status = ?2');
$q->setParameters(array(1 => 'jwage', 2 => 'active'));
$users = $q->getResult();
}
/**
* @group DDC-1070
*/
public function testIterateResultAsArrayAndParams()
{
$article1 = new CmsArticle;
$article1->topic = "Doctrine 2";
$article1->text = "This is an introduction to Doctrine 2.";
$article2 = new CmsArticle;
$article2->topic = "Symfony 2";
$article2->text = "This is an introduction to Symfony 2.";
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$articleId = $article1->id;
$query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = ?1");
$articles = $query->iterate(array(1 => 'Doctrine 2'), Query::HYDRATE_ARRAY);
$found = array();
foreach ($articles AS $article) {
$found[] = $article;
}
$this->assertEquals(1, count($found));
$this->assertEquals(array(
array(array('id' => $articleId, 'topic' => 'Doctrine 2', 'text' => 'This is an introduction to Doctrine 2.', 'version' => 1))
), $found);
}
public function testIterateResult_IterativelyBuildUpUnitOfWork()
{
$article1 = new CmsArticle;
$article1->topic = "Doctrine 2";
$article1->text = "This is an introduction to Doctrine 2.";
$article2 = new CmsArticle;
$article2->topic = "Symfony 2";
$article2->text = "This is an introduction to Symfony 2.";
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a");
$articles = $query->iterate();
$iteratedCount = 0;
$topics = array();
foreach($articles AS $row) {
$article = $row[0];
$topics[] = $article->topic;
$identityMap = $this->_em->getUnitOfWork()->getIdentityMap();
$identityMapCount = count($identityMap['Doctrine\Tests\Models\CMS\CmsArticle']);
$this->assertTrue($identityMapCount>$iteratedCount);
$iteratedCount++;
}
$this->assertEquals(array("Doctrine 2", "Symfony 2"), $topics);
$this->assertEquals(2, $iteratedCount);
$this->_em->flush();
$this->_em->clear();
}
public function testIterateResultClearEveryCycle()
{
$article1 = new CmsArticle;
$article1->topic = "Doctrine 2";
$article1->text = "This is an introduction to Doctrine 2.";
$article2 = new CmsArticle;
$article2->topic = "Symfony 2";
$article2->text = "This is an introduction to Symfony 2.";
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a");
$articles = $query->iterate();
$iteratedCount = 0;
$topics = array();
foreach($articles AS $row) {
$article = $row[0];
$topics[] = $article->topic;
$this->_em->clear();
$iteratedCount++;
}
$this->assertEquals(array("Doctrine 2", "Symfony 2"), $topics);
$this->assertEquals(2, $iteratedCount);
$this->_em->flush();
}
/**
* @expectedException \Doctrine\ORM\Query\QueryException
*/
public function testIterateResult_FetchJoinedCollection_ThrowsException()
{
$query = $this->_em->createQuery("SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a");
$articles = $query->iterate();
}
/**
* @expectedException Doctrine\ORM\NoResultException
*/
public function testGetSingleResultThrowsExceptionOnNoResult()
{
$this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a")
->getSingleResult();
}
/**
* @expectedException Doctrine\ORM\NoResultException
*/
public function testGetSingleScalarResultThrowsExceptionOnNoResult()
{
$this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a")
->getSingleScalarResult();
}
/**
* @expectedException Doctrine\ORM\NonUniqueResultException
*/
public function testGetSingleScalarResultThrowsExceptionOnNonUniqueResult()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$article1 = new CmsArticle;
$article1->topic = "Doctrine 2";
$article1->text = "This is an introduction to Doctrine 2.";
$user->addArticle($article1);
$article2 = new CmsArticle;
$article2->topic = "Symfony 2";
$article2->text = "This is an introduction to Symfony 2.";
$user->addArticle($article2);
$this->_em->persist($user);
$this->_em->persist($article1);
$this->_em->persist($article2);
$this->_em->flush();
$this->_em->clear();
$this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a")
->getSingleScalarResult();
}
public function testModifiedLimitQuery()
{
for ($i = 0; $i < 5; $i++) {
$user = new CmsUser;
$user->name = 'Guilherme' . $i;
$user->username = 'gblanco' . $i;
$user->status = 'developer';
$this->_em->persist($user);
}
$this->_em->flush();
$this->_em->clear();
$data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u')
->setFirstResult(1)
->setMaxResults(2)
->getResult();
$this->assertEquals(2, count($data));
$this->assertEquals('gblanco1', $data[0]->username);
$this->assertEquals('gblanco2', $data[1]->username);
$data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u')
->setFirstResult(3)
->setMaxResults(2)
->getResult();
$this->assertEquals(2, count($data));
$this->assertEquals('gblanco3', $data[0]->username);
$this->assertEquals('gblanco4', $data[1]->username);
$data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u')
->setFirstResult(3)
->setMaxResults(2)
->getScalarResult();
}
public function testSupportsQueriesWithEntityNamespaces()
{
$this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS');
try {
$query = $this->_em->createQuery('UPDATE CMS:CmsUser u SET u.name = ?1');
$this->assertEquals('UPDATE cms_users SET name = ?', $query->getSql());
$query->free();
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
$this->_em->getConfiguration()->setEntityNamespaces(array());
}
/**
* @group DDC-604
*/
public function testEntityParameters()
{
$article = new CmsArticle;
$article->topic = "dr. dolittle";
$article->text = "Once upon a time ...";
$author = new CmsUser;
$author->name = "anonymous";
$author->username = "anon";
$author->status = "here";
$article->user = $author;
$this->_em->persist($author);
$this->_em->persist($article);
$this->_em->flush();
$this->_em->clear();
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a where a.topic = :topic and a.user = :user")
->setParameter("user", $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $author->id))
->setParameter("topic", "dr. dolittle");
$result = $q->getResult();
$this->assertEquals(1, count($result));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0]);
$this->assertEquals("dr. dolittle", $result[0]->topic);
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[0]->user);
$this->assertFalse($result[0]->user->__isInitialized__);
}
/**
* @group DDC-952
*/
public function testEnableFetchEagerMode()
{
for ($i = 0; $i < 10; $i++) {
$article = new CmsArticle;
$article->topic = "dr. dolittle";
$article->text = "Once upon a time ...";
$author = new CmsUser;
$author->name = "anonymous";
$author->username = "anon".$i;
$author->status = "here";
$article->user = $author;
$this->_em->persist($author);
$this->_em->persist($article);
}
$this->_em->flush();
$this->_em->clear();
$articles = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a')
->setFetchMode('Doctrine\Tests\Models\CMS\CmsArticle', 'user', ClassMetadata::FETCH_EAGER)
->getResult();
$this->assertEquals(10, count($articles));
foreach ($articles AS $article) {
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $article);
}
}
/**
* @group DDC-991
*/
public function testgetOneOrNullResult()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
$fetchedUser = $query->getOneOrNullResult();
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $fetchedUser);
$this->assertEquals('gblanco', $fetchedUser->username);
$query = $this->_em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
$fetchedUsername = $query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
$this->assertEquals('gblanco', $fetchedUsername);
}
/**
* @group DDC-991
*/
public function testgetOneOrNullResultSeveralRows()
{
$user = new CmsUser;
$user->name = 'Guilherme';
$user->username = 'gblanco';
$user->status = 'developer';
$this->_em->persist($user);
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u");
$this->setExpectedException('Doctrine\ORM\NonUniqueResultException');
$fetchedUser = $query->getOneOrNullResult();
}
/**
* @group DDC-991
*/
public function testgetOneOrNullResultNoRows()
{
$query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u");
$this->assertNull($query->getOneOrNullResult());
$query = $this->_em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'");
$this->assertNull($query->getOneOrNullResult(Query::HYDRATE_SCALAR));
}
/**
* @group DBAL-171
*/
public function testParameterOrder()
{
$user1 = new CmsUser;
$user1->name = 'Benjamin';
$user1->username = 'beberlei';
$user1->status = 'developer';
$this->_em->persist($user1);
$user2 = new CmsUser;
$user2->name = 'Roman';
$user2->username = 'romanb';
$user2->status = 'developer';
$this->_em->persist($user2);
$user3 = new CmsUser;
$user3->name = 'Jonathan';
$user3->username = 'jwage';
$user3->status = 'developer';
$this->_em->persist($user3);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.status = :a AND u.id IN (:b)");
$query->setParameters(array(
'b' => array($user1->id, $user2->id, $user3->id),
'a' => 'developer',
));
$result = $query->getResult();
$this->assertEquals(3, count($result));
}
public function testDqlWithAutoInferOfParameters()
{
$user = new CmsUser;
$user->name = 'Benjamin';
$user->username = 'beberlei';
$user->status = 'developer';
$this->_em->persist($user);
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'developer';
$this->_em->persist($user);
$user = new CmsUser;
$user->name = 'Jonathan';
$user->username = 'jwage';
$user->status = 'developer';
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username IN (?0)");
$query->setParameter(0, array('beberlei', 'jwage'));
$users = $query->execute();
$this->assertEquals(2, count($users));
}
public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalPrimary()
{
$qb = $this->_em->createQueryBuilder();
$qb->select('u')
->from('Doctrine\Tests\Models\CMS\CmsUser', 'u')
->innerJoin('u.articles', 'a')
->where('(u.id = 0) OR (u.id IS NULL)');
$query = $qb->getQuery();
$users = $query->execute();
$this->assertEquals(0, count($users));
}
public function testQueryWithArrayOfEntitiesAsParameter()
{
$userA = new CmsUser;
$userA->name = 'Benjamin';
$userA->username = 'beberlei';
$userA->status = 'developer';
$this->_em->persist($userA);
$userB = new CmsUser;
$userB->name = 'Roman';
$userB->username = 'romanb';
$userB->status = 'developer';
$this->_em->persist($userB);
$userC = new CmsUser;
$userC->name = 'Jonathan';
$userC->username = 'jwage';
$userC->status = 'developer';
$this->_em->persist($userC);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (?0) OR u.username = ?1");
$query->setParameter(0, array($userA, $userC));
$query->setParameter(1, 'beberlei');
$users = $query->execute();
$this->assertEquals(2, count($users));
}
public function testQueryWithHiddenAsSelectExpression()
{
$userA = new CmsUser;
$userA->name = 'Benjamin';
$userA->username = 'beberlei';
$userA->status = 'developer';
$this->_em->persist($userA);
$userB = new CmsUser;
$userB->name = 'Roman';
$userB->username = 'romanb';
$userB->status = 'developer';
$this->_em->persist($userB);
$userC = new CmsUser;
$userC->name = 'Jonathan';
$userC->username = 'jwage';
$userC->status = 'developer';
$this->_em->persist($userC);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery("SELECT u, (SELECT COUNT(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2) AS HIDDEN total FROM Doctrine\Tests\Models\CMS\CmsUser u");
$users = $query->execute();
$this->assertEquals(3, count($users));
$this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]);
}
/**
* @group DDC-1651
*/
public function testSetParameterBindingSingleIdentifierObjectConverted()
{
$userC = new CmsUser;
$userC->name = 'Jonathan';
$userC->username = 'jwage';
$userC->status = 'developer';
$this->_em->persist($userC);
$this->_em->flush();
$this->_em->clear();
$q = $this->_em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1");
$q->setParameter(1, $userC);
$this->assertEquals($userC->id, $q->getParameter(1));
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
/**
* Functional Query tests.
*
* @group DDC-692
*/
class ReadOnlyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\ReadOnlyEntity'),
));
} catch(\Exception $e) {
}
}
public function testReadOnlyEntityNeverChangeTracked()
{
$readOnly = new ReadOnlyEntity("Test1", 1234);
$this->_em->persist($readOnly);
$this->_em->flush();
$readOnly->name = "Test2";
$readOnly->numericValue = 4321;
$this->_em->flush();
$this->_em->clear();
$dbReadOnly = $this->_em->find('Doctrine\Tests\ORM\Functional\ReadOnlyEntity', $readOnly->id);
$this->assertEquals("Test1", $dbReadOnly->name);
$this->assertEquals(1234, $dbReadOnly->numericValue);
}
/**
* @group DDC-1659
*/
public function testClearReadOnly()
{
$readOnly = new ReadOnlyEntity("Test1", 1234);
$this->_em->persist($readOnly);
$this->_em->flush();
$this->_em->getUnitOfWork()->markReadOnly($readOnly);
$this->_em->clear();
$this->assertFalse($this->_em->getUnitOfWork()->isReadOnly($readOnly));
}
/**
* @group DDC-1659
*/
public function testClearEntitiesReadOnly()
{
$readOnly = new ReadOnlyEntity("Test1", 1234);
$this->_em->persist($readOnly);
$this->_em->flush();
$this->_em->getUnitOfWork()->markReadOnly($readOnly);
$this->_em->clear(get_class($readOnly));
$this->assertFalse($this->_em->getUnitOfWork()->isReadOnly($readOnly));
}
}
/**
* @Entity(readOnly=true)
*/
class ReadOnlyEntity
{
/**
* @Id @GeneratedValue @Column(type="integer")
* @var int
*/
public $id;
/** @column(type="string") */
public $name;
/** @Column(type="integer") */
public $numericValue;
public function __construct($name, $number)
{
$this->name = $name;
$this->numericValue = $number;
}
}

View File

@@ -0,0 +1,250 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Proxy\ProxyFactory;
use Doctrine\ORM\Proxy\ProxyClassGenerator;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\Models\ECommerce\ECommerceShipping;
use Doctrine\Tests\Models\Company\CompanyAuction;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests the generation of a proxy object for lazy loading.
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class ReferenceProxyTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
$this->_factory = new ProxyFactory(
$this->_em,
__DIR__ . '/../../Proxies',
'Doctrine\Tests\Proxies',
true);
}
public function createProduct()
{
$product = new ECommerceProduct();
$product->setName('Doctrine Cookbook');
$this->_em->persist($product);
$this->_em->flush();
$this->_em->clear();
return $product->getId();
}
public function createAuction()
{
$event = new CompanyAuction();
$event->setData('Doctrine Cookbook');
$this->_em->persist($event);
$this->_em->flush();
$this->_em->clear();
return $event->getId();
}
public function testLazyLoadsFieldValuesFromDatabase()
{
$id = $this->createProduct();
$productProxy = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct', array('id' => $id));
$this->assertEquals('Doctrine Cookbook', $productProxy->getName());
}
/**
* @group DDC-727
*/
public function testAccessMetatadaForProxy()
{
$id = $this->createProduct();
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$class = $this->_em->getClassMetadata(get_class($entity));
$this->assertEquals('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $class->name);
}
/**
* @group DDC-1033
*/
public function testReferenceFind()
{
$id = $this->createProduct();
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$entity2 = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertSame($entity, $entity2);
$this->assertEquals('Doctrine Cookbook', $entity2->getName());
}
/**
* @group DDC-1033
*/
public function testCloneProxy()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
/* @var $clone Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$clone = clone $entity;
$this->assertEquals($id, $entity->getId());
$this->assertEquals('Doctrine Cookbook', $entity->getName());
$this->assertFalse($this->_em->contains($clone), "Cloning a reference proxy should return an unmanaged/detached entity.");
$this->assertEquals($id, $clone->getId(), "Cloning a reference proxy should return same id.");
$this->assertEquals('Doctrine Cookbook', $clone->getName(), "Cloning a reference proxy should return same product name.");
// domain logic, Product::__clone sets isCloned public property
$this->assertTrue($clone->isCloned);
$this->assertFalse($entity->isCloned);
}
/**
* @group DDC-733
*/
public function testInitializeProxy()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy.");
$this->_em->getUnitOfWork()->initializeObject($entity);
$this->assertTrue($entity->__isInitialized__, "Should be initialized after called UnitOfWork::initializeObject()");
}
/**
* @group DDC-1163
*/
public function testInitializeChangeAndFlushProxy()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$entity->setName('Doctrine 2 Cookbook');
$this->_em->flush();
$this->_em->clear();
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertEquals('Doctrine 2 Cookbook', $entity->getName());
}
/**
* @group DDC-1022
*/
public function testWakeupCalledOnProxy()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertFalse($entity->wakeUp);
$entity->setName('Doctrine 2 Cookbook');
$this->assertTrue($entity->wakeUp, "Loading the proxy should call __wakeup().");
}
public function testDoNotInitializeProxyOnGettingTheIdentifier()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy.");
$this->assertEquals($id, $entity->getId());
$this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy.");
}
/**
* @group DDC-1625
*/
public function testDoNotInitializeProxyOnGettingTheIdentifier_DDC_1625()
{
$id = $this->createAuction();
/* @var $entity Doctrine\Tests\Models\Company\CompanyAuction */
$entity = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyAuction' , $id);
$this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy.");
$this->assertEquals($id, $entity->getId());
$this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy when extending.");
}
public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightType()
{
$product = new ECommerceProduct();
$product->setName('Doctrine Cookbook');
$shipping = new ECommerceShipping();
$shipping->setDays(1);
$product->setShipping($shipping);
$this->_em->persist($product);
$this->_em->flush();
$this->_em->clear();
$id = $shipping->getId();
$product = $this->_em->getRepository('Doctrine\Tests\Models\ECommerce\ECommerceProduct')->find($product->getId());
$entity = $product->getShipping();
$this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy.");
$this->assertEquals($id, $entity->getId());
$this->assertSame($id, $entity->getId(), "Check that the id's are the same value, and type.");
$this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy.");
}
public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy.");
$this->assertEquals('Doctrine Cookbook', $entity->getName());
$this->assertTrue($entity->__isInitialized__, "Getting something other than the identifier initializes the proxy.");
}
/**
* @group DDC-1604
*/
public function testCommonPersistenceProxy()
{
$id = $this->createProduct();
/* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */
$entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id);
$className = \Doctrine\Common\Util\ClassUtils::getClass($entity);
$this->assertInstanceOf('Doctrine\Common\Persistence\Proxy', $entity);
$this->assertFalse($entity->__isInitialized());
$this->assertEquals('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $className);
$restName = str_replace($this->_em->getConfiguration()->getProxyNamespace(), "", get_class($entity));
$restName = substr(get_class($entity), strlen($this->_em->getConfiguration()->getProxyNamespace()) +1);
$proxyFileName = $this->_em->getConfiguration()->getProxyDir() . DIRECTORY_SEPARATOR . str_replace("\\", "", $restName) . ".php";
$this->assertTrue(file_exists($proxyFileName), "Proxy file name cannot be found generically.");
$entity->__load();
$this->assertTrue($entity->__isInitialized());
}
}

View File

@@ -0,0 +1,254 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Common\Cache\ArrayCache;
require_once __DIR__ . '/../../TestInit.php';
/**
* ResultCacheTest
*
* @author robo
*/
class ResultCacheTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
/**
* @var \ReflectionProperty
*/
private $cacheDataReflection;
protected function setUp() {
$this->cacheDataReflection = new \ReflectionProperty("Doctrine\Common\Cache\ArrayCache", "data");
$this->cacheDataReflection->setAccessible(true);
$this->useModelSet('cms');
parent::setUp();
}
/**
* @param ArrayCache $cache
* @return integer
*/
private function getCacheSize(ArrayCache $cache)
{
return sizeof($this->cacheDataReflection->getValue($cache));
}
public function testResultCache()
{
$user = new CmsUser;
$user->name = 'Roman';
$user->username = 'romanb';
$user->status = 'dev';
$this->_em->persist($user);
$this->_em->flush();
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$cache = new ArrayCache();
$query->setResultCacheDriver($cache)->setResultCacheId('my_cache_id');
$this->assertFalse($cache->contains('my_cache_id'));
$users = $query->getResult();
$this->assertTrue($cache->contains('my_cache_id'));
$this->assertEquals(1, count($users));
$this->assertEquals('Roman', $users[0]->name);
$this->_em->clear();
$query2 = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$query2->setResultCacheDriver($cache)->setResultCacheId('my_cache_id');
$users = $query2->getResult();
$this->assertTrue($cache->contains('my_cache_id'));
$this->assertEquals(1, count($users));
$this->assertEquals('Roman', $users[0]->name);
}
public function testSetResultCacheId()
{
$cache = new ArrayCache;
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$query->setResultCacheDriver($cache);
$query->setResultCacheId('testing_result_cache_id');
$this->assertFalse($cache->contains('testing_result_cache_id'));
$users = $query->getResult();
$this->assertTrue($cache->contains('testing_result_cache_id'));
}
public function testUseResultCache()
{
$cache = new \Doctrine\Common\Cache\ArrayCache();
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux');
$query->useResultCache(true);
$query->setResultCacheDriver($cache);
$query->setResultCacheId('testing_result_cache_id');
$users = $query->getResult();
$this->assertTrue($cache->contains('testing_result_cache_id'));
$this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache());
}
/**
* @group DDC-1026
*/
public function testUseResultCacheParams()
{
$cache = new \Doctrine\Common\Cache\ArrayCache();
$sqlCount = count($this->_sqlLoggerStack->queries);
$query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux WHERE ux.id = ?1');
$query->setParameter(1, 1);
$query->setResultCacheDriver($cache);
$query->useResultCache(true);
$query->getResult();
$query->setParameter(1, 2);
$query->getResult();
$this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "Two non-cached queries.");
$query->setParameter(1, 1);
$query->useResultCache(true);
$query->getResult();
$query->setParameter(1, 2);
$query->getResult();
$this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "The next two sql should have been cached, but were not.");
}
public function testNativeQueryResultCaching()
{
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addScalarResult('id', 'u');
$query = $this->_em->createNativeQuery('select u.id FROM cms_users u WHERE u.id = ?', $rsm);
$query->setParameter(1, 10);
$cache = new ArrayCache();
$query->setResultCacheDriver($cache)->useResultCache(true);
$this->assertEquals(0, $this->getCacheSize($cache));
$query->getResult();
$this->assertEquals(1, $this->getCacheSize($cache));
return $query;
}
/**
* @param string $query
* @depends testNativeQueryResultCaching
*/
public function testResultCacheNotDependsOnQueryHints($query)
{
$cache = $query->getResultCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$query->setHint('foo', 'bar');
$query->getResult();
$this->assertEquals($cacheCount, $this->getCacheSize($cache));
}
/**
* @param <type> $query
* @depends testNativeQueryResultCaching
*/
public function testResultCacheDependsOnParameters($query)
{
$cache = $query->getResultCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$query->setParameter(1, 50);
$query->getResult();
$this->assertEquals($cacheCount + 1, $this->getCacheSize($cache));
}
/**
* @param <type> $query
* @depends testNativeQueryResultCaching
*/
public function testResultCacheNotDependsOnHydrationMode($query)
{
$cache = $query->getResultCacheDriver();
$cacheCount = $this->getCacheSize($cache);
$this->assertNotEquals(\Doctrine\ORM\Query::HYDRATE_ARRAY, $query->getHydrationMode());
$query->getArrayResult();
$this->assertEquals($cacheCount, $this->getCacheSize($cache));
}
/**
* @group DDC-909
*/
public function testResultCacheWithObjectParameter()
{
$user1 = new CmsUser;
$user1->name = 'Roman';
$user1->username = 'romanb';
$user1->status = 'dev';
$user2 = new CmsUser;
$user2->name = 'Benjamin';
$user2->username = 'beberlei';
$user2->status = 'dev';
$article = new CmsArticle();
$article->text = "foo";
$article->topic = "baz";
$article->user = $user1;
$this->_em->persist($article);
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->flush();
$query = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1');
$query->setParameter(1, $user1);
$cache = new ArrayCache();
$query->setResultCacheDriver($cache)->useResultCache(true);
$articles = $query->getResult();
$this->assertEquals(1, count($articles));
$this->assertEquals('baz', $articles[0]->topic);
$this->_em->clear();
$query2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1');
$query2->setParameter(1, $user1);
$query2->setResultCacheDriver($cache)->useResultCache(true);
$articles = $query2->getResult();
$this->assertEquals(1, count($articles));
$this->assertEquals('baz', $articles[0]->topic);
$query3 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1');
$query3->setParameter(1, $user2);
$query3->setResultCacheDriver($cache)->useResultCache(true);
$articles = $query3->getResult();
$this->assertEquals(0, count($articles));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
<?php
namespace Doctrine\Tests\ORM\Functional\SchemaTool;
use Doctrine\DBAL\Schema\Schema;
require_once __DIR__ . '/../../../TestInit.php';
/**
* Functional tests for the Class Table Inheritance mapping strategy.
*
* @author robo
*/
class CompanySchemaTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('company');
parent::setUp();
}
/**
* @group DDC-966
* @return Schema
*/
public function testGeneratedSchema()
{
$schema = $this->_em->getConnection()->getSchemaManager()->createSchema();
$this->assertTrue($schema->hasTable('company_contracts'));
return $schema;
}
/**
* @group DDC-966
* @depends testGeneratedSchema
*/
public function testSingleTableInheritance(Schema $schema)
{
$table = $schema->getTable('company_contracts');
// Check nullability constraints
$this->assertTrue($table->getColumn('id')->getNotnull());
$this->assertTrue($table->getColumn('completed')->getNotnull());
$this->assertFalse($table->getColumn('salesPerson_id')->getNotnull());
$this->assertTrue($table->getColumn('discr')->getNotnull());
$this->assertFalse($table->getColumn('fixPrice')->getNotnull());
$this->assertFalse($table->getColumn('hoursWorked')->getNotnull());
$this->assertFalse($table->getColumn('pricePerHour')->getNotnull());
$this->assertFalse($table->getColumn('maxPrice')->getNotnull());
}
/**
* @group DBAL-115
*/
public function testDropPartSchemaWithForeignKeys()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) {
$this->markTestSkipped("Foreign Key test");
}
$sql = $this->_schemaTool->getDropSchemaSQL(array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyManager'),
));
$this->assertEquals(4, count($sql));
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Doctrine\Tests\ORM\Functional\SchemaTool;
use Doctrine\ORM\Tools;
require_once __DIR__ . '/../../../TestInit.php';
/**
* WARNING: This test should be run as last test! It can affect others very easily!
*/
class DDC214Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $classes = array();
private $schemaTool = null;
public function setUp() {
parent::setUp();
$conn = $this->_em->getConnection();
if (strpos($conn->getDriver()->getName(), "sqlite") !== false) {
$this->markTestSkipped('SQLite does not support ALTER TABLE statements.');
}
$this->schemaTool = new Tools\SchemaTool($this->_em);
}
/**
* @group DDC-214
*/
public function testCmsAddressModel()
{
$this->classes = array(
'Doctrine\Tests\Models\CMS\CmsUser',
'Doctrine\Tests\Models\CMS\CmsPhonenumber',
'Doctrine\Tests\Models\CMS\CmsAddress',
'Doctrine\Tests\Models\CMS\CmsGroup',
'Doctrine\Tests\Models\CMS\CmsArticle'
);
$this->assertCreatedSchemaNeedsNoUpdates($this->classes);
}
/**
* @group DDC-214
*/
public function testCompanyModel()
{
$this->classes = array(
'Doctrine\Tests\Models\Company\CompanyPerson',
'Doctrine\Tests\Models\Company\CompanyEmployee',
'Doctrine\Tests\Models\Company\CompanyManager',
'Doctrine\Tests\Models\Company\CompanyOrganization',
'Doctrine\Tests\Models\Company\CompanyEvent',
'Doctrine\Tests\Models\Company\CompanyAuction',
'Doctrine\Tests\Models\Company\CompanyRaffle',
'Doctrine\Tests\Models\Company\CompanyCar'
);
$this->assertCreatedSchemaNeedsNoUpdates($this->classes);
}
public function assertCreatedSchemaNeedsNoUpdates($classes)
{
$classMetadata = array();
foreach ($classes AS $class) {
$classMetadata[] = $this->_em->getClassMetadata($class);
}
try {
$this->schemaTool->createSchema($classMetadata);
} catch(\Exception $e) {
// was already created
}
$sm = $this->_em->getConnection()->getSchemaManager();
$fromSchema = $sm->createSchema();
$toSchema = $this->schemaTool->getSchemaFromMetadata($classMetadata);
$comparator = new \Doctrine\DBAL\Schema\Comparator();
$schemaDiff = $comparator->compare($fromSchema, $toSchema);
$sql = $schemaDiff->toSql($this->_em->getConnection()->getDatabasePlatform());
$sql = array_filter($sql, function($sql) { return strpos($sql, 'DROP') === false; });
$this->assertEquals(0, count($sql), "SQL: " . implode(PHP_EOL, $sql));
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Doctrine\Tests\ORM\Functional\SchemaTool;
use Doctrine\ORM\Tools\SchemaTool,
Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../../TestInit.php';
class MySqlSchemaToolTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
if ($this->_em->getConnection()->getDatabasePlatform()->getName() !== 'mysql') {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of mysql.');
}
}
public function testGetCreateSchemaSql()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'),
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals("CREATE TABLE cms_addresses (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, UNIQUE INDEX UNIQ_ACAC157BA76ED395 (user_id), PRIMARY KEY(id)) ENGINE = InnoDB", $sql[0]);
$this->assertEquals("CREATE TABLE cms_users (id INT AUTO_INCREMENT NOT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, email_id INT DEFAULT NULL, UNIQUE INDEX UNIQ_3AF03EC5F85E0677 (username), UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 (email_id), PRIMARY KEY(id)) ENGINE = InnoDB", $sql[1]);
$this->assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_7EA9409AA76ED395 (user_id), INDEX IDX_7EA9409AFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) ENGINE = InnoDB", $sql[2]);
$this->assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_F21F790FA76ED395 (user_id), PRIMARY KEY(phonenumber)) ENGINE = InnoDB", $sql[3]);
$this->assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[4]);
$this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[5]);
$this->assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[6]);
$this->assertEquals(7, count($sql));
}
public function testGetCreateSchemaSql2()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\DecimalModel')
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals(1, count($sql));
$this->assertEquals("CREATE TABLE decimal_model (id INT AUTO_INCREMENT NOT NULL, `decimal` NUMERIC(5, 2) NOT NULL, `high_scale` NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB", $sql[0]);
}
public function testGetCreateSchemaSql3()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\BooleanModel')
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals(1, count($sql));
$this->assertEquals("CREATE TABLE boolean_model (id INT AUTO_INCREMENT NOT NULL, booleanField TINYINT(1) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB", $sql[0]);
}
/**
* @group DBAL-204
*/
public function testGetCreateSchemaSql4()
{
$classes = array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\MysqlSchemaNamespacedEntity')
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals(0, count($sql));
}
}
/**
* @Entity
* @Table("namespace.entity")
*/
class MysqlSchemaNamespacedEntity
{
/** @Column(type="integer") @Id @GeneratedValue */
public $id;
}

View File

@@ -0,0 +1,108 @@
<?php
namespace Doctrine\Tests\ORM\Functional\SchemaTool;
use Doctrine\ORM\Tools\SchemaTool,
Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../../TestInit.php';
class PostgreSqlSchemaToolTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
if ($this->_em->getConnection()->getDatabasePlatform()->getName() !== 'postgresql') {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of postgresql.');
}
}
public function testPostgresMetadataSequenceIncrementedBy10()
{
$address = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress');
$this->assertEquals(1, $address->sequenceGeneratorDefinition['allocationSize']);
}
public function testGetCreateSchemaSql()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'),
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$sqlCount = count($sql);
$this->assertEquals("CREATE TABLE cms_addresses (id INT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, PRIMARY KEY(id))", array_shift($sql));
$this->assertEquals("CREATE UNIQUE INDEX UNIQ_ACAC157BA76ED395 ON cms_addresses (user_id)", array_shift($sql));
$this->assertEquals("CREATE TABLE cms_users (id INT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))", array_shift($sql));
$this->assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5F85E0677 ON cms_users (username)", array_shift($sql));
$this->assertEquals("CREATE UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 ON cms_users (email_id)", array_shift($sql));
$this->assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, PRIMARY KEY(user_id, group_id))", array_shift($sql));
$this->assertEquals("CREATE INDEX IDX_7EA9409AA76ED395 ON cms_users_groups (user_id)", array_shift($sql));
$this->assertEquals("CREATE INDEX IDX_7EA9409AFE54D947 ON cms_users_groups (group_id)", array_shift($sql));
$this->assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, PRIMARY KEY(phonenumber))", array_shift($sql));
$this->assertEquals("CREATE INDEX IDX_F21F790FA76ED395 ON cms_phonenumbers (user_id)", array_shift($sql));
$this->assertEquals("CREATE SEQUENCE cms_addresses_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql));
$this->assertEquals("CREATE SEQUENCE cms_users_id_seq INCREMENT BY 1 MINVALUE 1 START 1", array_shift($sql));
$this->assertEquals("ALTER TABLE cms_addresses ADD CONSTRAINT FK_ACAC157BA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql));
$this->assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql));
$this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql));
$this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql));
$this->assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql));
$this->assertEquals(array(), $sql, "SQL Array should be empty now.");
$this->assertEquals(17, $sqlCount, "Total of 17 queries should be executed");
}
public function testGetCreateSchemaSql2()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\DecimalModel')
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals(2, count($sql));
$this->assertEquals('CREATE TABLE decimal_model (id INT NOT NULL, "decimal" NUMERIC(5, 2) NOT NULL, "high_scale" NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id))', $sql[0]);
$this->assertEquals("CREATE SEQUENCE decimal_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]);
}
public function testGetCreateSchemaSql3()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\BooleanModel')
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getCreateSchemaSql($classes);
$this->assertEquals(2, count($sql));
$this->assertEquals("CREATE TABLE boolean_model (id INT NOT NULL, booleanField BOOLEAN NOT NULL, PRIMARY KEY(id))", $sql[0]);
$this->assertEquals("CREATE SEQUENCE boolean_model_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[1]);
}
public function testGetDropSchemaSql()
{
$classes = array(
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'),
$this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'),
);
$tool = new SchemaTool($this->_em);
$sql = $tool->getDropSchemaSQL($classes);
$this->assertEquals(14, count($sql));
$dropSequenceSQLs = 0;
foreach ($sql AS $stmt) {
if (strpos($stmt, "DROP SEQUENCE") === 0) {
$dropSequenceSQLs++;
}
}
$this->assertEquals(4, $dropSequenceSQLs, "Expect 4 sequences to be dropped.");
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Tools\SchemaValidator;
/**
* Test the validity of all modelsets
*
* @group DDC-1601
*/
class SchemaValidatorTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
static public function dataValidateModelSets()
{
$modelSets = array();
foreach (self::$_modelSets as $modelSet => $classes) {
if ($modelSet == "customtype") {
continue;
}
$modelSets[] = array($modelSet);
}
return $modelSets;
}
/**
* @dataProvider dataValidateModelSets
*/
public function testValidateModelSets($modelSet)
{
$validator = new SchemaValidator($this->_em);
$classes = array();
foreach (self::$_modelSets[$modelSet] as $className) {
$classes[] = $this->_em->getClassMetadata($className);
}
foreach ($classes as $class) {
$ce = $validator->validateClass($class);
foreach ($ce as $key => $error) {
if (strpos($error, "must be private or protected. Public fields may break lazy-loading.") !== false) {
unset($ce[$key]);
}
}
$this->assertEquals(0, count($ce), "Invalid Modelset: " . $modelSet . " class " . $class->name . ": ". implode("\n", $ce));
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
require_once __DIR__ . '/../../TestInit.php';
/**
* Description of SequenceGeneratorTest
*
* @author robo
*/
class SequenceGeneratorTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
if (!$this->_em->getConnection()->getDatabasePlatform()->supportsSequences()) {
$this->markTestSkipped('Only working for Databases that support sequences.');
}
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\SequenceEntity'),
));
} catch(\Exception $e) {
}
}
public function testHighAllocationSizeSequence()
{
for ($i = 0; $i < 11; $i++) {
$e = new SequenceEntity();
$this->_em->persist($e);
}
$this->_em->flush();
}
}
/**
* @Entity
*/
class SequenceEntity
{
/**
* @Id
* @column(type="integer")
* @GeneratedValue(strategy="SEQUENCE")
* @SequenceGenerator(allocationSize=5,sequenceName="person_id_seq")
*/
public $id;
}

View File

@@ -0,0 +1,370 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Mapping\ClassMetadata;
require_once __DIR__ . '/../../TestInit.php';
class SingleTableInheritanceTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $salesPerson;
private $engineers = array();
private $fix;
private $flex;
private $ultra;
public function setUp()
{
$this->useModelSet('company');
parent::setUp();
}
public function persistRelatedEmployees()
{
$this->salesPerson = new \Doctrine\Tests\Models\Company\CompanyEmployee();
$this->salesPerson->setName('Poor Sales Guy');
$this->salesPerson->setDepartment('Sales');
$this->salesPerson->setSalary(100);
$engineer1 = new \Doctrine\Tests\Models\Company\CompanyEmployee();
$engineer1->setName('Roman B.');
$engineer1->setDepartment('IT');
$engineer1->setSalary(100);
$this->engineers[] = $engineer1;
$engineer2 = new \Doctrine\Tests\Models\Company\CompanyEmployee();
$engineer2->setName('Jonathan W.');
$engineer2->setDepartment('IT');
$engineer2->setSalary(100);
$this->engineers[] = $engineer2;
$engineer3 = new \Doctrine\Tests\Models\Company\CompanyEmployee();
$engineer3->setName('Benjamin E.');
$engineer3->setDepartment('IT');
$engineer3->setSalary(100);
$this->engineers[] = $engineer3;
$engineer4 = new \Doctrine\Tests\Models\Company\CompanyEmployee();
$engineer4->setName('Guilherme B.');
$engineer4->setDepartment('IT');
$engineer4->setSalary(100);
$this->engineers[] = $engineer4;
$this->_em->persist($this->salesPerson);
$this->_em->persist($engineer1);
$this->_em->persist($engineer2);
$this->_em->persist($engineer3);
$this->_em->persist($engineer4);
}
public function loadFullFixture()
{
$this->persistRelatedEmployees();
$this->fix = new \Doctrine\Tests\Models\Company\CompanyFixContract();
$this->fix->setFixPrice(1000);
$this->fix->setSalesPerson($this->salesPerson);
$this->fix->addEngineer($this->engineers[0]);
$this->fix->addEngineer($this->engineers[1]);
$this->fix->markCompleted();
$this->flex = new \Doctrine\Tests\Models\Company\CompanyFlexContract();
$this->flex->setSalesPerson($this->salesPerson);
$this->flex->setHoursWorked(100);
$this->flex->setPricePerHour(100);
$this->flex->addEngineer($this->engineers[2]);
$this->flex->addEngineer($this->engineers[1]);
$this->flex->addEngineer($this->engineers[3]);
$this->flex->markCompleted();
$this->ultra = new \Doctrine\Tests\Models\Company\CompanyFlexUltraContract();
$this->ultra->setSalesPerson($this->salesPerson);
$this->ultra->setHoursWorked(150);
$this->ultra->setPricePerHour(150);
$this->ultra->setMaxPrice(7000);
$this->ultra->addEngineer($this->engineers[3]);
$this->ultra->addEngineer($this->engineers[0]);
$this->_em->persist($this->fix);
$this->_em->persist($this->flex);
$this->_em->persist($this->ultra);
$this->_em->flush();
$this->_em->clear();
}
public function testPersistChildOfBaseClass()
{
$this->persistRelatedEmployees();
$fixContract = new \Doctrine\Tests\Models\Company\CompanyFixContract();
$fixContract->setFixPrice(1000);
$fixContract->setSalesPerson($this->salesPerson);
$this->_em->persist($fixContract);
$this->_em->flush();
$this->_em->clear();
$contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFixContract', $fixContract->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract);
$this->assertEquals(1000, $contract->getFixPrice());
$this->assertEquals($this->salesPerson->getId(), $contract->getSalesPerson()->getId());
}
public function testPersistDeepChildOfBaseClass()
{
$this->persistRelatedEmployees();
$ultraContract = new \Doctrine\Tests\Models\Company\CompanyFlexUltraContract();
$ultraContract->setSalesPerson($this->salesPerson);
$ultraContract->setHoursWorked(100);
$ultraContract->setPricePerHour(50);
$ultraContract->setMaxPrice(7000);
$this->_em->persist($ultraContract);
$this->_em->flush();
$this->_em->clear();
$contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $ultraContract->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $contract);
$this->assertEquals(7000, $contract->getMaxPrice());
$this->assertEquals(100, $contract->getHoursWorked());
$this->assertEquals(50, $contract->getPricePerHour());
}
public function testChildClassLifecycleUpdate()
{
$this->loadFullFixture();
$fix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId());
$fix->setFixPrice(2500);
$this->_em->flush();
$this->_em->clear();
$newFix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId());
$this->assertEquals(2500, $newFix->getFixPrice());
}
public function testChildClassLifecycleRemove()
{
$this->loadFullFixture();
$fix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId());
$this->_em->remove($fix);
$this->_em->flush();
$this->assertNull($this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()));
}
public function testFindAllForAbstractBaseClass()
{
$this->loadFullFixture();
$contracts = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyContract')->findAll();
$this->assertEquals(3, count($contracts));
$this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts);
}
public function testFindAllForChildClass()
{
$this->loadFullFixture();
$this->assertEquals(1, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFixContract')->findAll()));
$this->assertEquals(2, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexContract')->findAll()));
$this->assertEquals(1, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexUltraContract')->findAll()));
}
public function testFindForAbstractBaseClass()
{
$this->loadFullFixture();
$contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract);
$this->assertEquals(1000, $contract->getFixPrice());
}
public function testQueryForAbstractBaseClass()
{
$this->loadFullFixture();
$contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult();
$this->assertEquals(3, count($contracts));
$this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts);
}
public function testQueryForChildClass()
{
$this->loadFullFixture();
$this->assertEquals(1, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c')->getResult()));
$this->assertEquals(2, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexContract c')->getResult()));
$this->assertEquals(1, count($this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract c')->getResult()));
}
public function testQueryBaseClassWithJoin()
{
$this->loadFullFixture();
$contracts = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson p')->getResult();
$this->assertEquals(3, count($contracts));
$this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts);
}
public function testQueryScalarWithDiscrimnatorValue()
{
$this->loadFullFixture();
$contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c ORDER BY c.id')->getScalarResult();
$discrValues = \array_map(function($a) {
return $a['c_discr'];
}, $contracts);
sort($discrValues);
$this->assertEquals(array('fix', 'flexible', 'flexultra'), $discrValues);
}
public function testQueryChildClassWithCondition()
{
$this->loadFullFixture();
$dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c WHERE c.fixPrice = ?1';
$contract = $this->_em->createQuery($dql)->setParameter(1, 1000)->getSingleResult();
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract);
$this->assertEquals(1000, $contract->getFixPrice());
}
public function testUpdateChildClassWithCondition()
{
$this->loadFullFixture();
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyFlexContract c SET c.hoursWorked = c.hoursWorked * 2 WHERE c.hoursWorked = 150';
$affected = $this->_em->createQuery($dql)->execute();
$this->assertEquals(1, $affected);
$flexContract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->flex->getId());
$ultraContract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->ultra->getId());
$this->assertEquals(300, $ultraContract->getHoursWorked());
$this->assertEquals(100, $flexContract->getHoursWorked());
}
public function testUpdateBaseClassWithCondition()
{
$this->loadFullFixture();
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = true WHERE c.completed = false';
$affected = $this->_em->createQuery($dql)->execute();
$this->assertEquals(1, $affected);
$dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyContract c SET c.completed = false';
$affected = $this->_em->createQuery($dql)->execute();
$this->assertEquals(3, $affected);
}
public function testDeleteByChildClassCondition()
{
$this->loadFullFixture();
$dql = 'DELETE Doctrine\Tests\Models\Company\CompanyFlexContract c';
$affected = $this->_em->createQuery($dql)->execute();
$this->assertEquals(2, $affected);
}
public function testDeleteByBaseClassCondition()
{
$this->loadFullFixture();
$dql = "DELETE Doctrine\Tests\Models\Company\CompanyContract c WHERE c.completed = true";
$affected = $this->_em->createQuery($dql)->execute();
$this->assertEquals(2, $affected);
$contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult();
$this->assertEquals(1, count($contracts));
$this->assertFalse($contracts[0]->isCompleted(), "Only non completed contracts should be left.");
}
/**
* @group DDC-130
*/
public function testDeleteJoinTableRecords()
{
$this->loadFullFixture();
// remove managed copy of the fix contract
$this->_em->remove($this->_em->find(get_class($this->fix), $this->fix->getId()));
$this->_em->flush();
$this->assertNull($this->_em->find(get_class($this->fix), $this->fix->getId()), "Contract should not be present in the database anymore.");
}
/**
* @group DDC-817
*/
public function testFindByAssociation()
{
$this->loadFullFixture();
$repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyContract");
$contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId()));
$this->assertEquals(3, count($contracts), "There should be 3 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyContract'");
$repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFixContract");
$contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId()));
$this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFixContract'");
$repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFlexContract");
$contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId()));
$this->assertEquals(2, count($contracts), "There should be 2 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexContract'");
$repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFlexUltraContract");
$contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId()));
$this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexUltraContract'");
}
/**
* @group DDC-834
*/
public function testGetReferenceEntityWithSubclasses()
{
$this->loadFullFixture();
$ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId());
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "Cannot Request a proxy from a class that has subclasses.");
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyContract', $ref);
$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $ref, "Direct fetch of the reference has to load the child class Emplyoee directly.");
$this->_em->clear();
$ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyFixContract', $this->fix->getId());
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "A proxy can be generated only if no subclasses exists for the requested reference.");
}
/**
* @group DDC-952
*/
public function testEagerLoadInheritanceHierachy()
{
$this->loadFullFixture();
$dql = 'SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1';
$contract = $this->_em->createQuery($dql)
->setFetchMode('Doctrine\Tests\Models\Company\CompanyFixContract', 'salesPerson', ClassMetadata::FETCH_EAGER)
->setParameter(1, $this->fix->getId())
->getSingleResult();
$this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $contract->getSalesPerson());
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\ECommerce\ECommerceCart,
Doctrine\Tests\Models\ECommerce\ECommerceFeature,
Doctrine\Tests\Models\ECommerce\ECommerceCustomer,
Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\ORM\Mapping\AssociationMapping;
require_once __DIR__ . '/../../TestInit.php';
/**
* Tests capabilities of the persister.
* @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
*/
class StandardEntityPersisterTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('ecommerce');
parent::setUp();
}
public function testAcceptsForeignKeysAsCriteria()
{
$customer = new ECommerceCustomer();
$customer->setName('John Doe');
$cart = new ECommerceCart();
$cart->setPayment('Credit card');
$customer->setCart($cart);
$this->_em->persist($customer);
$this->_em->flush();
$this->_em->clear();
$cardId = $cart->getId();
unset($cart);
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart');
$persister = $this->_em->getUnitOfWork()->getEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceCart');
$newCart = new ECommerceCart();
$this->_em->getUnitOfWork()->registerManaged($newCart, array('id' => $cardId), array());
$persister->load(array('customer_id' => $customer->getId()), $newCart, $class->associationMappings['customer']);
$this->assertEquals('Credit card', $newCart->getPayment());
}
/**
* Ticket #2478 from Damon Jones (dljones)
*/
public function testAddPersistRetrieve()
{
$f1 = new ECommerceFeature;
$f1->setDescription('AC-3');
$f2 = new ECommerceFeature;
$f2->setDescription('DTS');
$p = new ECommerceProduct;
$p->addFeature($f1);
$p->addfeature($f2);
$this->_em->persist($p);
$this->_em->flush();
$this->assertEquals(2, count($p->getFeatures()));
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $p->getFeatures());
$q = $this->_em->createQuery(
'SELECT p, f
FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p
JOIN p.features f'
);
$res = $q->getResult();
$this->assertEquals(2, count($p->getFeatures()));
$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $p->getFeatures());
// Check that the features are the same instances still
foreach ($p->getFeatures() as $feature) {
if ($feature->getDescription() == 'AC-3') {
$this->assertTrue($feature === $f1);
} else {
$this->assertTrue($feature === $f2);
}
}
// Now we test how Hydrator affects IdentityMap
// (change from ArrayCollection to PersistentCollection)
$f3 = new ECommerceFeature();
$f3->setDescription('XVID');
$p->addFeature($f3);
// Now we persist the Feature #3
$this->_em->persist($p);
$this->_em->flush();
$q = $this->_em->createQuery(
'SELECT p, f
FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p
JOIN p.features f'
);
$res = $q->getResult();
// Persisted Product now must have 3 Feature items
$this->assertEquals(3, count($res[0]->getFeatures()));
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Tests\Models\CMS\CmsUser;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1040
*/
class DDC1040Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testReuseNamedEntityParameter()
{
$user = new CmsUser();
$user->name = "John Galt";
$user->username = "jgalt";
$user->status = "inactive";
$article = new CmsArticle();
$article->topic = "This is John Galt speaking!";
$article->text = "Yadda Yadda!";
$article->setAuthor($user);
$this->_em->persist($user);
$this->_em->persist($article);
$this->_em->flush();
$dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author";
$this->_em->createQuery($dql)
->setParameter('author', $user)
->getResult();
$dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = :author AND a.user = :author";
$this->_em->createQuery($dql)
->setParameter('author', $user)
->getResult();
$dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = :topic AND a.user = :author AND a.user = :author";
$farticle = $this->_em->createQuery($dql)
->setParameter('author', $user)
->setParameter('topic', 'This is John Galt speaking!')
->getSingleResult();
$this->assertSame($article, $farticle);
}
public function testUseMultiplePositionalParameters()
{
$user = new CmsUser();
$user->name = "John Galt";
$user->username = "jgalt";
$user->status = "inactive";
$article = new CmsArticle();
$article->topic = "This is John Galt speaking!";
$article->text = "Yadda Yadda!";
$article->setAuthor($user);
$this->_em->persist($user);
$this->_em->persist($article);
$this->_em->flush();
$dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = ?1 AND a.user = ?2 AND a.user = ?3";
$farticle = $this->_em->createQuery($dql)
->setParameter(1, 'This is John Galt speaking!')
->setParameter(2, $user)
->setParameter(3, $user)
->getSingleResult();
$this->assertSame($article, $farticle);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1041
*/
class DDC1041Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('company');
parent::setUp();
}
public function testGrabWrongSubtypeReturnsNull()
{
$fix = new \Doctrine\Tests\Models\Company\CompanyFixContract();
$fix->setFixPrice(2000);
$this->_em->persist($fix);
$this->_em->flush();
$id = $fix->getId();
$this->assertNull($this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexContract', $id));
$this->assertNull($this->_em->getReference('Doctrine\Tests\Models\Company\CompanyFlexContract', $id));
$this->assertNull($this->_em->getPartialReference('Doctrine\Tests\Models\Company\CompanyFlexContract', $id));
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1043
*/
class DDC1043Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testChangeSetPlusWeirdPHPCastingIntCastingRule()
{
$user = new \Doctrine\Tests\Models\CMS\CmsUser();
$user->name = "John Galt";
$user->username = "jgalt";
$user->status = "+44";
$this->_em->persist($user);
$this->_em->flush();
$user->status = "44";
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find("Doctrine\Tests\Models\CMS\CmsUser", $user->id);
$this->assertSame("44", $user->status);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1050
*/
class DDC1050Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->markTestSkipped('performance skipped');
$this->useModelSet('cms');
parent::setUp();
}
public function testPerformance()
{
for ($i = 2; $i < 10000; ++$i) {
$user = new \Doctrine\Tests\Models\CMS\CmsUser();
$user->status = 'developer';
$user->username = 'jwage'+$i;
$user->name = 'Jonathan';
$this->_em->persist($user);
}
$this->_em->flush();
$this->_em->clear();
$s = microtime(true);
$users = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll();
$e = microtime(true);
echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL;
}
}

View File

@@ -0,0 +1,317 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1080
*/
class DDC1080Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function testHydration()
{
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080Foo'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080Bar'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080FooBar'),
));
$foo1 = new DDC1080Foo();
$foo1->setFooTitle('foo title 1');
$foo2 = new DDC1080Foo();
$foo2->setFooTitle('foo title 2');
$bar1 = new DDC1080Bar();
$bar1->setBarTitle('bar title 1');
$bar2 = new DDC1080Bar();
$bar2->setBarTitle('bar title 2');
$bar3 = new DDC1080Bar();
$bar3->setBarTitle('bar title 3');
$foobar1 = new DDC1080FooBar();
$foobar1->setFoo($foo1);
$foobar1->setBar($bar1);
$foobar1->setOrderNr(0);
$foobar2 = new DDC1080FooBar();
$foobar2->setFoo($foo1);
$foobar2->setBar($bar2);
$foobar2->setOrderNr(0);
$foobar3 = new DDC1080FooBar();
$foobar3->setFoo($foo1);
$foobar3->setBar($bar3);
$foobar3->setOrderNr(0);
$this->_em->persist($foo1);
$this->_em->persist($foo2);
$this->_em->persist($bar1);
$this->_em->persist($bar2);
$this->_em->persist($bar3);
$this->_em->flush();
$this->_em->persist($foobar1);
$this->_em->persist($foobar2);
$this->_em->persist($foobar3);
$this->_em->flush();
$this->_em->clear();
$foo = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC1080Foo', $foo1->getFooId());
$fooBars = $foo->getFooBars();
$this->assertEquals(3, count($fooBars), "Should return three foobars.");
}
}
/**
* @Entity
* @Table(name="foo")
*/
class DDC1080Foo
{
/**
* @Id
* @Column(name="fooID", type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $_fooID;
/**
* @Column(name="fooTitle", type="string")
*/
protected $_fooTitle;
/**
* @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_foo",
* cascade={"persist"})
* @OrderBy({"_orderNr"="ASC"})
*/
protected $_fooBars;
public function __construct()
{
$this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @return the $fooID
*/
public function getFooID()
{
return $this->_fooID;
}
/**
* @return the $fooTitle
*/
public function getFooTitle()
{
return $this->_fooTitle;
}
/**
* @return the $fooBars
*/
public function getFooBars()
{
return $this->_fooBars;
}
/**
* @param field_type $fooID
*/
public function setFooID($fooID)
{
$this->_fooID = $fooID;
}
/**
* @param field_type $fooTitle
*/
public function setFooTitle($fooTitle)
{
$this->_fooTitle = $fooTitle;
}
/**
* @param field_type $fooBars
*/
public function setFooBars($fooBars)
{
$this->_fooBars = $fooBars;
}
}
/**
* @Entity
* @Table(name="bar")
*/
class DDC1080Bar
{
/**
* @Id
* @Column(name="barID", type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $_barID;
/**
* @Column(name="barTitle", type="string")
*/
protected $_barTitle;
/**
* @OneToMany(targetEntity="DDC1080FooBar", mappedBy="_bar",
* cascade={"persist"})
* @OrderBy({"_orderNr"="ASC"})
*/
protected $_fooBars;
public function __construct()
{
$this->_fooBars = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @return the $barID
*/
public function getBarID()
{
return $this->_barID;
}
/**
* @return the $barTitle
*/
public function getBarTitle()
{
return $this->_barTitle;
}
/**
* @return the $fooBars
*/
public function getFooBars()
{
return $this->_fooBars;
}
/**
* @param field_type $barID
*/
public function setBarID($barID)
{
$this->_barID = $barID;
}
/**
* @param field_type $barTitle
*/
public function setBarTitle($barTitle)
{
$this->_barTitle = $barTitle;
}
/**
* @param field_type $fooBars
*/
public function setFooBars($fooBars)
{
$this->_fooBars = $fooBars;
}
}
/**
* @Table(name="fooBar")
* @Entity
*/
class DDC1080FooBar
{
/**
* @ManyToOne(targetEntity="DDC1080Foo")
* @JoinColumn(name="fooID", referencedColumnName="fooID")
* @Id
*/
protected $_foo = null;
/**
* @ManyToOne(targetEntity="DDC1080Bar")
* @JoinColumn(name="barID", referencedColumnName="barID")
* @Id
*/
protected $_bar = null;
/**
* @var integer orderNr
* @Column(name="orderNr", type="integer", nullable=false)
*/
protected $_orderNr = null;
/**
* Retrieve the foo property
*
* @return DDC1080Foo
*/
public function getFoo()
{
return $this->_foo;
}
/**
* Set the foo property
*
* @param DDC1080Foo $foo
* @return DDC1080FooBar
*/
public function setFoo($foo)
{
$this->_foo = $foo;
return $this;
}
/**
* Retrieve the bar property
*
* @return DDC1080Bar
*/
public function getBar()
{
return $this->_bar;
}
/**
* Set the bar property
*
* @param DDC1080Bar $bar
* @return DDC1080FooBar
*/
public function setBar($bar)
{
$this->_bar = $bar;
return $this;
}
/**
* Retrieve the orderNr property
*
* @return integer|null
*/
public function getOrderNr()
{
return $this->_orderNr;
}
/**
* Set the orderNr property
*
* @param integer|null $orderNr
* @return DDC1080FooBar
*/
public function setOrderNr($orderNr)
{
$this->_orderNr = $orderNr;
return $this;
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1113
* @group DDC-1306
*/
class DDC1113Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Engine'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Vehicle'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Car'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Bus'),
));
} catch (\Exception $e) {
}
}
public function testIssue()
{
$car = new DDC1113Car();
$car->engine = new DDC1113Engine();
$bus = new DDC1113Bus();
$bus->engine = new DDC1113Engine();
$this->_em->persist($car);
$this->_em->flush();
$this->_em->persist($bus);
$this->_em->flush();
$this->_em->remove($bus);
$this->_em->remove($car);
$this->_em->flush();
}
}
/**
* @Entity
* @InheritanceType("SINGLE_TABLE")
* @DiscriminatorMap({"car" = "DDC1113Car", "bus" = "DDC1113Bus"})
*/
class DDC1113Vehicle
{
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
/**
* @ManyToOne(targetEntity="DDC1113Vehicle")
*/
public $parent;
/** @OneToOne(targetEntity="DDC1113Engine", cascade={"persist", "remove"}) */
public $engine;
}
/**
* @Entity
*/
class DDC1113Car extends DDC1113Vehicle
{
}
/**
* @Entity
*/
class DDC1113Bus extends DDC1113Vehicle
{
}
/**
* @Entity
*/
class DDC1113Engine
{
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1129
*/
class DDC1129Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testVersionFieldIgnoredInChangesetComputation()
{
$article = new \Doctrine\Tests\Models\CMS\CmsArticle();
$article->text = "I don't know.";
$article->topic = "Who is John Galt?";
$this->_em->persist($article);
$this->_em->flush();
$this->assertEquals(1, $article->version);
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsArticle');
$uow = $this->_em->getUnitOfWork();
$uow->computeChangeSet($class, $article);
$changeSet = $uow->getEntityChangeSet($article);
$this->assertEquals(0, count($changeSet), "No changesets should be computed.");
$article->text = "This is John Galt speaking.";
$this->_em->flush();
$this->assertEquals(2, $article->version);
$uow->computeChangeSet($class, $article);
$changeSet = $uow->getEntityChangeSet($article);
$this->assertEquals(0, count($changeSet), "No changesets should be computed.");
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1151
*/
class DDC1151Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function testQuoteForeignKey()
{
if ($this->_em->getConnection()->getDatabasePlatform()->getName() != 'postgresql') {
$this->markTestSkipped("This test is useful for all databases, but designed only for postgresql.");
}
$sql = $this->_schemaTool->getCreateSchemaSql(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1151User'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1151Group'),
));
$this->assertEquals("CREATE TABLE \"User\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[0]);
$this->assertEquals("CREATE TABLE ddc1151user_ddc1151group (ddc1151user_id INT NOT NULL, ddc1151group_id INT NOT NULL, PRIMARY KEY(ddc1151user_id, ddc1151group_id))", $sql[1]);
$this->assertEquals("CREATE INDEX IDX_88A3259AC5AD08A ON ddc1151user_ddc1151group (ddc1151user_id)", $sql[2]);
$this->assertEquals("CREATE INDEX IDX_88A32597357E0B1 ON ddc1151user_ddc1151group (ddc1151group_id)", $sql[3]);
$this->assertEquals("CREATE TABLE \"Group\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[4]);
$this->assertEquals("CREATE SEQUENCE User_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[5]);
$this->assertEquals("CREATE SEQUENCE Group_id_seq INCREMENT BY 1 MINVALUE 1 START 1", $sql[6]);
$this->assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A3259AC5AD08A FOREIGN KEY (ddc1151user_id) REFERENCES \"User\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[7]);
$this->assertEquals("ALTER TABLE ddc1151user_ddc1151group ADD CONSTRAINT FK_88A32597357E0B1 FOREIGN KEY (ddc1151group_id) REFERENCES \"Group\" (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE", $sql[8]);
}
}
/**
* @Entity
* @Table(name="`User`")
*/
class DDC1151User
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/** @ManyToMany(targetEntity="DDC1151Group") */
public $groups;
}
/**
* @Entity
* @Table(name="`Group`")
*/
class DDC1151Group
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
}

View File

@@ -0,0 +1,215 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1163
*/
class DDC1163Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163Product'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163SpecialProduct'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163ProxyHolder'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163Tag'),
));
}
public function testIssue()
{
$this->createSpecialProductAndProxyHolderReferencingIt();
$this->_em->clear();
$this->createProxyForSpecialProduct();
$this->setPropertyAndAssignTagToSpecialProduct();
// fails
$this->_em->flush();
}
private function createSpecialProductAndProxyHolderReferencingIt()
{
$specialProduct = new DDC1163SpecialProduct();
$this->_em->persist($specialProduct);
$proxyHolder = new DDC1163ProxyHolder();
$this->_em->persist($proxyHolder);
$proxyHolder->setSpecialProduct($specialProduct);
$this->_em->flush();
$this->productId = $specialProduct->getId();
$this->proxyHolderId = $proxyHolder->getId();
}
/**
* We want Doctrine to instantiate a lazy-load proxy for the previously created
* 'SpecialProduct' and register it.
*
* When Doctrine loads the 'ProxyHolder', it will do just that because the 'ProxyHolder'
* references the 'SpecialProduct'.
*/
private function createProxyForSpecialProduct()
{
/* @var $proxyHolder ProxyHolder */
$proxyHolder = $this->_em->find(__NAMESPACE__ . '\\DDC1163ProxyHolder', $this->proxyHolderId);
$this->assertInstanceOf(__NAMESPACE__.'\\DDC1163SpecialProduct', $proxyHolder->getSpecialProduct());
}
private function setPropertyAndAssignTagToSpecialProduct()
{
/* @var $specialProduct SpecialProduct */
$specialProduct = $this->_em->find(__NAMESPACE__ . '\\DDC1163SpecialProduct', $this->productId);
$this->assertInstanceOf(__NAMESPACE__.'\\DDC1163SpecialProduct', $specialProduct);
$this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $specialProduct);
$specialProduct->setSubclassProperty('foobar');
// this screams violation of law of demeter ;)
$this->assertEquals(
__NAMESPACE__.'\\DDC1163SpecialProduct',
$this->_em->getUnitOfWork()->getEntityPersister(get_class($specialProduct))->getClassMetadata()->name
);
$tag = new DDC1163Tag('Foo');
$this->_em->persist($tag);
$tag->setProduct($specialProduct);
}
}
/**
* @Entity
*/
class DDC1163ProxyHolder
{
/**
* @var int
* @Column(name="id", type="integer")
* @Id
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var SpecialProduct
* @OneToOne(targetEntity="DDC1163SpecialProduct")
*/
private $specialProduct;
public function getId()
{
return $this->id;
}
public function setSpecialProduct(DDC1163SpecialProduct $specialProduct)
{
$this->specialProduct = $specialProduct;
}
public function getSpecialProduct()
{
return $this->specialProduct;
}
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="type", type="string")
* @DiscriminatorMap({"special" = "DDC1163SpecialProduct"})
*/
abstract class DDC1163Product
{
/**
* @var int
* @Column(name="id", type="integer")
* @Id
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
public function getId()
{
return $this->id;
}
}
/**
* @Entity
*/
class DDC1163SpecialProduct extends DDC1163Product
{
/**
* @var string
* @Column(name="subclass_property", type="string", nullable=true)
*/
private $subclassProperty;
/**
* @param string $value
*/
public function setSubclassProperty($value)
{
$this->subclassProperty = $value;
}
}
/**
* @Entity
*/
class DDC1163Tag
{
/**
* @var int
* @Column(name="id", type="integer")
* @Id
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @Column(name="name", type="string")
*/
private $name;
/**
* @var Product
* @ManyToOne(targetEntity="DDC1163Product", inversedBy="tags")
* @JoinColumns({
* @JoinColumn(name="product_id", referencedColumnName="id")
* })
*/
private $product;
/**
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* @param Product $product
*/
public function setProduct(DDC1163Product $product)
{
$this->product = $product;
}
}

View File

@@ -0,0 +1,464 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Tests\Models\DDC117\DDC117ArticleDetails;
use Doctrine\Tests\Models\DDC117\DDC117Article;
use Doctrine\Tests\Models\DDC117\DDC117Reference;
use Doctrine\Tests\Models\DDC117\DDC117Translation;
use Doctrine\Tests\Models\DDC117\DDC117ApproveChanges;
use Doctrine\Tests\Models\DDC117\DDC117Editor;
require_once __DIR__ . '/../../../TestInit.php';
class DDC117Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $article1;
private $article2;
private $reference;
private $translation;
private $articleDetails;
protected function setUp() {
$this->useModelSet('ddc117');
parent::setUp();
$this->article1 = new DDC117Article("Foo");
$this->article2 = new DDC117Article("Bar");
$this->_em->persist($this->article1);
$this->_em->persist($this->article2);
$this->_em->flush();
$this->reference = new DDC117Reference($this->article1, $this->article2, "Test-Description");
$this->_em->persist($this->reference);
$this->translation = new DDC117Translation($this->article1, "en", "Bar");
$this->_em->persist($this->translation);
$this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text");
$this->_em->persist($this->articleDetails);
$this->_em->flush();
$this->_em->clear();
}
/**
* @group DDC-117
*/
public function testAssociationOnlyCompositeKey()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $mapRef);
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->target());
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->source());
$this->assertSame($mapRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria));
$this->_em->clear();
$dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE r.source = ?1";
$dqlRef = $this->_em->createQuery($dql)->setParameter(1, 1)->getSingleResult();
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $mapRef);
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->target());
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->source());
$this->assertSame($dqlRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria));
$this->_em->clear();
$dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1";
$dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult();
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $dqlRef);
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $dqlRef->target());
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $dqlRef->source());
$this->assertSame($dqlRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria));
$dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1";
$dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult();
$this->_em->contains($dqlRef);
}
/**
* @group DDC-117
*/
public function testUpdateAssocationEntity()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$this->assertNotNull($mapRef);
$mapRef->setDescription("New Description!!");
$this->_em->flush();
$this->_em->clear();
$mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$this->assertEquals('New Description!!', $mapRef->getDescription());
}
/**
* @group DDC-117
*/
public function testFetchDql()
{
$dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1";
$refs = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getResult();
$this->assertTrue(count($refs) > 0, "Has to contain at least one Reference.");
foreach ($refs AS $ref) {
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $ref, "Contains only Reference instances.");
$this->assertTrue($this->_em->contains($ref), "Contains Reference in the IdentityMap.");
}
}
/**
* @group DDC-117
*/
public function testRemoveCompositeElement()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$refRep = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$this->_em->remove($refRep);
$this->_em->flush();
$this->_em->clear();
$this->assertNull($this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria));
}
/**
* @group DDC-117
*/
public function testDqlRemoveCompositeElement()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$dql = "DELETE "."Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = ?1 AND r.target = ?2";
$this->_em->createQuery($dql)
->setParameter(1, $this->article1->id())
->setParameter(2, $this->article2->id())
->execute();
$this->assertNull($this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria));
}
/**
* @group DDC-117
*/
public function testInverseSideAccess()
{
$this->article1 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id());
$this->assertEquals(1, count($this->article1->references()));
foreach ($this->article1->references() AS $this->reference) {
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $this->reference);
$this->assertSame($this->article1, $this->reference->source());
}
$this->_em->clear();
$dql = 'SELECT a, r FROM '. 'Doctrine\Tests\Models\DDC117\DDC117Article a INNER JOIN a.references r WHERE a.id = ?1';
$articleDql = $this->_em->createQuery($dql)
->setParameter(1, $this->article1->id())
->getSingleResult();
$this->assertEquals(1, count($this->article1->references()));
foreach ($this->article1->references() AS $this->reference) {
$this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $this->reference);
$this->assertSame($this->article1, $this->reference->source());
}
}
/**
* @group DDC-117
*/
public function testMixedCompositeKey()
{
$idCriteria = array('article' => $this->article1->id(), 'language' => 'en');
$this->translation = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria);
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $this->translation);
$this->assertSame($this->translation, $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria));
$this->_em->clear();
$dql = 'SELECT t, a FROM ' . 'Doctrine\Tests\Models\DDC117\DDC117Translation t JOIN t.article a WHERE t.article = ?1 AND t.language = ?2';
$dqlTrans = $this->_em->createQuery($dql)
->setParameter(1, $this->article1->id())
->setParameter(2, 'en')
->getSingleResult();
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $this->translation);
}
/**
* @group DDC-117
*/
public function testMixedCompositeKeyViolateUniqueness()
{
$this->article1 = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Article', $this->article1->id());
$this->article1->addTranslation('en', 'Bar');
$this->article1->addTranslation('en', 'Baz');
$exceptionThrown = false;
try {
// exception depending on the underyling Database Driver
$this->_em->flush();
} catch(\Exception $e) {
$exceptionThrown = true;
}
$this->assertTrue($exceptionThrown, "The underlying database driver throws an exception.");
}
/**
* @group DDC-117
*/
public function testOneToOneForeignObjectId()
{
$this->article1 = new DDC117Article("Foo");
$this->_em->persist($this->article1);
$this->_em->flush();
$this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text");
$this->_em->persist($this->articleDetails);
$this->_em->flush();
$this->articleDetails->update("not so very long text!");
$this->_em->flush();
$this->_em->clear();
/* @var $article DDC117Article */
$article = $this->_em->find(get_class($this->article1), $this->article1->id());
$this->assertEquals('not so very long text!', $article->getText());
}
/**
* @group DDC-117
*/
public function testOneToOneCascadeRemove()
{
$article = $this->_em->find(get_class($this->article1), $this->article1->id());
$this->_em->remove($article);
$this->_em->flush();
$this->assertFalse($this->_em->contains($article->getDetails()));
}
/**
* @group DDC-117
*/
public function testOneToOneCascadePersist()
{
if (!$this->_em->getConnection()->getDatabasePlatform()->prefersSequences()) {
$this->markTestSkipped('Test only works with databases that prefer sequences as ID strategy.');
}
$this->article1 = new DDC117Article("Foo");
$this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text");
$this->_em->persist($this->article1);
$this->_em->flush();
}
/**
* @group DDC-117
*/
public function testReferencesToForeignKeyEntities()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$reference = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$idCriteria = array('article' => $this->article1->id(), 'language' => 'en');
$translation = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria);
$approveChanges = new DDC117ApproveChanges($reference->source()->getDetails(), $reference, $translation);
$this->_em->persist($approveChanges);
$this->_em->flush();
$this->_em->clear();
$approveChanges = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117ApproveChanges", $approveChanges->getId());
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails', $approveChanges->getArticleDetails());
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Reference', $approveChanges->getReference());
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $approveChanges->getTranslation());
}
/**
* @group DDC-117
*/
public function testLoadOneToManyCollectionOfForeignKeyEntities()
{
/* @var $article DDC117Article */
$article = $this->_em->find(get_class($this->article1), $this->article1->id());
$translations = $article->getTranslations();
$this->assertFalse($translations->isInitialized());
$this->assertContainsOnly('Doctrine\Tests\Models\DDC117\DDC117Translation', $translations);
$this->assertTrue($translations->isInitialized());
}
/**
* @group DDC-117
*/
public function testLoadManyToManyCollectionOfForeignKeyEntities()
{
$editor = $this->loadEditorFixture();
$this->assertFalse($editor->reviewingTranslations->isInitialized());
$this->assertContainsOnly("Doctrine\Tests\Models\DDC117\DDC117Translation", $editor->reviewingTranslations);
$this->assertTrue($editor->reviewingTranslations->isInitialized());
$this->_em->clear();
$dql = "SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE e.id = ?1";
$editor = $this->_em->createQuery($dql)->setParameter(1, $editor->id)->getSingleResult();
$this->assertTrue($editor->reviewingTranslations->isInitialized());
$this->assertContainsOnly("Doctrine\Tests\Models\DDC117\DDC117Translation", $editor->reviewingTranslations);
}
/**
* @group DDC-117
*/
public function testClearManyToManyCollectionOfForeignKeyEntities()
{
$editor = $this->loadEditorFixture();
$this->assertEquals(3, count($editor->reviewingTranslations));
$editor->reviewingTranslations->clear();
$this->_em->flush();
$this->_em->clear();
$editor = $this->_em->find(get_class($editor), $editor->id);
$this->assertEquals(0, count($editor->reviewingTranslations));
}
/**
* @group DDC-117
*/
public function testLoadInverseManyToManyCollection()
{
$editor = $this->loadEditorFixture();
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $editor->reviewingTranslations[0]);
$reviewedBy = $editor->reviewingTranslations[0]->getReviewedByEditors();
$this->assertEquals(1, count($reviewedBy));
$this->assertSame($editor, $reviewedBy[0]);
$this->_em->clear();
$dql = "SELECT t, e FROM Doctrine\Tests\Models\DDC117\DDC117Translation t ".
"JOIN t.reviewedByEditors e WHERE t.article = ?1 AND t.language = ?2";
$trans = $this->_em->createQuery($dql)
->setParameter(1, $this->translation->getArticleId())
->setParameter(2, $this->translation->getLanguage())
->getSingleResult();
$this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $trans);
$this->assertContainsOnly('Doctrine\Tests\Models\DDC117\DDC117Editor', $trans->reviewedByEditors);
$this->assertEquals(1, count($trans->reviewedByEditors));
}
/**
* @group DDC-117
*/
public function testLoadOneToManyOfSourceEntityWithAssociationIdentifier()
{
$editor = $this->loadEditorFixture();
$editor->addLastTranslation($editor->reviewingTranslations[0]);
$this->_em->flush();
$this->_em->clear();
$editor = $this->_em->find(get_class($editor), $editor->id);
$lastTranslatedBy = $editor->reviewingTranslations[0]->getLastTranslatedBy();
$lastTranslatedBy->count();
$this->assertEquals(1, count($lastTranslatedBy));
}
/**
* @return DDC117Editor
*/
private function loadEditorFixture()
{
$editor = new DDC117Editor("beberlei");
/* @var $article1 DDC117Article */
$article1 = $this->_em->find(get_class($this->article1), $this->article1->id());
foreach ($article1->getTranslations() AS $translation) {
$editor->reviewingTranslations[] = $translation;
}
/* @var $article2 DDC117Article */
$article2 = $this->_em->find(get_class($this->article2), $this->article2->id());
$article2->addTranslation("de", "Vanille-Krapferl"); // omnomnom
$article2->addTranslation("fr", "Sorry can't speak french!");
foreach ($article2->getTranslations() AS $translation) {
$this->_em->persist($translation); // otherwise persisting the editor won't work, reachability!
$editor->reviewingTranslations[] = $translation;
}
$this->_em->persist($editor);
$this->_em->flush();
$this->_em->clear();
return $this->_em->find(get_class($editor), $editor->id);
}
/**
* @group DDC-1519
*/
public function testMergeForeignKeyIdentifierEntity()
{
$idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id());
$refRep = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria);
$this->_em->detach($refRep);
$refRep = $this->_em->merge($refRep);
$this->assertEquals($this->article1->id(), $refRep->source()->id());
$this->assertEquals($this->article2->id(), $refRep->target()->id());
}
/**
* @group DDC-1652
*/
public function testArrayHydrationWithCompositeKey()
{
$dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t";
$before = count($this->_em->createQuery($dql)->getResult());
$this->article1 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id());
$this->article2 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article2->id());
$this->reference = new DDC117Reference($this->article2, $this->article1, "Test-Description");
$this->_em->persist($this->reference);
$this->reference = new DDC117Reference($this->article1, $this->article1, "Test-Description");
$this->_em->persist($this->reference);
$this->reference = new DDC117Reference($this->article2, $this->article2, "Test-Description");
$this->_em->persist($this->reference);
$this->_em->flush();
$dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t";
$data = $this->_em->createQuery($dql)->getArrayResult();
$this->assertEquals($before + 3, count($data));
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
class DDC1181Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Hotel'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Booking'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Room'),
));
}
/**
* @group DDC-1181
*/
public function testIssue()
{
$hotel = new DDC1181Hotel();
$room1 = new DDC1181Room();
$room2 = new DDC1181Room();
$this->_em->persist($hotel);
$this->_em->persist($room1);
$this->_em->persist($room2);
$this->_em->flush();
$booking1 = new DDC1181Booking;
$booking1->hotel = $hotel;
$booking1->room = $room1;
$booking2 = new DDC1181Booking;
$booking2->hotel = $hotel;
$booking2->room = $room2;
$hotel->bookings[] = $booking1;
$hotel->bookings[] = $booking2;
$this->_em->persist($booking1);
$this->_em->persist($booking2);
$this->_em->flush();
$this->_em->remove($hotel);
$this->_em->flush();
}
}
/**
* @Entity
*/
class DDC1181Hotel
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/**
* @oneToMany(targetEntity="DDC1181Booking", mappedBy="hotel", cascade={"remove"})
* @var Booking[]
*/
public $bookings;
}
/**
* @Entity
*/
class DDC1181Booking
{
/**
* @var Hotel
*
* @Id
* @ManyToOne(targetEntity="DDC1181Hotel", inversedBy="bookings")
* @JoinColumns({
* @JoinColumn(name="hotel_id", referencedColumnName="id")
* })
*/
public $hotel;
/**
* @var Room
*
* @Id
* @ManyToOne(targetEntity="DDC1181Room")
* @JoinColumns({
* @JoinColumn(name="room_id", referencedColumnName="id")
* })
*/
public $room;
}
/**
* @Entity
*/
class DDC1181Room
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
use DateTime, Doctrine\DBAL\Types\Type;
class DDC1193Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Company'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Person'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Account')
));
}
/**
* @group DDC-1193
*/
public function testIssue()
{
$company = new DDC1193Company();
$person = new DDC1193Person();
$account = new DDC1193Account();
$person->account = $account;
$person->company = $company;
$company->member = $person;
$this->_em->persist($company);
$this->_em->flush();
$companyId = $company->id;
$accountId = $account->id;
$this->_em->clear();
$company = $this->_em->find(get_class($company), $companyId);
$this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($company), "Company is in identity map.");
$this->assertFalse($company->member->__isInitialized__, "Pre-Condition");
$this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($company->member), "Member is in identity map.");
$this->_em->remove($company);
$this->_em->flush();
$this->assertEquals(count($this->_em->getRepository(get_class($account))->findAll()), 0);
}
}
/** @Entity */
class DDC1193Company {
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/** @OneToOne(targetEntity="DDC1193Person", cascade={"persist", "remove"}) */
public $member;
}
/** @Entity */
class DDC1193Person {
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @OneToOne(targetEntity="DDC1193Account", cascade={"persist", "remove"})
*/
public $account;
}
/** @Entity */
class DDC1193Account {
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
require_once __DIR__ . '/../../../TestInit.php';
class DDC1209Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_1'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_2'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_3')
));
} catch(\Exception $e) {
}
}
/**
* @group DDC-1209
*/
public function testIdentifierCanHaveCustomType()
{
$this->_em->persist(new DDC1209_3());
$this->_em->flush();
}
/**
* @group DDC-1209
*/
public function testCompositeIdentifierCanHaveCustomType()
{
$future1 = new DDC1209_1();
$this->_em->persist($future1);
$this->_em->flush();
$future2 = new DDC1209_2($future1);
$this->_em->persist($future2);
$this->_em->flush();
}
}
/**
* @Entity
*/
class DDC1209_1
{
/**
* @Id @GeneratedValue @Column(type="integer")
*/
private $id;
public function getId()
{
return $this->id;
}
}
/**
* @Entity
*/
class DDC1209_2
{
/**
* @Id
* @ManyToOne(targetEntity="DDC1209_1")
* @JoinColumn(referencedColumnName="id", nullable=false)
*/
private $future1;
/**
* @Id
* @Column(type="datetime", nullable=false)
*/
private $starting_datetime;
/**
* @Id
* @Column(type="datetime", nullable=false)
*/
private $during_datetime;
/**
* @Id
* @Column(type="datetime", nullable=false)
*/
private $ending_datetime;
public function __construct(DDC1209_1 $future1)
{
$this->future1 = $future1;
$this->starting_datetime = new DateTime2();
$this->during_datetime = new DateTime2();
$this->ending_datetime = new DateTime2();
}
}
/**
* @Entity
*/
class DDC1209_3
{
/**
* @Id
* @Column(type="datetime", name="somedate")
*/
private $date;
public function __construct()
{
$this->date = new DateTime2();
}
}
class DateTime2 extends \DateTime
{
public function __toString()
{
return $this->format('Y');
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsEmployee;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1225
*/
class DDC1225Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1225_TestEntity1'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1225_TestEntity2'),
));
} catch(\PDOException $e) {
}
}
public function testIssue()
{
$qb = $this->_em->createQueryBuilder();
$qb->from('Doctrine\Tests\ORM\Functional\Ticket\DDC1225_TestEntity1', 'te1')
->select('te1')
->where('te1.testEntity2 = ?1')
->setParameter(1, 0);
$this->assertEquals(
strtolower('SELECT t0_.test_entity2_id AS test_entity2_id0 FROM te1 t0_ WHERE t0_.test_entity2_id = ?'),
strtolower($qb->getQuery()->getSQL())
);
}
}
/**
* @Entity
* @Table(name="te1")
*/
class DDC1225_TestEntity1
{
/**
* @Id
* @ManyToOne(targetEntity="Doctrine\Tests\ORM\Functional\Ticket\DDC1225_TestEntity2")
* @JoinColumn(name="test_entity2_id", referencedColumnName="id", nullable=false)
*/
private $testEntity2;
/**
* @param DDC1225_TestEntity2 $testEntity2
*/
public function setTestEntity2(DDC1225_TestEntity2 $testEntity2)
{
$this->testEntity2 = $testEntity2;
}
/**
* @return DDC1225_TestEntity2
*/
public function getTestEntity2()
{
return $this->testEntity2;
}
}
/**
* @Entity
* @Table(name="te2")
*/
class DDC1225_TestEntity2
{
/**
* @Id
* @GeneratedValue(strategy="AUTO")
* @Column(type="integer")
*/
private $id;
}

View File

@@ -0,0 +1,136 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsEmployee;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1228
* @group DDC-1226
*/
class DDC1228Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1228User'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1228Profile'),
));
} catch(\Exception $e) {
}
}
public function testOneToOnePersist()
{
$user = new DDC1228User;
$profile = new DDC1228Profile();
$profile->name = "Foo";
$user->profile = $profile;
$this->_em->persist($user);
$this->_em->persist($profile);
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id);
$this->assertFalse($user->getProfile()->__isInitialized__, "Proxy is not initialized");
$user->getProfile()->setName("Bar");
$this->assertTrue($user->getProfile()->__isInitialized__, "Proxy is not initialized");
$this->assertEquals("Bar", $user->getProfile()->getName());
$this->assertEquals(array("id" => 1, "name" => "Foo"), $this->_em->getUnitOfWork()->getOriginalEntityData($user->getProfile()));
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id);
$this->assertEquals("Bar", $user->getProfile()->getName());
}
public function testRefresh()
{
$user = new DDC1228User;
$profile = new DDC1228Profile();
$profile->name = "Foo";
$user->profile = $profile;
$this->_em->persist($user);
$this->_em->persist($profile);
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1228User', $user->id);
$this->_em->refresh($user);
$user->name = "Baz";
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id);
$this->assertEquals("Baz", $user->name);
}
}
/**
* @Entity
*/
class DDC1228User
{
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
public $id;
/**
* @Column(type="string")
* @var string
*/
public $name = 'Bar';
/**
* @OneToOne(targetEntity="DDC1228Profile")
* @var Profile
*/
public $profile;
public function getProfile()
{
return $this->profile;
}
}
/**
* @Entity
*/
class DDC1228Profile
{
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
public $id;
/**
* @column(type="string")
* @var string
*/
public $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsEmployee;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1238
*/
class DDC1238Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1238User'),
));
} catch(\Exception $e) {
}
}
public function testIssue()
{
$user = new DDC1238User;
$user->setName("test");
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$userId = $user->getId();
$this->_em->clear();
$user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId);
$this->_em->clear();
$userId2 = $user->getId();
$this->assertEquals($userId, $userId2, "This proxy can still be initialized.");
}
public function testIssueProxyClear()
{
$user = new DDC1238User;
$user->setName("test");
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
// force proxy load, getId() doesn't work anymore
$user->getName();
$userId = $user->getId();
$this->_em->clear();
$user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId);
$this->_em->clear();
$user2 = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId);
// force proxy load, getId() doesn't work anymore
$user->getName();
$this->assertNull($user->getId(), "Now this is null, we already have a user instance of that type");
}
}
/**
* @Entity
*/
class DDC1238User
{
/** @Id @GeneratedValue @Column(type="integer") */
private $id;
/**
* @Column
* @var string
*/
private $name;
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsEmployee;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1250
*/
class DDC1250Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1250ClientHistory'),
));
} catch(\PDOException $e) {
}
}
public function testIssue()
{
$c1 = new DDC1250ClientHistory;
$c2 = new DDC1250ClientHistory;
$c1->declinedClientsHistory = $c2;
$c1->declinedBy = $c2;
$c2->declinedBy = $c1;
$c2->declinedClientsHistory= $c1;
$this->_em->persist($c1);
$this->_em->persist($c2);
$this->_em->flush();
$this->_em->clear();
$history = $this->_em->createQuery('SELECT h FROM ' . __NAMESPACE__ . '\\DDC1250ClientHistory h WHERE h.id = ?1')
->setParameter(1, $c2->id)->getSingleResult();
$this->assertInstanceOf(__NAMESPACE__ . '\\DDC1250ClientHistory', $history);
}
}
/**
* @Entity
*/
class DDC1250ClientHistory
{
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
/** @OneToOne(targetEntity="DDC1250ClientHistory", inversedBy="declinedBy")
* @JoinColumn(name="declined_clients_history_id", referencedColumnName="id")
*/
public $declinedClientsHistory;
/**
* @OneToOne(targetEntity="DDC1250ClientHistory", mappedBy="declinedClientsHistory")
* @var
*/
public $declinedBy;
}
/**
*
Entities\ClientsHistory:
type: entity
table: clients_history
fields:
id:
id: true
type: integer
unsigned: false
nullable: false
generator:
strategy: IDENTITY
[...skiped...]
oneToOne:
declinedClientsHistory:
targetEntity: Entities\ClientsHistory
joinColumn:
name: declined_clients_history_id
referencedColumnName: id
inversedBy: declinedBy
declinedBy:
targetEntity: Entities\ClientsHistory
mappedBy: declinedClientsHistory
lifecycleCallbacks: { }
repositoryClass: Entities\ClientsHistoryRepository
*/

View File

@@ -0,0 +1,50 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsGroup;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1276
*/
class DDC1276Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testIssue()
{
$user = new CmsUser();
$user->name = "Benjamin";
$user->username = "beberlei";
$user->status = "active";
$this->_em->persist($user);
for ($i = 0; $i < 2; $i++) {
$group = new CmsGroup();
$group->name = "group".$i;
$user->groups[] = $group;
$this->_em->persist($group);
}
$this->_em->flush();
$this->_em->clear();
$user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->id);
$cloned = clone $user;
$this->assertSame($user->groups, $cloned->groups);
$this->assertEquals(2, count($user->groups));
$this->_em->merge($cloned);
$this->assertEquals(2, count($user->groups));
$this->_em->flush();
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1300
*/
class DDC1300Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1300Foo'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1300FooLocale'),
));
}
public function testIssue()
{
$foo = new DDC1300Foo();
$foo->_fooReference = "foo";
$this->_em->persist($foo);
$this->_em->flush();
$locale = new DDC1300FooLocale();
$locale->_foo = $foo;
$locale->_locale = "en";
$locale->_title = "blub";
$this->_em->persist($locale);
$this->_em->flush();
$query = $this->_em->createQuery('SELECT f, fl FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1300Foo f JOIN f._fooLocaleRefFoo fl');
$result = $query->getResult();
$this->assertEquals(1, count($result));
}
}
/**
* @Entity
*/
class DDC1300Foo
{
/**
* @var integer fooID
* @Column(name="fooID", type="integer", nullable=false)
* @GeneratedValue(strategy="AUTO")
* @Id
*/
public $_fooID = null;
/**
* @var string fooReference
* @Column(name="fooReference", type="string", nullable=true, length=45)
*/
public $_fooReference = null;
/**
* @OneToMany(targetEntity="DDC1300FooLocale", mappedBy="_foo",
* cascade={"persist"})
*/
public $_fooLocaleRefFoo = null;
/**
* Constructor
*
* @param array|Zend_Config|null $options
* @return Bug_Model_Foo
*/
public function __construct($options = null)
{
$this->_fooLocaleRefFoo = new \Doctrine\Common\Collections\ArrayCollection();
}
}
/**
* @Entity
*/
class DDC1300FooLocale
{
/**
* @ManyToOne(targetEntity="DDC1300Foo")
* @JoinColumn(name="fooID", referencedColumnName="fooID")
* @Id
*/
public $_foo = null;
/**
* @var string locale
* @Column(name="locale", type="string", nullable=false, length=5)
* @Id
*/
public $_locale = null;
/**
* @var string title
* @Column(name="title", type="string", nullable=true, length=150)
*/
public $_title = null;
}

View File

@@ -0,0 +1,148 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @author asm89
*/
class DDC1301Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
private $userId;
public function setUp()
{
$this->useModelSet('legacy');
parent::setUp();
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Legacy\LegacyUser');
$class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY;
$this->loadFixture();
}
public function tearDown()
{
parent::tearDown();
$class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Legacy\LegacyUser');
$class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
$class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
$class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_LAZY;
}
public function testCountNotInitializesLegacyCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->_articles->isInitialized());
$this->assertEquals(2, count($user->_articles));
$this->assertFalse($user->_articles->isInitialized());
foreach ($user->_articles AS $article) { }
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration.");
}
public function testCountNotInitializesLegacyCollectionWithForeignIdentifier()
{
$user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->_references->isInitialized());
$this->assertEquals(2, count($user->_references));
$this->assertFalse($user->_references->isInitialized());
foreach ($user->_references AS $reference) { }
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration.");
}
public function testCountNotInitializesLegacyManyToManyCollection()
{
$user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId);
$queryCount = $this->getCurrentQueryCount();
$this->assertFalse($user->_cars->isInitialized());
$this->assertEquals(3, count($user->_cars));
$this->assertFalse($user->_cars->isInitialized());
foreach ($user->_cars AS $reference) { }
$this->assertEquals($queryCount + 2, $this->getCurrentQueryCount(), "Expecting two queries to be fired for count, then iteration.");
}
public function loadFixture()
{
$user1 = new \Doctrine\Tests\Models\Legacy\LegacyUser();
$user1->_username = "beberlei";
$user1->_name = "Benjamin";
$user1->_status = "active";
$user2 = new \Doctrine\Tests\Models\Legacy\LegacyUser();
$user2->_username = "jwage";
$user2->_name = "Jonathan";
$user2->_status = "active";
$user3 = new \Doctrine\Tests\Models\Legacy\LegacyUser();
$user3->_username = "romanb";
$user3->_name = "Roman";
$user3->_status = "active";
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->persist($user3);
$article1 = new \Doctrine\Tests\Models\Legacy\LegacyArticle();
$article1->_topic = "Test";
$article1->_text = "Test";
$article1->setAuthor($user1);
$article2 = new \Doctrine\Tests\Models\Legacy\LegacyArticle();
$article2->_topic = "Test";
$article2->_text = "Test";
$article2->setAuthor($user1);
$this->_em->persist($article1);
$this->_em->persist($article2);
$car1 = new \Doctrine\Tests\Models\Legacy\LegacyCar();
$car1->_description = "Test1";
$car2 = new \Doctrine\Tests\Models\Legacy\LegacyCar();
$car2->_description = "Test2";
$car3 = new \Doctrine\Tests\Models\Legacy\LegacyCar();
$car3->_description = "Test3";
$user1->addCar($car1);
$user1->addCar($car2);
$user1->addCar($car3);
$user2->addCar($car1);
$user3->addCar($car1);
$this->_em->persist($car1);
$this->_em->persist($car2);
$this->_em->persist($car3);
$this->_em->flush();
$detail1 = new \Doctrine\Tests\Models\Legacy\LegacyUserReference($user1, $user2, "foo");
$detail2 = new \Doctrine\Tests\Models\Legacy\LegacyUserReference($user1, $user3, "bar");
$this->_em->persist($detail1);
$this->_em->persist($detail2);
$this->_em->flush();
$this->_em->clear();
$this->userId = $user1->getId();
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsGroup;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1306
*/
class DDC1306Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
$this->useModelSet('cms');
parent::setUp();
}
public function testIssue()
{
$phone = new CmsPhonenumber();
$phone->phonenumber = "1234";
// puts user and phone into commit order calculator
$this->_em->persist($phone);
$this->_em->flush();
$address = new \Doctrine\Tests\Models\CMS\CmsAddress();
$address->city = "bonn";
$address->country = "Germany";
$address->street = "somestreet!";
$address->zip = 12345;
$this->_em->persist($address);
$user = new CmsUser();
$user->username = "beberlei";
$user->name = "benjamin";
$user->status = "active";
$user->setAddress($address);
// puts user and address into commit order calculator, but does not calculate user dependencies new
$this->_em->persist($user);
$this->_em->flush();
$this->_em->remove($user->getAddress());
$this->_em->remove($user);
$this->_em->flush();
}
}

View File

@@ -0,0 +1,218 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use DateTime;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1335
*/
class DDC1335Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1335User'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1335Phone'),
));
$this->loadFixture();
} catch(\Exception $e) {
}
}
public function testDql()
{
$dql = 'SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id';
$query = $this->_em->createQuery($dql);
$result = $query->getResult();
$this->assertEquals(sizeof($result), 3);
$this->assertArrayHasKey(1, $result);
$this->assertArrayHasKey(2, $result);
$this->assertArrayHasKey(3, $result);
$dql = 'SELECT u, p FROM '.__NAMESPACE__ . '\DDC1335User u INDEX BY u.email INNER JOIN u.phones p INDEX BY p.id';
$query = $this->_em->createQuery($dql);
$result = $query->getResult();
$this->assertEquals(sizeof($result), 3);
$this->assertArrayHasKey('foo@foo.com', $result);
$this->assertArrayHasKey('bar@bar.com', $result);
$this->assertArrayHasKey('foobar@foobar.com', $result);
$this->assertEquals(sizeof($result['foo@foo.com']->phones), 3);
$this->assertEquals(sizeof($result['bar@bar.com']->phones), 3);
$this->assertEquals(sizeof($result['foobar@foobar.com']->phones), 3);
$foo = $result['foo@foo.com']->phones->toArray();
$bar = $result['bar@bar.com']->phones->toArray();
$foobar = $result['foobar@foobar.com']->phones->toArray();
$this->assertArrayHasKey(1, $foo);
$this->assertArrayHasKey(2, $foo);
$this->assertArrayHasKey(3, $foo);
$this->assertArrayHasKey(4, $bar);
$this->assertArrayHasKey(5, $bar);
$this->assertArrayHasKey(6, $bar);
$this->assertArrayHasKey(7, $foobar);
$this->assertArrayHasKey(8, $foobar);
$this->assertArrayHasKey(9, $foobar);
}
public function testTicket()
{
$builder = $this->_em->createQueryBuilder();
$builder->select('u')->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.id');
$dql = $builder->getQuery()->getDQL();
$result = $builder->getQuery()->getResult();
$this->assertEquals(sizeof($result), 3);
$this->assertArrayHasKey(1, $result);
$this->assertArrayHasKey(2, $result);
$this->assertArrayHasKey(3, $result);
$this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.id', $dql);
}
public function testIndexByUnique()
{
$builder = $this->_em->createQueryBuilder();
$builder->select('u')->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.email');
$dql = $builder->getQuery()->getDQL();
$result = $builder->getQuery()->getResult();
$this->assertEquals(sizeof($result), 3);
$this->assertArrayHasKey('foo@foo.com', $result);
$this->assertArrayHasKey('bar@bar.com', $result);
$this->assertArrayHasKey('foobar@foobar.com', $result);
$this->assertEquals('SELECT u FROM ' . __NAMESPACE__ . '\DDC1335User u INDEX BY u.email', $dql);
}
public function testIndexWithJoin()
{
$builder = $this->_em->createQueryBuilder();
$builder->select('u','p')
->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.email')
->join('u.phones', 'p', null, null, 'p.id');
$dql = $builder->getQuery()->getDQL();
$result = $builder->getQuery()->getResult();
$this->assertEquals(sizeof($result), 3);
$this->assertArrayHasKey('foo@foo.com', $result);
$this->assertArrayHasKey('bar@bar.com', $result);
$this->assertArrayHasKey('foobar@foobar.com', $result);
$this->assertEquals(sizeof($result['foo@foo.com']->phones), 3);
$this->assertEquals(sizeof($result['bar@bar.com']->phones), 3);
$this->assertEquals(sizeof($result['foobar@foobar.com']->phones), 3);
$this->assertArrayHasKey(1, $result['foo@foo.com']->phones->toArray());
$this->assertArrayHasKey(2, $result['foo@foo.com']->phones->toArray());
$this->assertArrayHasKey(3, $result['foo@foo.com']->phones->toArray());
$this->assertArrayHasKey(4, $result['bar@bar.com']->phones->toArray());
$this->assertArrayHasKey(5, $result['bar@bar.com']->phones->toArray());
$this->assertArrayHasKey(6, $result['bar@bar.com']->phones->toArray());
$this->assertArrayHasKey(7, $result['foobar@foobar.com']->phones->toArray());
$this->assertArrayHasKey(8, $result['foobar@foobar.com']->phones->toArray());
$this->assertArrayHasKey(9, $result['foobar@foobar.com']->phones->toArray());
$this->assertEquals('SELECT u, p FROM '.__NAMESPACE__ . '\DDC1335User u INDEX BY u.email INNER JOIN u.phones p INDEX BY p.id', $dql);
}
private function loadFixture()
{
$p1 = array('11 xxxx-xxxx','11 yyyy-yyyy','11 zzzz-zzzz');
$p2 = array('22 xxxx-xxxx','22 yyyy-yyyy','22 zzzz-zzzz');
$p3 = array('33 xxxx-xxxx','33 yyyy-yyyy','33 zzzz-zzzz');
$u1 = new DDC1335User("foo@foo.com", "Foo",$p1);
$u2 = new DDC1335User("bar@bar.com", "Bar",$p2);
$u3 = new DDC1335User("foobar@foobar.com", "Foo Bar",$p3);
$this->_em->persist($u1);
$this->_em->persist($u2);
$this->_em->persist($u3);
$this->_em->flush();
$this->_em->clear();
}
}
/**
* @Entity
*/
class DDC1335User
{
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @Column(type="string", unique=true)
*/
public $email;
/**
* @Column(type="string")
*/
public $name;
/**
* @OneToMany(targetEntity="DDC1335Phone", mappedBy="user", cascade={"persist", "remove"})
*/
public $phones;
public function __construct($email, $name, array $numbers = array())
{
$this->name = $name;
$this->email = $email;
$this->phones = new \Doctrine\Common\Collections\ArrayCollection();
foreach ($numbers as $number) {
$this->phones->add(new DDC1335Phone($this,$number));
}
}
}
/**
* @Entity
*/
class DDC1335Phone
{
/**
* @Id
* @Column(name="id", type="integer")
* @GeneratedValue
*/
public $id;
/**
* @Column(name="numericalValue", type="string", nullable = false)
*/
public $numericalValue;
/**
* @ManyToOne(targetEntity="DDC1335User", inversedBy="phones")
* @JoinColumn(name="user_id", referencedColumnName="id", nullable = false)
*/
public $user;
public function __construct($user, $number)
{
$this->user = $user;
$this->numericalValue = $number;
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Tests\OrmFunctionalTestCase;
/**
* @group DDC-1360
*/
class DDC1360Test extends OrmFunctionalTestCase
{
public function testSchemaDoubleQuotedCreate()
{
if ($this->_em->getConnection()->getDatabasePlatform()->getName() != "postgresql") {
$this->markTestSkipped("PostgreSQL only test.");
}
$sql = $this->_schemaTool->getCreateSchemaSQL(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1360DoubleQuote')
));
$this->assertEquals(array(
'CREATE TABLE "user"."user" (id INT NOT NULL, PRIMARY KEY(id))',
'CREATE SEQUENCE "user".user_id_seq INCREMENT BY 1 MINVALUE 1 START 1',
), $sql);
}
}
/**
* @Entity @Table(name="`user`.`user`")
*/
class DDC1360DoubleQuote
{
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1383
*/
class DDC1383Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1383AbstractEntity'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1383Entity'),
));
} catch(\Exception $ignored) {}
}
public function testFailingCase()
{
$parent = new DDC1383Entity();
$child = new DDC1383Entity();
$child->setReference($parent);
$this->_em->persist($parent);
$this->_em->persist($child);
$id = $child->getId();
$this->_em->flush();
$this->_em->clear();
// Try merging the parent entity
$child = $this->_em->merge($child);
$parent = $child->getReference();
// Parent is not instance of the abstract class
self::assertTrue($parent instanceof DDC1383AbstractEntity,
"Entity class is " . get_class($parent) . ', "DDC1383AbstractEntity" was expected');
// Parent is NOT instance of entity
self::assertTrue($parent instanceof DDC1383Entity,
"Entity class is " . get_class($parent) . ', "DDC1383Entity" was expected');
}
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="integer")
* @DiscriminatorMap({1 = "DDC1383Entity"})
*/
abstract class DDC1383AbstractEntity
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
protected $id;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
}
/**
* @Entity
*/
class DDC1383Entity extends DDC1383AbstractEntity
{
/**
* @ManyToOne(targetEntity="DDC1383AbstractEntity")
*/
protected $reference;
public function getReference()
{
return $this->reference;
}
public function setReference(DDC1383AbstractEntity $reference)
{
$this->reference = $reference;
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1392
*/
class DDC1392Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1392File'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1392Picture'),
));
} catch (\Exception $ignored) {
}
}
public function testFailingCase()
{
$file = new DDC1392File;
$picture = new DDC1392Picture;
$picture->setFile($file);
$em = $this->_em;
$em->persist($picture);
$em->flush();
$em->clear();
$fileId = $file->getFileId();
$pictureId = $picture->getPictureId();
$this->assertTrue($fileId > 0);
$picture = $em->find(__NAMESPACE__ . '\DDC1392Picture', $pictureId);
$this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED.");
$file = $picture->getFile();
// With this activated there will be no problem
//$file->__load();
$picture->setFile(null);
$em->clear();
$em->merge($file);
$em->flush();
$q = $this->_em->createQuery("SELECT COUNT(e) FROM " . __NAMESPACE__ . '\DDC1392File e');
$result = $q->getSingleScalarResult();
self::assertEquals(1, $result);
}
}
/**
* @Entity
*/
class DDC1392Picture
{
/**
* @Column(name="picture_id", type="integer")
* @Id @GeneratedValue
*/
private $pictureId;
/**
* @ManyToOne(targetEntity="DDC1392File", cascade={"persist", "remove"})
* @JoinColumn(name="file_id", referencedColumnName="file_id")
*/
private $file;
/**
* Get pictureId
*/
public function getPictureId()
{
return $this->pictureId;
}
/**
* Set file
*/
public function setFile($value = null)
{
$this->file = $value;
}
/**
* Get file
*/
public function getFile()
{
return $this->file;
}
}
/**
* @Entity
*/
class DDC1392File
{
/**
* @Column(name="file_id", type="integer")
* @Id
* @GeneratedValue(strategy="AUTO")
*/
public $fileId;
/**
* Get fileId
*/
public function getFileId()
{
return $this->fileId;
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1400
*/
class DDC1400Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400Article'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400User'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400UserState'),
));
} catch (\Exception $ignored) {
}
}
public function testFailingCase()
{
$article = new DDC1400Article;
$user1 = new DDC1400User;
$user2 = new DDC1400User;
$this->_em->persist($article);
$this->_em->persist($user1);
$this->_em->persist($user2);
$this->_em->flush();
$userState1 = new DDC1400UserState;
$userState1->article = $article;
$userState1->articleId = $article->id;
$userState1->user = $user1;
$userState1->userId = $user1->id;
$userState2 = new DDC1400UserState;
$userState2->article = $article;
$userState2->articleId = $article->id;
$userState2->user = $user2;
$userState2->userId = $user2->id;
$this->_em->persist($userState1);
$this->_em->persist($userState2);
$this->_em->flush();
$this->_em->clear();
$user1 = $this->_em->getReference(__NAMESPACE__.'\DDC1400User', $user1->id);
$q = $this->_em->createQuery("SELECT a, s FROM ".__NAMESPACE__."\DDC1400Article a JOIN a.userStates s WITH s.user = :activeUser");
$q->setParameter('activeUser', $user1);
$articles = $q->getResult();
$this->_em->flush();
}
}
/**
* @Entity
*/
class DDC1400Article
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @OneToMany(targetEntity="DDC1400UserState", mappedBy="article", indexBy="userId", fetch="EXTRA_LAZY")
*/
public $userStates;
}
/**
* @Entity
*/
class DDC1400User
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @OneToMany(targetEntity="DDC1400UserState", mappedBy="user", indexBy="articleId", fetch="EXTRA_LAZY")
*/
public $userStates;
}
/**
* @Entity
*/
class DDC1400UserState
{
/**
* @Id
* @ManyToOne(targetEntity="DDC1400Article", inversedBy="userStates")
*/
public $article;
/**
* @Id
* @ManyToOne(targetEntity="DDC1400User", inversedBy="userStates")
*/
public $user;
/**
* @Column(name="user_id", type="integer")
*/
public $userId;
/**
* @Column(name="article_id", type="integer")
*/
public $articleId;
}

View File

@@ -0,0 +1,129 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1404
*/
class DDC1404Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1404ParentEntity'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1404ChildEntity'),
));
$this->loadFixtures();
} catch (Exception $exc) {
}
}
public function testTicket()
{
$repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1404ChildEntity');
$queryAll = $repository->createNamedQuery('all');
$queryFirst = $repository->createNamedQuery('first');
$querySecond = $repository->createNamedQuery('second');
$this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p', $queryAll->getDQL());
$this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 1', $queryFirst->getDQL());
$this->assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 2', $querySecond->getDQL());
$this->assertEquals(sizeof($queryAll->getResult()), 2);
$this->assertEquals(sizeof($queryFirst->getResult()), 1);
$this->assertEquals(sizeof($querySecond->getResult()), 1);
}
public function loadFixtures()
{
$c1 = new DDC1404ChildEntity("ChildEntity 1");
$c2 = new DDC1404ChildEntity("ChildEntity 2");
$this->_em->persist($c1);
$this->_em->persist($c2);
$this->_em->flush();
}
}
/**
* @MappedSuperclass
*
* @NamedQueries({
* @NamedQuery(name="all", query="SELECT p FROM __CLASS__ p"),
* @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"),
* })
*/
class DDC1404ParentEntity
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue()
*/
protected $id;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
}
/**
* @Entity
*
* @NamedQueries({
* @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"),
* @NamedQuery(name="second", query="SELECT p FROM __CLASS__ p WHERE p.id = 2")
* })
*/
class DDC1404ChildEntity extends DDC1404ParentEntity
{
/**
* @column(type="string")
*/
private $name;
/**
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
}

View File

@@ -0,0 +1,297 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1430
*/
class DDC1430Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1430Order'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1430OrderProduct'),
));
$this->loadFixtures();
} catch (\Exception $exc) {
}
}
public function testOrderByFields()
{
$repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order');
$builder = $repository->createQueryBuilder('o');
$query = $builder->select('o.id, o.date, COUNT(p.id) AS p_count')
->leftJoin('o.products', 'p')
->groupBy('o.id, o.date')
->orderBy('o.id')
->getQuery();
$this->assertEquals('SELECT o.id, o.date, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date ORDER BY o.id ASC', $query->getDQL());
$this->assertSQLEquals('SELECT d0_.order_id AS order_id0, d0_.created_at AS created_at1, COUNT(d1_.id) AS sclr2 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at ORDER BY d0_.order_id ASC', $query->getSQL());
$result = $query->getResult();
$this->assertEquals(2, sizeof($result));
$this->assertArrayHasKey('id', $result[0]);
$this->assertArrayHasKey('id', $result[1]);
$this->assertArrayHasKey('p_count', $result[0]);
$this->assertArrayHasKey('p_count', $result[1]);
$this->assertEquals(1, $result[0]['id']);
$this->assertEquals(2, $result[1]['id']);
$this->assertEquals(2, $result[0]['p_count']);
$this->assertEquals(3, $result[1]['p_count']);
}
public function testOrderByAllObjectFields()
{
$repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order');
$builder = $repository->createQueryBuilder('o');
$query = $builder->select('o, COUNT(p.id) AS p_count')
->leftJoin('o.products', 'p')
->groupBy('o.id, o.date, o.status')
->orderBy('o.id')
->getQuery();
$this->assertEquals('SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o.id, o.date, o.status ORDER BY o.id ASC', $query->getDQL());
$this->assertSQLEquals('SELECT d0_.order_id AS order_id0, d0_.created_at AS created_at1, d0_.order_status AS order_status2, COUNT(d1_.id) AS sclr3 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at, d0_.order_status ORDER BY d0_.order_id ASC', $query->getSQL());
$result = $query->getResult();
$this->assertEquals(2, sizeof($result));
$this->assertTrue($result[0][0] instanceof DDC1430Order);
$this->assertTrue($result[1][0] instanceof DDC1430Order);
$this->assertEquals($result[0][0]->getId(), 1);
$this->assertEquals($result[1][0]->getId(), 2);
$this->assertEquals($result[0]['p_count'], 2);
$this->assertEquals($result[1]['p_count'], 3);
}
public function testTicket()
{
$repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order');
$builder = $repository->createQueryBuilder('o');
$query = $builder->select('o, COUNT(p.id) AS p_count')
->leftJoin('o.products', 'p')
->groupBy('o')
->orderBy('o.id')
->getQuery();
$this->assertEquals('SELECT o, COUNT(p.id) AS p_count FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1430Order o LEFT JOIN o.products p GROUP BY o ORDER BY o.id ASC', $query->getDQL());
$this->assertSQLEquals('SELECT d0_.order_id AS order_id0, d0_.created_at AS created_at1, d0_.order_status AS order_status2, COUNT(d1_.id) AS sclr3 FROM DDC1430Order d0_ LEFT JOIN DDC1430OrderProduct d1_ ON d0_.order_id = d1_.order_id GROUP BY d0_.order_id, d0_.created_at, d0_.order_status ORDER BY d0_.order_id ASC', $query->getSQL());
$result = $query->getResult();
$this->assertEquals(2, sizeof($result));
$this->assertTrue($result[0][0] instanceof DDC1430Order);
$this->assertTrue($result[1][0] instanceof DDC1430Order);
$this->assertEquals($result[0][0]->getId(), 1);
$this->assertEquals($result[1][0]->getId(), 2);
$this->assertEquals($result[0]['p_count'], 2);
$this->assertEquals($result[1]['p_count'], 3);
}
public function loadFixtures()
{
$o1 = new DDC1430Order('NEW');
$o2 = new DDC1430Order('OK');
$o1->addProduct(new DDC1430OrderProduct(1.1));
$o1->addProduct(new DDC1430OrderProduct(1.2));
$o2->addProduct(new DDC1430OrderProduct(2.1));
$o2->addProduct(new DDC1430OrderProduct(2.2));
$o2->addProduct(new DDC1430OrderProduct(2.3));
$this->_em->persist($o1);
$this->_em->persist($o2);
$this->_em->flush();
}
}
/**
* @Entity
*/
class DDC1430Order
{
/**
* @Id
* @Column(name="order_id", type="integer")
* @GeneratedValue()
*/
protected $id;
/**
* @Column(name="created_at", type="datetime")
*/
private $date;
/**
* @Column(name="order_status", type="string")
*/
private $status;
/**
* @OneToMany(targetEntity="DDC1430OrderProduct", mappedBy="order", cascade={"persist", "remove"})
*
* @var \Doctrine\Common\Collections\ArrayCollection $products
*/
private $products;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
public function __construct($status)
{
$this->status = $status;
$this->date = new \DateTime();
$this->products = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @param string $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getProducts()
{
return $this->products;
}
/**
* @param DDC1430OrderProduct $product
*/
public function addProduct(DDC1430OrderProduct $product)
{
$product->setOrder($this);
$this->products->add($product);
}
}
/**
* @Entity
*/
class DDC1430OrderProduct
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue()
*/
protected $id;
/**
* @var DDC1430Order $order
*
* @ManyToOne(targetEntity="DDC1430Order", inversedBy="products")
* @JoinColumn(name="order_id", referencedColumnName="order_id", nullable = false)
*/
private $order;
/**
* @column(type="float")
*/
private $value;
/**
* @param float $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return DDC1430Order
*/
public function getOrder()
{
return $this->order;
}
/**
* @param DDC1430Order $order
*/
public function setOrder(DDC1430Order $order)
{
$this->order = $order;
}
/**
* @return float
*/
public function getValue()
{
return $this->value;
}
/**
* @param float $value
*/
public function setValue($value)
{
$this->value = $value;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\UnitOfWork;
/**
* @group DDC-1436
*/
class DDC1436Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1436Page'),
));
} catch (\Exception $ignored) {
}
}
public function testIdentityMap()
{
// fixtures
$parent = null;
for ($i = 0; $i < 3; $i++) {
$page = new DDC1436Page();
$page->setParent($parent);
$this->_em->persist($page);
$parent = $page;
}
$this->_em->flush();
$this->_em->clear();
$id = $parent->getId();
// step 1
$page = $this->_em
->createQuery('SELECT p, parent FROM ' . __NAMESPACE__ . '\DDC1436Page p LEFT JOIN p.parent parent WHERE p.id = :id')
->setParameter('id', $id)
->getOneOrNullResult();
$this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page);
// step 2
$page = $this->_em->find(__NAMESPACE__ . '\DDC1436Page', $id);
$this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page);
$this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page->getParent());
$this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page->getParent()->getParent());
}
}
/**
* @Entity
*/
class DDC1436Page
{
/**
* @Id
* @GeneratedValue
* @Column(type="integer", name="id")
*/
protected $id;
/**
* @ManyToOne(targetEntity="DDC1436Page")
* @JoinColumn(name="pid", referencedColumnName="id")
*/
protected $parent;
public function getId()
{
return $this->id;
}
/**
* @return DDC1436Page
*/
public function getParent()
{
return $this->parent;
}
public function setParent($parent)
{
$this->parent = $parent;
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
require_once __DIR__ . '/../../../TestInit.php';
class DDC144Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144FlowElement'),
// $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144Expression'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144Operand'),
));
}
/**
* @group DDC-144
*/
public function testIssue()
{
$operand = new DDC144Operand;
$operand->property = 'flowValue';
$operand->operandProperty = 'operandValue';
$this->_em->persist($operand);
$this->_em->flush();
}
}
/**
* @Entity
* @Table(name="ddc144_flowelements")
* @InheritanceType("JOINED")
* @DiscriminatorColumn(type="string", name="discr")
* @DiscriminatorMap({"flowelement" = "DDC144FlowElement", "operand" = "DDC144Operand"})
*/
class DDC144FlowElement {
/**
* @Id @Column(type="integer") @GeneratedValue
* @var integer
*/
public $id;
/** @Column */
public $property;
}
abstract class DDC144Expression extends DDC144FlowElement {
abstract function method();
}
/** @Entity @Table(name="ddc144_operands") */
class DDC144Operand extends DDC144Expression {
/** @Column */
public $operandProperty;
function method() {}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1452
*/
class DDC1452Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
$this->useModelSet('cms');
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1452EntityA'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1452EntityB'),
));
} catch (\Exception $ignored) {
}
}
public function testIssue()
{
$a1 = new DDC1452EntityA();
$a1->title = "foo";
$a2 = new DDC1452EntityA();
$a2->title = "bar";
$b = new DDC1452EntityB();
$b->entityAFrom = $a1;
$b->entityATo = $a2;
$this->_em->persist($a1);
$this->_em->persist($a2);
$this->_em->persist($b);
$this->_em->flush();
$this->_em->clear();
$dql = "SELECT a, b, ba FROM " . __NAMESPACE__ . "\DDC1452EntityA AS a LEFT JOIN a.entitiesB AS b LEFT JOIN b.entityATo AS ba";
$results = $this->_em->createQuery($dql)->setMaxResults(1)->getResult();
$this->assertSame($results[0], $results[0]->entitiesB[0]->entityAFrom);
$this->assertFalse( $results[0]->entitiesB[0]->entityATo instanceof \Doctrine\ORM\Proxy\Proxy );
$this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results[0]->entitiesB[0]->entityATo->getEntitiesB());
}
public function testFetchJoinOneToOneFromInverse()
{
$address = new \Doctrine\Tests\Models\CMS\CmsAddress();
$address->city = "Bonn";
$address->country = "Germany";
$address->street = "Somestreet";
$address->zip = 12345;
$user = new \Doctrine\Tests\Models\CMS\CmsUser();
$user->name = "beberlei";
$user->username = "beberlei";
$user->status = "active";
$user->address = $address;
$address->user = $user;
$this->_em->persist($address);
$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
$dql = "SELECT a, u FROM Doctrine\Tests\Models\CMS\CmsAddress a INNER JOIN a.user u";
$data = $this->_em->createQuery($dql)->getResult();
$this->_em->clear();
$this->assertFalse($data[0]->user instanceof \Doctrine\ORM\Proxy\Proxy);
$dql = "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.address a";
$data = $this->_em->createQuery($dql)->getResult();
$this->assertFalse($data[0]->address instanceof \Doctrine\ORM\Proxy\Proxy);
}
}
/**
* @Entity
*/
class DDC1452EntityA
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/** @Column */
public $title;
/** @ManyToMany(targetEntity="DDC1452EntityB", mappedBy="entityAFrom") */
public $entitiesB;
public function __construct()
{
$this->entitiesB = new ArrayCollection();
}
public function getEntitiesB()
{
return $this->entitiesB;
}
}
/**
* @Entity
*/
class DDC1452EntityB
{
/** @Id @Column(type="integer") @GeneratedValue */
public $id;
/**
* @ManyToOne(targetEntity="DDC1452EntityA", inversedBy="entitiesB")
*/
public $entityAFrom;
/**
* @ManyToOne(targetEntity="DDC1452EntityA")
*/
public $entityATo;
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\ORM\UnitOfWork;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1454
*/
class DDC1454Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1454File'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1454Picture'),
));
} catch (\Exception $ignored) {
}
}
public function testFailingCase()
{
$pic = new DDC1454Picture();
$this->_em->getUnitOfWork()->getEntityState($pic);
}
}
/**
* @Entity
*/
class DDC1454Picture extends DDC1454File
{
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"picture" = "DDC1454Picture"})
*/
class DDC1454File
{
/**
* @Column(name="file_id", type="integer")
* @Id
*/
public $fileId;
public function __construct() {
$this->fileId = rand();
}
/**
* Get fileId
*/
public function getFileId() {
return $this->fileId;
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsGroup;
require_once __DIR__ . '/../../../TestInit.php';
class DDC1258Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\TestEntity'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\TestAdditionalEntity')
));
}
public function testIssue()
{
$testEntity = new TestEntity();
$testEntity->setValue(3);
$testEntity->setAdditional(new TestAdditionalEntity());
$this->_em->persist($testEntity);
$this->_em->flush();
$this->_em->clear();
// So here the value is 3
$this->assertEquals(3, $testEntity->getValue());
$test = $this->_em->getRepository(__NAMESPACE__ . '\TestEntity')->find(1);
// New value is set
$test->setValue(5);
// So here the value is 5
$this->assertEquals(5, $test->getValue());
// Get the additional entity
$additional = $test->getAdditional();
// Still 5..
$this->assertEquals(5, $test->getValue());
// Force the proxy to load
$additional->getBool();
// The value should still be 5
$this->assertEquals(5, $test->getValue());
}
}
/**
* @Entity
*/
class TestEntity
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="integer")
*/
protected $value;
/**
* @OneToOne(targetEntity="TestAdditionalEntity", inversedBy="entity", orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $additional;
public function getValue()
{
return $this->value;
}
public function setValue($value)
{
$this->value = $value;
}
public function getAdditional()
{
return $this->additional;
}
public function setAdditional($additional)
{
$this->additional = $additional;
}
}
/**
* @Entity
*/
class TestAdditionalEntity
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @OneToOne(targetEntity="TestEntity", mappedBy="additional")
*/
protected $entity;
/**
* @Column(type="boolean")
*/
protected $bool;
public function __construct()
{
$this->bool = false;
}
public function getBool()
{
return $this->bool;
}
public function setBool($bool)
{
$this->bool = $bool;
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Tests\Models\CMS\CmsArticle;
use Doctrine\Tests\Models\CMS\CmsUser;
require_once __DIR__ . '/../../../TestInit.php';
/**
* @group DDC-1461
*/
class DDC1461Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
public function setUp()
{
parent::setUp();
try {
$this->_schemaTool->createSchema(array(
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1461TwitterAccount'),
$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1461User')
));
} catch(\Exception $e) {
}
}
public function testChangeDetectionDeferredExplicit()
{
$user = new DDC1461User;
$this->_em->persist($user);
$this->_em->flush();
$this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user, \Doctrine\ORM\UnitOfWork::STATE_NEW), "Entity should be managed.");
$this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($user), "Entity should be managed.");
$acc = new DDC1461TwitterAccount;
$user->twitterAccount = $acc;
$this->_em->persist($user);
$this->_em->flush();
$user = $this->_em->find(get_class($user), $user->id);
$this->assertNotNull($user->twitterAccount);
}
}
/**
* @Entity
* @ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class DDC1461User
{
/**
* @Id
* @GeneratedValue(strategy="AUTO")
* @Column(type="integer")
*/
public $id;
/**
* @OneToOne(targetEntity="DDC1461TwitterAccount", orphanRemoval=true, fetch="EAGER", cascade = {"persist"}, inversedBy="user")
* @var TwitterAccount
*/
public $twitterAccount;
}
/**
* @Entity
* @ChangeTrackingPolicy("DEFERRED_EXPLICIT")
*/
class DDC1461TwitterAccount
{
/**
* @Id
* @GeneratedValue(strategy="AUTO")
* @Column(type="integer")
*/
public $id;
/**
* @OneToOne(targetEntity="DDC1461User", fetch="EAGER")
*/
public $user;
}

Some files were not shown because too many files have changed in this diff Show More