[DDC-3224] getResult(HYDRATE_OBJECT) with joined query is returning reduced number of rows Created: 23/Jul/14  Updated: 23/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: gondo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

osx, PHP-FPM 5.5.13, nginx/1.6.0, mysql 5.6.19 Homebrew



 Description   

given that i have these 2 entities (pseodocode):

/**
 * @ORM\Table(name="entity1", options={"collate"="utf8_unicode_ci", "charset"="utf8"})
 * @ORM\Entity(repositoryClass="Entity1Repository")
 */
class Entity1 {
    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="name", type="string")
     */
    protected $name;

    /**
     * @var Entity2[]
     * @ORM\OneToMany(targetEntity="Entity2", mappedBy="entity1")
     */
    protected $entity2;
}

/**
 * @ORM\Table(name="entity2", options={"collate"="utf8_unicode_ci", "charset"="utf8"})
 * @ORM\Entity()
 */
class Entity2 {
    /**
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \DateTime
     * @ORM\Column(name="date", type="datetime")
     */
    protected $date;

    /**
     * @var Entity1
     * @ORM\ManyToOne(targetEntity="Entity1", inversedBy="entity2", fetch="EAGER")
     */
    protected $entity1;
}

tables and data

entity1:

id name
1 Jhon
2 Clare

entity2:

id date entity1_id
1 2011-01-01 00:00:01 1
2 2012-02-02 00:00:02 1
3 2013-03-03 00:00:03 2
4 2014-04-04 00:00:04 2

my query builder

use Doctrine\ORM\EntityRepository;

class Entity1Repository extends EntityRepository
{
    public function getData()
    {
        $qb = $this
            ->createQueryBuilder('Entity1')
            ->select('Entity1, Entity2.date')
            ->join('Entity1.entity2', 'Entity2', Join::WITH, 'Entity2.date > :date')
            ->setParameter('date', '2000-01-01 00:00:01')
        ;
        $result1 = $qb->getQuery()->getArrayResult(); // HYDRATE_ARRAY
        $result = $qb->getQuery()->getResult(); // HYDRATE_OBJECT
        
//        return $result1;
//        return $result2;
    }
}

proper result is this:

id name date
1 Jhon 2011-01-01 00:00:01
1 Jhon 2012-02-02 00:00:02
2 Clare 2013-03-03 00:00:03
2 Clare 2014-04-04 00:00:04

what is happening

$result1 = $qb->getQuery()->getArrayResult(); // HYDRATE_ARRAY

is really returning proper number of rows

BUT and here comes the BUG finally:

$result2 = $qb->getQuery()->getResult(); // HYDRATE_OBJECT

is returning just 2 rows:

id name date
1 Jhon 2011-01-01 00:00:01
2 Clare 2013-03-03 00:00:03

this is because somehow entities are made unique.

my workaround

as a workaround, what i have to do is, to exectute 2 queries. 1st to get just Entity1.ids joined with Entity2.dates by using `getArrayResult()`
and second query to get Entity1 objeces by unique ids from 1st query.
and than manualy join those results in php.



 Comments   
Comment by Marco Pivetta [ 23/Jul/14 ]

I see that you are using Join::WITH, but not providing a conditional in the example. Are you filtering a fetch-joined association?

Comment by gondo [ 23/Jul/14 ]

sorry i've tried to simplify my structure as much as it was possible, there are actually real conditions, one of them is date condition (among many others). i've updated my code

Comment by Marco Pivetta [ 23/Jul/14 ]

There are still some inconsistencies in the issue - where is that query parameter used, for example?

Comment by gondo [ 23/Jul/14 ]

im using it in EntityRepository (sorry, didnt know thats important) i ll update my code
and the whole code is in Symfony2 project (web and command line applications)

Comment by Marco Pivetta [ 23/Jul/14 ]

What I mean is that in

->setParameter('date', new \DateTime('last month'))

, parameter :date does not exist in the DQL.

Comment by gondo [ 23/Jul/14 ]

i see, sorry its part of JOIN condition, i've updated the code





[DDC-3222] PostUpdate event destroying collectionUpdates Created: 21/Jul/14  Updated: 21/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: Jacob Spizziri Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OSX, AMP, php 5.3.27



 Description   

I have an entity that contains a Many-To-Many Unidirectional association. When the association is updated and the entity is flushed the changes are not being persisted to the database.

This is because the postUpdate event is being fired on executeUpdates, which is being called before the collection updates are being processed here:

            // Collection updates (deleteRows, updateRows, insertRows)
            foreach ($this->collectionUpdates as $collectionToUpdate) {
                $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
            }

This is occurring in UnitOfWork->commit() lines 333 through 366.

Apparently the postUpdate listener I wrote was causing the collectionUpdates property to be erased.



 Comments   
Comment by Marco Pivetta [ 21/Jul/14 ]

What does the listener actually do? Doesn't look like a bug to me...

Comment by Jacob Spizziri [ 21/Jul/14 ]

I'm using FOSElasticaBundle/ElasticSearch. On the postUpdate event I'm calling fos:elastica:populate on the entity indexes. Heres the code

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace SRC\Bundle\SearchBundle\EventListener;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Doctrine\ORM\Event\LifecycleEventArgs;
use SRC\Bundle\ProductBundle\Entity\Product;
use SRC\Bundle\UserBundle\Entity\User;

/**
 * Description of SearchIndexer
 *
 * @author jacobspizziri
 */
class SearchIndexer
{	
	protected $container;
	protected $logger;
	
	public function __construct($container, $logger) {
		$this->container = $container;
		$this->logger = $logger;
	}
	
	
	public function postUpdate(LifecycleEventArgs $args){
		$this->index($args);
	}
	
	protected function index($args){
		$entity = $args->getEntity();

		$arguments = false;
		$command = new \FOS\ElasticaBundle\Command\PopulateCommand();
		$command->setContainer($this->container);
		
		//TODO: probably need to specify the --env=prod/dev
		// update Elastica on Product update
		if ($entity instanceof Product) {
			$this->logger->info('Updating Product Search Indexes');
			
			$arguments = array(
					'--index'=>'website',
					'--type' => 'product'
					);
		} else if ($entity instanceof User) {
			$this->logger->info('Updating User Search Indexes');

			$arguments = array(
					'--index'=>'website',
					'--type' => 'user'
					);
		}
		
		
		if($command && $arguments){
			$input = new ArrayInput($arguments);
			$output = new NullOutput();
			
			$result = $command->run($input, $output);
			$this->logger->info('Finished Updating Search Indexes with result: '. strval($result));
		}
	}
}
?>

Am I using this event incorrectly? Should I only be using postPersist?





[DDC-3212] Remove ArrayHydrator logic Created: 14/Jul/14  Updated: 14/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.5
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Critical
Reporter: Marco Pivetta Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: hydration, hydrator


 Description   

The Doctrine\ORM\Internal\Hydration\ArrayHydrator ( https://github.com/doctrine/doctrine2/blob/85fbf684363b932a4ebaf543ef059f9ee1e512b0/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php ) is currently very messy and complicated due to the lack of actual Doctrine\ORM\UnitOfWork references when working with it, since we are not dealing with objects.

In order to reduce the amount of bugs and code duplication when working with array hydration, I would simply suggest making use of the Doctrine\ORM\Internal\Hydration\ObjectHydrator ( https://github.com/doctrine/doctrine2/blob/85fbf684363b932a4ebaf543ef059f9ee1e512b0/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php ) and its siblings, and then extracting data coming from the results in it as an array.

This could be a simple reflection-based extraction (pseudo):

class ArrayHydrator
{
    public function hydrateAllData()
    {
        foreach ($this->objectHydrator->hydrateAllData() as $object) {
            yield $this->extractData($object);
        }
    }
}

The point here is that array-based hydration is not the primary focus of the ORM, and users should probably rely on SQL only when they want array hydration.



 Comments   
Comment by Marco Pivetta [ 14/Jul/14 ]

Note: performance is one of our biggest requirements, and array hydration is meant to achieve that. As I stated above, plain SQL is probably better for this sort of operation, so the issue is more about deprecating the ArrayHydrator completely, providing utilities to manipulate SQL resultsets instead.





[DDC-3062] [GH-997] [FIX] Allow to use ManyToMany with all operators Created: 31/Mar/14  Updated: 08/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: 2.5
Security Level: All

Type: Bug Priority: Critical
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of bakura10:

Url: https://github.com/doctrine/doctrine2/pull/997

Message:

Hi,

ping @guillhermoblanco : I think this may be blocking for 2.5

I introduced not so long ago support for ManyToMany for Criteria. However, I realized my implementation was really incomplete, because I hard-coded the "=" operator (https://github.com/doctrine/doctrine2/pull/885/files#diff-982b7374bbe9d5f4b6b71f4869a446eaR575). This means that it fails in a lot of cases when you use something different than "eq" for Criteria.

This PR fixes that, however it's a bit hacky. The SqlExpressionVisitor was made by type hinting for a BasicEntityPersister, preventing us from using us for a collection persister. Therefore I added a new interface to keep BC.

There is also a lot of code duplication (the whole "getSelectConditionSQL" was copied from the BasicEntityPersister), but without trait or BC, I have no idea about how to solve it.

All tests pass, test were added for other operators.






[DDC-2953] ArrayHydrator: Not all items hydrated while orderBy Created: 05/Feb/14  Updated: 14/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4, 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Critical
Reporter: Mariusz Jaskółka Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: array, hydration
Environment:

Linux and Windows, PHP5


Attachments: File ArrayHydrator.php     File Array_Hydrator_4.2.php     File Array_hydrator_4.2_bugfix.php    

 Description   

I will explain the problem using example and pseudo-code:

I have query like that:
SELECT (...) FROM order LEFT JOIN person LEFT JOIN identifier (...) order by (...)

The rows returned by query are following (the order is very important):
order_id|person_id|identifier_id|
12 |21 |33 |
12 |21 |34 |
11 |21 |35 |
11 |21 |33 |
11 |21 |34 |
12 |21 |35 |

After hydration the result is like:
result[0][person][identifier][0][id]=33
result[0][person][identifier][0][id]=34
result[1][person][identifier][0][id]=35
result[1][person][identifier][0][id]=34

But it should be:
result[0][person][identifier][0][id]=33
result[0][person][identifier][0][id]=34
result[0][person][identifier][0][id]=35
result[1][person][identifier][0][id]=35
result[1][person][identifier][0][id]=34
result[1][person][identifier][0][id]=33

The reason is that ArrayHydrator::_identifierMap contains only object id and parents object id. In may example there is difference in parents parent (grandparent) id.



 Comments   
Comment by Marco Pivetta [ 05/Feb/14 ]

I've started work on this at https://github.com/doctrine/doctrine2/pull/933

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

This is how I temporary solved the issue, maybe it can help (attachment).

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka can you provide a diff with current master? This seems to be based off 2.3 or previous versions...

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

Version 2.4.2 oryginal file and bugfix

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

Oh sorry it is version 2.4.1 (composer downloaded that version for me).
I hope it will be ok.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka thanks! I'm trying it right now

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

I added one dimention to $this->_identifierMap to be sure that all object's children's keys will be mapped separately.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka, I've applied your hotfix at https://github.com/doctrine/doctrine2/commit/c05921032ff6947daca2d7275031e5cde4700634 and the tests seem to pass on my system and on travis. You may want to check it out and see if it works for your use case.

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

It works for my use case correctly. You apparently forgot to remove/comment line 82 which is not necessary now.

Comment by Marco Pivetta [ 06/Feb/14 ]

Mariusz Jaskółka fixed, thanks!

Comment by Marco Pivetta [ 14/Jul/14 ]

I don't think we'll have a fix for this issue for 2.5, as it will probably require a complete rewrite of the array hydrator

Comment by Guilherme Blanco [ 14/Jul/14 ]

... and introducing BC breaks.





[DDC-3221] Invalid binding for primary key of entity relation Created: 21/Jul/14  Updated: 21/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.3
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Alexandr Smaga Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

Hello.

We use doctrine2 ORM with doctrine/doctrine-bundle in our symfony2 based project. We developed functionality which is similar to some kind of import process.

And we have an issue that appears from time to time in different points during the import.

Issue is following:
Lets imagine we have 3 entities Account, Contact, Contact Address.
Account has many to one relation on contact and contact has one to many relation on contact address.

Our import creates all 3 entities and persist only Account, contact and address are persisted via cascade persist.
We have writer that contains following code

    public function write(array $items)
    {
        try {
            $this->entityManager->beginTransaction();
            foreach ($items as $item) {
                $this->entityManager->persist($item);
            }
            $this->entityManager->commit();
        } catch (\Exception $exception) {
            $this->entityManager->rollback();

            throw $exception;
        }
        $this->entityManager->flush();
        $this->entityManager->clear();
    }

So we clear EntityManager for each batch in order to avoid high memory consumption.
Import fails during different entities insert, but errors are very similar.
Example of error is

> [error] An exception occurred while executing 'INSERT INTO ... VALUES (?, ?, ?, ?, ?)' with params ["__start__", "2014-07-21 00:55:35", 0, null, 21]:
>
> SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`DB`.`account`, CONSTRAINT `FK_B3D57B301023C4EE` FOREIGN KEY (`contact_id`) REFERENCES `contact` (`id`) ON DELETE CASCADE)

After debugging I found that problem is in BasicEntityPersister#prepareUpdateData

$uow->getEntityIdentifier($newVal);


returns oid that is real one, but UOW contains not the same ID as in $newVal entity. It seems like spl_object_hash duplicates oid.

Any help is appreciated.
Thanks in advance.






[DDC-3220] Association mappings of embedded class not loaded into entity classMetadata Created: 21/Jul/14  Updated: 21/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Anatolie Marinescu Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None


 Description   

method inlineEmbeddable from Doctrine\ORM\Mapping\ClassMetadataInfo mapped only columns, but relations is omitted






[DDC-3218] Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given Created: 18/Jul/14  Updated: 18/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2, 2.4.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Grégoire Pineau Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux / Mint 15
php 5.5.*



 Description   

Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /home/greg/dev/product/insight/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined

Stack trace:

[1] PHPUnit_Framework_Error: Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined
at n/a
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php line 47

at PHPUnit_Util_ErrorHandler::handleError('4096', 'Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be of the type array, null given, called in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1009 and defined', '/project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php', '47', array('entity' => object(Violation), 'em' => object(EntityManager)))
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php line 47

at Doctrine\ORM\Event\PreUpdateEventArgs->__construct(object(Violation), object(EntityManager), null)
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 1009

at Doctrine\ORM\UnitOfWork->executeUpdates(object(ClassMetadata))
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 341

at Doctrine\ORM\UnitOfWork->commit(null)
in /project/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php line 389

at Doctrine\ORM\EntityManager->flush()
in /project/src/SensioLabs/Bundle/MyBundle/Controller/MyController.php line 127

at SensioLabs\Bundle\MyBundle\Controller\MyController->ignoreAction(object(Request), object(Project), object(Analysis), '4')
in line

at call_user_func_array(array(object(MyController), 'ignoreAction'), array(object(Request), object(Project), object(Analysis), '4'))
in /project/app/bootstrap.php.cache line 1043

at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
in /project/app/bootstrap.php.cache line 1015

at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
in /project/app/bootstrap.php.cache line 1154

at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
in /project/app/bootstrap.php.cache line 435

at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php line 81

at Symfony\Component\HttpKernel\Client->doRequest(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php line 111

at Symfony\Bundle\FrameworkBundle\Client->doRequest(object(Request))
in /project/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php line 319

at Symfony\Component\BrowserKit\Client->request('POST', '/projects/id-foo/analyses/2/rule/4/ignore', array('ignore_rule' => array('comment' => 'Message about why this rule has been ignored', '_token' => 'CxEFTSv4GZQSWYXtRt-eHybaML4z8I0WK1DHiwr8Ih0')))
in /project/src/SensioLabs/Bundle/MyBundle/Test/Client.php line 489

at SensioLabs\Bundle\MyBundle\Test\Client->ignoreRuleViolations('id-foo', '2', '4', false)
in /project/src/SensioLabs/Bundle/MyBundle/Tests/Acceptance/ViolationCommentsTest.php line 217

at SensioLabs\Bundle\MyBundle\Tests\Acceptance\ViolationCommentsTest->testDashboardWithCriticalIgnoredRules()
in line

at ReflectionMethod->invokeArgs(object(ViolationCommentsTest), array())
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 951

at PHPUnit_Framework_TestCase->runTest()
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 817

at PHPUnit_Framework_TestCase->runBare()
in /project/vendor/phpunit/phpunit/src/Framework/TestResult.php line 686

at PHPUnit_Framework_TestResult->run(object(ViolationCommentsTest))
in /project/vendor/phpunit/phpunit/src/Framework/TestCase.php line 753

at PHPUnit_Framework_TestCase->run(object(PHPUnit_Framework_TestResult))
in /project/vendor/phpunit/phpunit/src/Framework/TestSuite.php line 675

at PHPUnit_Framework_TestSuite->run(object(PHPUnit_Framework_TestResult))
in /project/vendor/phpunit/phpunit/src/TextUI/TestRunner.php line 426

at PHPUnit_TextUI_TestRunner->doRun(object(PHPUnit_Framework_TestSuite), array('listGroups' => false, 'loader' => null, 'useDefaultConfiguration' => true, 'configuration' => '/project/app/phpunit.xml.dist', 'filter' => 'testDashboardWithCriticalIgnoredRules', 'testSuffixes' => array('Test.php', '.phpt')))
in /opt/dotfiles/vendor/phpunit/phpunit/PHPUnit/TextUI/Command.php line 176

at PHPUnit_TextUI_Command->run(array('/usr/local/bin/phpunit', 'c', 'app/', '-filter', 'testDashboardWithCriticalIgnoredRules', 'src/SensioLabs/Bundle/MyBundle/Tests/Acceptance/ViolationCommentsTest.php'), true)
in /opt/dotfiles/vendor/phpunit/phpunit/PHPUnit/TextUI/Command.php line 129

at PHPUnit_TextUI_Command::main()
in /opt/dotfiles/vendor/phpunit/phpunit/composer/bin/phpunit line 63

I fails in this code

    private function executeUpdates($class)
    {
        $className          = $class->name;
        $persister          = $this->getEntityPersister($className);
        $preUpdateInvoke    = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
        $postUpdateInvoke   = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);

        foreach ($this->entityUpdates as $oid => $entity) {
            if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
                continue;
            }

            if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
// => this line
                $this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->entityChangeSets[$oid]), $preUpdateInvoke);
                $this->recomputeSingleEntityChangeSet($class, $entity);
            }

            if ( ! empty($this->entityChangeSets[$oid])) {
                $persister->update($entity);
            }

            unset($this->entityUpdates[$oid]);

            if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
                $this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
            }
        }
    }


 Comments   
Comment by Marco Pivetta [ 18/Jul/14 ]

Requires a test case





[DDC-3215] wrong quotation Created: 16/Jul/14  Updated: 17/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: DQL, ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: revrev Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dql, orm


 Description   

when doctrine build query´s, for example when you doing

$entitity->getTest()->clear();

following queries are generated (test_id is integer in mysql):

DELETE FROM test WHERE test_id = '6'

Is this right?
For me the right query would be:

DELETE FROM test WHERE test_id = 6

as in http://dev.mysql.com/doc/refman/5.5/en/type-conversion.html
6 will be converted to float, this can be an issue, or?

Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results that appear inconsistent:

mysql> SELECT '18015376320243458' = 18015376320243458;
        -> 1
mysql> SELECT '18015376320243459' = 18015376320243459;
        -> 0

this also happens in dql sometimes, why doctrine does this not automatic right due to description in the entities?

     /**
     * @ORM\Id @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */


 Comments   
Comment by Marco Pivetta [ 16/Jul/14 ]

Could you please convert this to a failing test case? Doctrine doesn't quote integers as strings by default.

Comment by revrev [ 16/Jul/14 ]

i try to describe what i have done

i have an Entity with:

    /**
     * @ORM\ManyToMany(targetEntity="Messen", inversedBy="vertrag_messen")
     * @ORM\JoinTable(name="vertrag_messen")
     **/
    private $vertrag_messen;

    public function __construct()
    {
        $this->vertrag_messen = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getMessen()
    {
        return $this->vertrag_messen;
    }

when i now clear the Data

$entitity->getMessen()->clear();

following query is created
DELETE FROM vertrag_messen where messe_id = '6'

Should here not set the value 6 as integer (param_int) (DELETE FROM test vertrag_messen where messe_id = 6) that mysql doesn´t have to cast the value? (http://dev.mysql.com/doc/refman/5.5/en/type-conversion.html) or is this not an problem?

Comment by Marco Pivetta [ 16/Jul/14 ]

is messe_id in your entity an integer or a string at the moment in time when that query is being executed?

Comment by revrev [ 16/Jul/14 ]

the value comes automatic
$entitity = $em->getRepository('Base\Entities\Vertrag')>find(intval($data["id"]));

i don´t set messe_id here

Comment by Marco Pivetta [ 16/Jul/14 ]

Can you var_dump the Base\Entities\Messe instance?

Comment by revrev [ 16/Jul/14 ]

object(stdClass)#1014 (64) {
["__CLASS__"]=>
string(24) "Base\Entities\Vertrag"
["id"]=>
int(6)
[„vertrag_messen"]=>
array(1)

Unknown macro: { [0]=> string(20) "BaseEntitiesMessen" }


["erstellungsdatum"]=>
object(stdClass)#1210 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2013-09-28T00}

["zeitraumvon"]=>
NULL
["zeitraumbis"]=>
NULL
["jahr"]=>
int(2014)
["created"]=>
object(stdClass)#1178 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2013-09-28T19}

["updated"]=>
object(stdClass)#1177 (3)

Unknown macro: { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2014-07-16T17}

["uuid"]=>
string(36) "52470c58-4288-45eb-b75f-0c41c0a81437"
}

Comment by Marco Pivetta [ 17/Jul/14 ]

yeah, integer identifier there.
Could you verify if the problem also comes up with current master? I think this issue is related with another one that was fixed some months ago in 2.5.x-dev





[DDC-3211] Annotation @ORM\Table(name="schema.table") don't generate sql using OCI8 Created: 09/Jul/14  Updated: 12/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.4.1, 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Jorge Potosme Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: cli, mapping, oci8, oracle, orm, symfony
Environment:

OS: Fedora 20
Web Server: Apache
DBMS: Oracle 12c
Framework: Symfony2
PHP version: 5.5.14
DBMS Driver: OCI8



 Description   

Using Symfony and "doctrine/orm": "2.4.@dev", "doctrine/doctrine-bundle": "1.3.@dev", with OCI8(Oracle Call Interface)
I have an entity
/**
* @ORM\Entity
* @ORM\Table(name="rrhh.usuario")
*/
class Usuario implements UserInterface

{ ... }

When i use de CLI (php app/console doctrine:schema:create --dump-sql) this don't show nothing, the output is empty.

If i change (name="rrhh.usuario") to (name="usuario", schema="rrhh") the CLI show the sql query but without the schema.



 Comments   
Comment by Marco Pivetta [ 09/Jul/14 ]

Duplicates this issue





[DDC-3203] "Orphan Removal" for ManyToMany and "Cascade remove" doesn't trigger "preRemove" callback on related entity Created: 01/Jul/14  Updated: 02/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Tadej Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Latest ZendFramework2, latest ZF2 DoctrineModule and latest ZF2 DoctrineORMModule



 Description   

I'm not sure if it's me, but I couldn't get "preRemove" callback/event working when "remove" action is triggered from related entity, but it works where the entity itself (the one with "preRemove" event) is removed directly.

According to documentation:
"If an association is marked as CASCADE=REMOVE Doctrine 2 will fetch this association. If its a Single association it will pass this entity to ´EntityManager#remove()`"....and similar for multiple entities.
DOC: http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html?highlight=working-with-objects%20removing-entities#removing-entities

"preRemove event is called on every entity when its passed to the EntityManager#remove()"
DOC: http://docs.doctrine-project.org/en/latest/reference/events.html#preremove

So according to documentation "preRemove" should get triggered on "cascade remove", but it doesn't get in my case. Is this normal behavior or a bug?

I'm not sure if it the problem might be in any of ZF2 modules, but I've decided to post the issue here, since I'm referring to documentation of this project.

Beside that I've also noticed that "orphan removal" doesn't work on ManyToMany, although documentation says that it's supported (on IRC they've said that it may be a bug in documentation, that it is not really yet supported...they found no code changes when documentation was changed).
DOC:
http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#orphan-removal






[DDC-3200] [GH-1077] Support filter parameters in Configuration Created: 01/Jul/14  Updated: 01/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of jmikola:

Url: https://github.com/doctrine/doctrine2/pull/1077

Message:

Based on work done in doctrine/mongodb-odm#908

My understanding is that this makes it easier to setup filters at boot time, instead of having to fetch them from the collection later on.

For added context, the related PR from MongoDB ODM's Symfony bundle is doctrine/DoctrineMongoDBBundle#255






[DDC-3197] [GH-1074] [DDC-3160] Alternate fix for DDC-2996 bug Created: 26/Jun/14  Updated: 06/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of zimmermanj42:

Url: https://github.com/doctrine/doctrine2/pull/1074

Message:

The fix implemented for DDC-2996 seems to have broken quite a bit of code outside of Doctrine (for instance, the popular DoctrineExtensions project).

I'm not too well versed in Doctrine internals, but looking at the fix, I found it odd that an entity would live in both the insertion and update tracking in the unit of work.

This implementation should fix the case described in DDC-2996, while not creating any side effects with objects that are scheduled to be inserted.

I've ran this test with the Doctrine test suite and have also tested this change with the DoctrineExtensions project; unless I'm doing something wrong, it seems to have good results.

Again, I'm not too well versed in the inner workings of Doctrine, but I did a little research, poked around some code, and came up with this.



 Comments   
Comment by Doctrine Bot [ 06/Jul/14 ]

A related Github Pull-Request [GH-1057] was closed:
https://github.com/doctrine/doctrine2/pull/1057

Comment by Doctrine Bot [ 06/Jul/14 ]

A related Github Pull-Request [GH-1074] was closed:
https://github.com/doctrine/doctrine2/pull/1074





[DDC-3195] indexBy implementation on containsKey of PersistentCollection in EXTRA LAZY mode uses property name as column name instead of column name Created: 26/May/14  Updated: 26/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: jos de witte Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Any



 Description   

indexBy implementation on containsKey (and possibly other EXTRA LAZY implemented methods) of PersistentCollection in EXTRA LAZY mode uses property name as column name instead of column name for OneToMany collections

For example property = fieldName, column name field_name.
Set indexBy on OneToMany annotation to fieldName (as it should be ) and it tries to use fieldName in backend instead of field_name






[DDC-3191] [GH-1072] Fix attempt of traversing bool in FileLockRegion Created: 26/Jun/14  Updated: 26/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of kamazee:

Url: https://github.com/doctrine/doctrine2/pull/1072

Message:

Minor fix: on some platforms (i.e. ArchLinux) `glob()` returns `false` when nothing matched even though no errors occurred. As docs for `glob` say, such behavior is expected (see ‘Note’ at http://php.net/glob)

This made 1 existing test fail:

./vendor/bin/phpunit 
PHPUnit 4.3-g58f3a0e by Sebastian Bergmann.

Configuration read from /home/alex/git/doctrine2/phpunit.xml.dist

.............................................................   61 / 2495 (  2%)
........S.............E......................................  122 / 2495 (  4%)
.............................................................  183 / 2495 (  7%)
.............................................................  244 / 2495 (  9%)
.............................................................  305 / 2495 ( 12%)
.............................................................  366 / 2495 ( 14%)
.........................S...SSSS.S..........................  427 / 2495 ( 17%)
.............................................................  488 / 2495 ( 19%)
....................................................SS.......  549 / 2495 ( 22%)
.............................................................  610 / 2495 ( 24%)
.............................................................  671 / 2495 ( 26%)
.............................................................  732 / 2495 ( 29%)
.............................................................  793 / 2495 ( 31%)
.......................................................S.SSSS  854 / 2495 ( 34%)
SSSSSSSS.....................................................  915 / 2495 ( 36%)
.........................................SS..................  976 / 2495 ( 39%)
............S...S...........S..............................S. 1037 / 2495 ( 41%)
............................................................. 1098 / 2495 ( 44%)
..................S.......................................... 1159 / 2495 ( 46%)
.................................................SS.......... 1220 / 2495 ( 48%)
.......................S..................................... 1281 / 2495 ( 51%)
............................................................. 1342 / 2495 ( 53%)
............................................................. 1403 / 2495 ( 56%)
............................................................. 1464 / 2495 ( 58%)
............................................................. 1525 / 2495 ( 61%)
............................................................. 1586 / 2495 ( 63%)
.........S.................................................S. 1647 / 2495 ( 66%)
............................................................. 1708 / 2495 ( 68%)
............................................................. 1769 / 2495 ( 70%)
............................................................. 1830 / 2495 ( 73%)
............................................................. 1891 / 2495 ( 75%)
............................................................. 1952 / 2495 ( 78%)
............................................................. 2013 / 2495 ( 80%)
............................................................. 2074 / 2495 ( 83%)
............................................................. 2135 / 2495 ( 85%)
............................................................. 2196 / 2495 ( 88%)
............................................................. 2257 / 2495 ( 90%)
............................................................. 2318 / 2495 ( 92%)
............................................................S 2379 / 2495 ( 95%)
.......S......S.......S.....................S...........S.... 2440 / 2495 ( 97%)
.......................................................

Time: 14.37 seconds, Memory: 164.50Mb

There was 1 error:

1) Doctrine\Tests\ORM\Cache\FileLockRegionTest::testEvictAll
Invalid argument supplied for foreach()

/home/alex/git/doctrine2/lib/Doctrine/ORM/Cache/Region/FileLockRegion.php:204
/home/alex/git/doctrine2/tests/Doctrine/Tests/ORM/Cache/AbstractRegionTest.php:80

Traversing bool is no good and casting to array wouldn't hurt there as far as I can tell.






[DDC-3189] blob doctrine2 not inserting file in mysql Created: 24/Jun/14  Updated: 26/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.3
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Gustavo Monti Rocha Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux Ubuntu 12.04, Mysql 5


Attachments: PNG File a.png     Zip Archive testedoctrineupload.zip    

 Description   

I have an entity mapped as:

/**
 * @Entity @Table(name="Upload")
**/
class Upload
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;

/** @Column(type="string") **/
protected $nome;

/** @Column(type="blob") **/
protected $arquivo;

When I use this (WORKS)

 $query = "INSERT INTO Upload1 (name, size, type, content ) "."VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

 mysql_query($query)

When I use this doctrine way (NOT WORKING, if you try to get this file from mysql, return a corrupted or empty file)

$upload = new Upload();

$upload-> setContent($content);
$upload-> setName($fileName);
$upload-> setSize($fileSize);
$upload-> setType($fileType);

$entityManager->persist($upload);
$entityManager->flush();

My html file:

<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246"> 
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload    "></td>
</tr>
</table>
</form>


 Comments   
Comment by Gustavo Monti Rocha [ 24/Jun/14 ]

trying to insert this image

Comment by Gustavo Monti Rocha [ 24/Jun/14 ]

Using:
$entityManager->getConnection()>getConfiguration()>setSQLLogger( new Doctrine\DBAL\Logging\EchoSQLLogger());

Getting:
"START TRANSACTION" INSERT INTO Upload (name, type, size, content) VALUES (?, ?, ?, ?) array(4) { [1] => string(5) "a.png" [2] => string(9) "image/png" [3] => int(264547) [4] => string(270342) "‰PNG  \0\0\0 IHDR\0\0@\0\0„\0\0\0v/jõ\0\0\0sBITÛáOà\0\0\0tEXtSoftware\0gnome-screenshotï¿>\0\0 \0IDATxœìw|TÅöÀÏܲ{·$›^I¥“Лҫ€ QPô©`

{êÏγ÷^ŸýYÀ‚ˆ\"¢ô %½m’í햙ߛ,›mÙe¾>š½÷Ι™3gæÎœ;]3ÿR P( …B¡P( …\0\0³X¾Ÿ†X]ŸÞ]ÿÂôP(\0àÜnñ¯N…B¡P( …B¡P(„B\0\0\\.÷ñ’ÊüünݺÇøîÚl¶m;æçfh4\0@BUR)”3®©šR( …B¡P( …ræa2Y+«ëV\0@4……}

Y–<¸§×KEÙ±ãHaaßâ¢#n·\0Ãf¦§ÄÇÇþÅé¦PÎ0¨‹B¡P( …B¡P(g(„ÙttTJ5\"\0< g§æefe¥ú?3rd¿Š £V.W7ì&\0˜âF+‰ø%9uÆF\0HINø«pôx…ZÅuÉL¥“Ô(‘Ù³¯\0ú÷í}ã¶9°A‡Óãr¥Åé¯n"... } array(4)

{ [1] => string(6) "string" [2] => string(6) "string" [3] => string(7) "integer" [4] => string(4) "blob" }

"COMMIT"

Comment by Steve Müller [ 26/Jun/14 ]

This looks more like a DBAL issue. Can you please provide the error/exception message that you receive from the driver/database server? Also do you use PDOMySQL or mysqli driver?

Comment by Gustavo Monti Rocha [ 26/Jun/14 ]

Steve,

I'm not getting any error/expection. Table looks like insert the blob file but when I try to download it is corrupted. You could see at getting .zip file and executing it.

I'm using PDOMysql.

Comment by Marco Pivetta [ 26/Jun/14 ]

This would probably need a data sample to reproduce the issue.

Comment by Gustavo Monti Rocha [ 26/Jun/14 ]

Marco,

you could use project attached and image in order to reproduce.

Comment by Marco Pivetta [ 26/Jun/14 ]

Gustavo Monti Rocha you should actually provide a functional test for this in case, see https://github.com/doctrine/dbal/tree/master/tests/Doctrine/Tests/DBAL

For example, the zip file you uploaded fails on various includes, and doesn't show the failures to me.





[DDC-3188] Call to a member function getValue() on a non-object in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php Created: 24/Jun/14  Updated: 27/Jun/14

Status: Reopened
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Daniel Imhoff Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.4.11
opensuse
apache2



 Description   

This is the line that causes the fatal error: https://github.com/doctrine/doctrine2/blob/v2.4.2/lib/Doctrine/ORM/UnitOfWork.php#L678

This is the association that is breaking it (i.e. reflFields[ 'user' ] is a non-object):

Tweet.php
/**
 * @ManyToOne(targetEntity="User")
 * @JoinColumn(name="user_id", referencedColumnName="id")
 *
 * @var User
 */
protected $user;

This is the pk of the referenced entity.

User.php
/**
 * @Id
 * @Column(name="id", type="bigint", nullable=false)
 *
 * @var int
 */
protected $id;

If an exception was thrown due to missing metadata information, I could catch it, but fatal errors due to this bug have been crashing our scripts and they've had to be manually restarted.

Let me know what other information is needed.

Full stack trace:

PHP 5. Doctrine\ORM\EntityManager->flush() our_code.php
PHP 6. Doctrine\ORM\UnitOfWork->commit() vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:389
PHP 7. Doctrine\ORM\UnitOfWork->computeChangeSets() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:297
PHP 8. Doctrine\ORM\UnitOfWork->computeScheduleInsertsChangeSets() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:703
PHP 9. Doctrine\ORM\UnitOfWork->computeChangeSet() vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:404
PHP Fatal error: Call to a member function getValue() on a non-object in vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 678



 Comments   
Comment by Marco Pivetta [ 24/Jun/14 ]

Did you actually validate your mappings?

Comment by Daniel Imhoff [ 24/Jun/14 ]

I did not validate the mapping. I did not know about the orm:validate-schema until just now. I will fix these errors and resubmit if there is still an issue.

Sorry about that, thanks.

Comment by Daniel Imhoff [ 24/Jun/14 ]

The tweet and user relationship is not in the list of invalid mappings.

Comment by Marco Pivetta [ 26/Jun/14 ]

Are User and Tweet in the same namespace?

Comment by Daniel Imhoff [ 27/Jun/14 ]

Yes, and I've since then used the FQNS. I would get a class not found error when validating schema.
This is something that I know can't really be debugged by you guys, I was just hoping for a little direction. We are using memcache to store our metadata, and we are clearing and regenerating the metadata during every deploy (it is not autogenerated). I'm now using a commit hash as the namespace of the metadata, so we'll see if this fixes the issue.

Comment by Marco Pivetta [ 27/Jun/14 ]

It looks like a typo (CasESensiTIViTy issue) to me.





[DDC-3186] [GH-1069] added method to be able to reuse the console application Created: 24/Jun/14  Updated: 24/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of anho:

Url: https://github.com/doctrine/doctrine2/pull/1069

Message:

This comes in handy, when you want to do more with the actual application object then just to run it.






[DDC-3184] Invalid hydration of entities using ManyToOne relation via queryBuilder Created: 23/Jun/14  Updated: 23/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4, 2.4.1, 2.4.2, 2.4.3
Fix Version/s: 2.5
Security Level: All

Type: Bug Priority: Major
Reporter: Dmitry Korotovsky Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File DDC3184Test.php    

 Comments   
Comment by Dmitry Korotovsky [ 23/Jun/14 ]

In master branch all works perfect

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

Marco Pivetta, fix in 2.5 branch will be ported to 2.4 stable version?

Comment by Marco Pivetta [ 23/Jun/14 ]

Dmitry Korotovsky first we'll need to check what commit fixed the issue. Could you git bisect with your test?

Comment by Dmitry Korotovsky [ 23/Jun/14 ]

Yes, i found it: https://github.com/doctrine/doctrine2/commit/38b683838648b549aad0e38ce88c70b6393755b3

Comment by Marco Pivetta [ 23/Jun/14 ]

Assigning to Guilherme Blanco, since he is the author of the fix.





[DDC-3183] Add JsonSerializable to Collections Created: 22/Jun/14  Updated: 22/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 3.0
Fix Version/s: 3.0
Security Level: All

Type: New Feature Priority: Major
Reporter: Gabriel Bull Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: collection, orm


 Description   

Implement this:

http://www.php.net/manual/fr/class.jsonserializable.php

Can't really make this claim if Doctrine is not implementing basic interfaces for collections:

> The missing (SPL) Collection/Array/OrderedMap interface.






[DDC-3182] [GH-1066] Added jsonSerialize method to PersistentCollection Created: 22/Jun/14  Updated: 22/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of gabrielbull:

Url: https://github.com/doctrine/doctrine2/pull/1066

Message:

Added jsonSerialize.

Here is to commit on collections:
https://github.com/doctrine/collections/pull/33



 Comments   
Comment by Doctrine Bot [ 22/Jun/14 ]

A related Github Pull-Request [GH-1066] was closed:
https://github.com/doctrine/doctrine2/pull/1066





[DDC-3181] Class Table Inheritance - wrong table order on insert with more than one level of inheritance Created: 20/Jun/14  Updated: 20/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: M. de Lange Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

oracle



 Description   

note: this issue seems the same as DDC-732

When using class table inheritance with multiple levels i.e.:
Object -> SolidObject -> Building -> House
(House inherits from Building, Building from SolidObject, SolidObject from Object)

Object has the discriminator column and mapping. When persisting a new House entity I get a foreign key error because there is no row in the Building table.

I searched in the Code and found the problem. In the class "Doctrine\ORM\Persisters\JoinedSubclassPersister" in function "executeInserts()" around line 146 the array $subTableStmts is first declared and then filled with insert statements. The statement of the House-table is first added, and then the parent-tables (except the root-table "Object", since that one is executed first).

So the order in which the insert statements are executed is:
1 Insert into Object ...
2 Insert into House ... (which causes the error)
3 insert into Building ...
4 Insert into SolidObject

I edited the source to insert into the parent-tables (first SolidObject, then Building) before inserting into the table that belongs to the class that is persisted (House). And this works fine in my case.






[DDC-3176] Table-inheritance and OneToOne association as entity ID Created: 18/Jun/14  Updated: 18/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Elioty Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: association, identity, inheritance, orm
Environment:

Ubuntu 14.04, PHP 5.5.9-1ubuntu4, Symfony 2.5



 Description   

The issue is fully described here:
http://stackoverflow.com/questions/24265731/symfony-doctrine-class-table-inheritance-and-foreign-key-as-primary-key






[DDC-3174] Query Cache not correct working when using SQLFilter Created: 17/Jun/14  Updated: 17/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Benno Eggnauer Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: cache, sqlfilter


 Description   

We have an SQLFilter to filter on entities with a specific Trait implemented. The filter is very easy:

$res = $targetTableAlias . '.agency_id = ' . $this->getCurrentAgencyId();

On our system we have the query cache enabled, this works as long the "AgencyId" doesn't change. When the ID changes, the query cache seems to return the wrong (old cache) query.



 Comments   
Comment by Marco Pivetta [ 17/Jun/14 ]

I'm not sure if this case should be contemplated by the ORM. Filters are low-level and supposed to be stateless (services).

Comment by Benno Eggnauer [ 17/Jun/14 ]

OK, we can disable the query cache for this case. But then should at least the documentation be updated, which explicitly mentions to use filter for locales, which are also not stateless: http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html#example-filter-class

Also in the query cache chapter: http://doctrine-orm.readthedocs.org/en/latest/reference/caching.html#query-cache

It is highly recommended that in a production environment you cache the transformation of a DQL query to its SQL counterpart. It doesn’t make sense to do this parsing multiple times as it doesn’t change unless you alter the DQL query.

Comment by Marco Pivetta [ 17/Jun/14 ]

Benno Eggnauer can you eventually provide a pull request?





[DDC-3171] [GH-1060] [DDC-3170] SimpleObjectHydrator fails to get discriminator column from mapped SQL result Created: 17/Jun/14  Updated: 17/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of ureimers:

Url: https://github.com/doctrine/doctrine2/pull/1060

Message:

This PR fixes DDC-3170(http://www.doctrine-project.org/jira/browse/DDC-3170).

When querying a simple entity which uses single table- or class table inheritance using simple object hydration (``AbstractQuery::HYDRATE_SIMPLEOBJECT``), the mapped discriminator column was not retrieved correctly.

If the column got an alias during result set mapping other than it's actual name (e.g. ``type34`` instead of ``type``) than this alias wasn't correctly resolved when retrieving the discriminator column from the SQL result set.



 Comments   
Comment by Ulf Reimers [ 17/Jun/14 ]

I created DDC-3170 for this and put it into the PR like stated in https://github.com/doctrine/doctrine2/blob/master/CONTRIBUTING.md#doctrinebot-tickets-and-jira.

Unfortunately the BOT still created this issue here which can be removed in my opinion.

Comment by Doctrine Bot [ 17/Jun/14 ]

A related Github Pull-Request [GH-1060] was closed:
https://github.com/doctrine/doctrine2/pull/1060





[DDC-3170] SimpleObjectHydrator fails to get discriminator column from mapped SQL result Created: 17/Jun/14  Updated: 17/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Ulf Reimers Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hydrator, inheritance, orm


 Description   

When querying a simple entity which uses single table- or class table inheritance using simple object hydration (AbstractQuery::HYDRATE_SIMPLEOBJECT), the mapped discriminator column is not retrieved correctly.

Example:

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"product" = "Product"})
 */
abstract class AbstractEntity
{
    /** @Id @Column(type="integer") @GeneratedValue */
    public $id;
}

/**
 * @Entity
 */
class Product extends AbstractEntity
{
}

$manager->createQueryBuilder()
                ->select('p')
                ->from('Product, 'p')
                ->getQuery()
                ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT);

// -> Exception: [Doctrine\ORM\Internal\Hydration\HydrationException] The discriminator column "type" is missing for "Product" using the DQL alias "p".

The SQL statement used is equal to:

SELECT r0_.id AS id0, r0_.type AS type1 FROM Product r1_ INNER JOIN AbstractEntity r0_ ON r1_.id = r0_.id

As you can see, the type column is given an alias of type1. This is saved in the ResultSetMapping of the request but not taken into account when actually retrieving the discriminator column back from the SQL result.

The problem is inside SimpleObjectHydrator#hydrateRowData().

When the discriminator column name is fetched via

$discrColumnName = $this->_platform->getSQLResultCasing($this->class->discriminatorColumn['name']);

the result is simply type which is wrong because the alias is type2. This can be fixed by adding

if ($metaMappingDiscrColumnName = array_search($discrColumnName, $this->_rsm->metaMappings)) {
    $discrColumnName = $metaMappingDiscrColumnName;
}

right after the column retrieval, because then the alias of the meta field type is correctly taken into account.

I'll create a PR with a unit test for this fix right after this ticket's creation.

I hope I'm doing everything right, this is my first contribution.



 Comments   
Comment by Ulf Reimers [ 17/Jun/14 ]

PR is https://github.com/doctrine/doctrine2/pull/1060

I though that I first create a ticket, then propose a fix for that with a PR and by adding the Ticket ID in the PR-Title they are linked automatically. But unfortunately it seems I've done something wrong there.

Comment by Doctrine Bot [ 17/Jun/14 ]

A related Github Pull-Request [GH-1060] was closed:
https://github.com/doctrine/doctrine2/pull/1060





[DDC-3169] ManyToMany association fails when joining on a single column of a composity key Created: 17/Jun/14  Updated: 17/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Bram Gerritsen Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: association, composite, orm


 Description   

I have two entities with a ManyToMany association between them. The first entity Campsite has a composite key (campsiteID, year). The second entity Region has a single key (regionID).
I want to create an association between Campsite::campsiteID and Region::regionID. See the entities below.

Campsite
/**
 * @ORM\Table(name="Campsite")
 */
class Campsite
{
    /**
     * @ORM\Id
     * @ORM\Column(name="campsiteID", type="integer", precision=0, nullable=false)
     */
    protected $campsiteID;

    /**
     * @ORM\Id
     * @ORM\Column(name="year", type="smallint", precision=0, nullable=false)
     */
    protected $year;

    /**
     * @ORM\ManyToMany(targetEntity="AcsiGeo\Entity\Region", fetch="EAGER", cascade={"detach"})
     * @ORM\JoinTable(name="CampsiteRegion",
     *   joinColumns={
     *     @ORM\JoinColumn(name="campsiteID", referencedColumnName="campsiteID", nullable=false)
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="regionID", referencedColumnName="regionID", nullable=false)
     *   }
     * )
     * @var \Doctrine\Common\Collections\ArrayCollection $regions
     */
    protected $regions;
}
Region
/**
 * @ORM\Table(name="Region")
 */
class Region
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(name="regionID", type="integer", precision=0, nullable=false)
     */
    protected $regionID;
}

I run the following code to persist a new one.

$campsite = new Campsite();
$campsite->setCampsiteID(111111);
$campsite->setYear(2014);

$region = new Region();
$region->setRegionID(1);
$campsite->addRegion($region);

$em->persist($region);
$em->persist($campsite);
$em->flush();

This results in a record added to the CampsiteRegion table:

campsiteID : 2014
regionID: 1

This is clearly wrong as the value of the year field is added to the campsiteID column.

While debugging the problem I've found an issue with the method to determine the params in ManyToManyPersister on line 147.
The following code pops the last identifier from the array of identifiers.

$params[] = $isRelationToSource ? array_pop($identifier1) : array_pop($identifier2);

In my case:

array(
    'campsiteID' => 111111,
    'year' => 2014
)

Which picks 2014 as the value to use.
When I change the code to get the actual column from the array everything works as expected.

$params[] = $isRelationToSource ? $identifier1[$joinTableColumn] : $identifier2[$joinTableColumn];

I am not 100% sure if this change will have some side effects / edge case I'm not aware of.

For the time being I have fixed the problem bij just reversing the properties in my class, but this is not a real fix of course.






[DDC-3165] one to zero or one with identity through foreign entity Created: 13/Jun/14  Updated: 13/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Andries Seutens Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   
<?php

/**
 * @Entity
 */
class User
{
    /** 
     * @Id @Column(type="integer") 
     * @GeneratedValue 
     */
    private $id;
    
    /**
     * @ORM\OneToOne(targetEntity="Address")
     *
     * @var Address
     */
    private $address;
    
    public function getAddress()
    {
        return $this->address;
    }
}

/**
 * @Entity
 */
class Address
{
    /**
     * @Id @OneToOne(targetEntity="User") 
     */
    private $user;
    
    public function foo()
    {}
}


?>

The relation between user and address is one to zero or one. When a record exists on both sides, everything goes fine. When the right side (address) does not have a relevant record, calling $user->getAddress(); always returns an instance. Calling a method on that instance results in an exception:

Fatal error: Uncaught exception 'Doctrine\ORM\EntityNotFoundException' with message 'Entity of type 'Address' was not found.' in doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php on line 176

Expected behaviour:
$user->getAddress() should return NULL when the right side is empty.

NOTES:
Mind that the address is identified through a foreign entity (User)






[DDC-3164] [GH-1057] Add failing test for DDC-3160 Created: 12/Jun/14  Updated: 06/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of flack:

Url: https://github.com/doctrine/doctrine2/pull/1057

Message:

See http://www.doctrine-project.org/jira/browse/DDC-3160



 Comments   
Comment by Doctrine Bot [ 06/Jul/14 ]

A related Github Pull-Request [GH-1057] was closed:
https://github.com/doctrine/doctrine2/pull/1057

Comment by Doctrine Bot [ 06/Jul/14 ]

A related Github Pull-Request [GH-1074] was closed:
https://github.com/doctrine/doctrine2/pull/1074





[DDC-3161] [GH-1054] SQLFilters enahancements Created: 10/Jun/14  Updated: 10/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of v3labs:

Url: https://github.com/doctrine/doctrine2/pull/1054

Message:

SQL filters in Doctrine are a bit too limited for my taste.
This pull request makes the current connection available inside sql filter classes.
The connection is needed to quote identifiers or values and generate sql statements for the current database. (sample use-case https://github.com/Atlantic18/DoctrineExtensions/blob/master/lib/Gedmo/SoftDeleteable/Filter/SoftDeleteableFilter.php)
Currently you can access the connection only through reflection which let's face it - is a hack.

I've also made the class depend on EntityManagerInterface instead of EntityManager.

There's a test for the new method.






[DDC-3156] [GH-1050] DDC-3120 -- Catch ReflectionException for internal classes in ClassMetad... Created: 06/Jun/14  Updated: 06/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of jbottigliero:

Url: https://github.com/doctrine/doctrine2/pull/1050

Message:

...ataInfo

I���m having an issue in relation to http://www.doctrine-project.org/jira/browse/DDC-3120 ��� When using ReflectionClass#newInstanceWithoutConstructor(); I���m getting a ReflectionException due to the class not being internal��� it���s resolveable by adding a try/catch to use ReflectionClass#newInstance. BUT, I���d like to know if there is something else going on here��� running PHP 5.5.13






[DDC-3155] orm:convert-mapping drops underscores from Doctrine type names specified in DB comments Created: 05/Jun/14  Updated: 05/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: John Flatness Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If you run orm:convert-mapping on a schema with comments like (DC2Type:json_array), the type name does get picked up, but the underscore is removed, so the type that ends up in the generated mapping's @Column annotation is jsonarray, not json_array.

The underscore being removed also seems to be affecting the EntityGenerator's attempt to map to correct PHP types for the @var annotation: that's showing up as just @var jsonarray even though the EntityGenerator should be mapping that to array. So it looks like the underscore is probably getting dropped at an earlier stage.






[DDC-3149] [GH-1046] Fix the "Erroneous data format for unserializing" error message Created: 03/Jun/14  Updated: 03/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of peterjmit:

Url: https://github.com/doctrine/doctrine2/pull/1046

Message:

Backport patch from PR #1045 to 2.3 branch.

@ocramius - I'm not sure if this is viable, but based on the comments from people it could be helpful to have this fixed in 5.3? I'm not 100% sure whether PHP or Doctrine is at fault here?



 Comments   
Comment by Doctrine Bot [ 03/Jun/14 ]

A related Github Pull-Request [GH-1046] was closed:
https://github.com/doctrine/doctrine2/pull/1046





[DDC-3148] ResultSetMappingBuilder::generateSelectClause ignores quoted column names Created: 02/Jun/14  Updated: 02/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Christian Ruhstaller Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If an entity has a quoted column (Magic Words etc.) and you want to use "generateSelectClause" for the specific entity it won't return the quoted name, just the plain name. If the name is a SQL Magic Word the corresponding SQL will fail.

Exp.: "profile.real" (wrong) instead of "profile.`real`".

File: Doctrine/ORM/Query/ResultSetMappingBuilder.php
Function: generateSelectClause

Line 445:
$sql .= " AS " . $columnName;

Example Entity:
...
class Profile

{ /** * @ORM\Column(name="`real`", type="boolean") */ protected $real=false; }




[DDC-3147] [GH-1045] Fix the "Erroneous data format for unserializing" error message Created: 30/May/14  Updated: 30/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of marmotz:

Url: https://github.com/doctrine/doctrine2/pull/1045

Message:

cf http://www.doctrine-project.org/jira/browse/DDC-3120



 Comments   
Comment by Doctrine Bot [ 30/May/14 ]

A related Github Pull-Request [GH-1045] was closed:
https://github.com/doctrine/doctrine2/pull/1045





[DDC-3146] Hydrator memory leak when using iterator Created: 30/May/14  Updated: 30/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Emiel Nijpels Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hydrator, leak, memory
Environment:

PHP 5.4.21, OS X 10.9.3



 Description   

When the hydrator iterate() function is invoked, a new event is added to the event manager with a reference to the current hydrator object. This reference is never cleared which causes the hydrator object to never be cleared from memory by the PHP garbage collection.

/doctrine/orm/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php
$evm = $this->_em->getEventManager();
$evm->addEventListener(array(Events::onClear), $this);

The effects of this bug are best visible when creating multiple iterator objects after each other in a repository:

// Loop through test code 10 times
for ($f = 0; $f < 10; $f++) {
    // Create test query
    $query = $this->createQueryBuilder('p')->getQuery();

    // Create IterableResult object
    $iterableResult = $query->iterate();

    // Loop through the iterator
    foreach ($iterableResult as $row) {}

    // Print out memory usage
    print(memory_get_usage() . PHP_EOL);
}

This results in the following output:

10536552
10549920
10563288
10576664
10590040
10603416
10616792
10630168
10643608
10656984

Notice how the used memory increases by about 13KB after each iteration.
To stop this memory leak the following code can be added to the end of the cleanup() function in the AbstractHydrator class:

$evm = $this->_em->getEventManager();
$evm->removeEventListener(array(Events::onClear), $this);

The output is now:

10537920
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048

The reference to the event manager is now automatically removed in the cleanup function which allows the hydrator object to be cleaned up by the garbage collection function in PHP.






[DDC-3136] DQL JOIN association return null Created: 24/May/14  Updated: 24/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: DQL, Mapping Drivers, ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Raphael Parazols Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony2



 Description   

Hello,
I observe a strange behavior of a query result done by DQL (only tested DQL in fact). In the last entry of my result, the joined entity are returned to null

My tables are:

Entity1
/**
 * @ORM\Table(name="entity1")
 * @ORM\Entity()
**/
class Entity1
{	
	 /**
     * @ORM\Column(name="entity1_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
	protected $entity1_Id; 
	
	/**
	* @ORM\Column(name="entity1_text", type="string")
	*/
    protected $entity1_Text;
}
Entity2
/**
 * @ORM\Table(name="entity2")
 * @ORM\Entity()
**/
class Entity2
{	
        /**
	* @ORM\OneToOne(targetEntity="Entity1")
	* @ORM\JoinColumn(name="entity1_id", referencedColumnName="entity1_id")
	* @ORM\Id
	*/
	protected $entity1_id; 
    
	/**
	* @ORM\ManyToOne(targetEntity="Entity3")
	* @ORM\JoinColumn(name="entity3_id", referencedColumnName="entity3_id")
	*/
	protected $entity3; 
}
Entity3
/**
 * @ORM\Table(name="entity3")
 * @ORM\Entity()
**/
class Entity3
{	
	 /**
     * @ORM\Column(name="entity3_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
	protected $entity3_Id; 
	
	/**
	* @ORM\Column(name="entity3_text", type="string")
	*/
    protected $entity3_Text;
}

So when I do a simple request like this:

DQL Request
SELECT ent2, ent3 FROM f4cIndexBundle:Entity2 ent2 JOIN ent2.entity3 ent3

The result is looks like this

Result NOK
array (size=2)
  0 => 
    object(f4c\IndexBundle\Entity\Entity2)[550]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[502]
          ...
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[497]
          protected 'entity3_Id' => int 2
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 2' (length=29)
  1 => 
    object(f4c\IndexBundle\Entity\Entity2)[498]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[499]
          ...
     protected 'entity3' => null

The entity3 of the last result is never joined and set to null (it's not possible because of the JOIN no ?)
I spent to days on this and I observed that when I add a property in my entity 2 like this

Entity2
/**
 * @ORM\Table(name="entity2")
 * @ORM\Entity()
**/
class Entity2
{	
    ...
    /**
	* @ORM\Column(name="entity2_text", type="string")
	*/
    protected $entity2_Text;
}

The result is ok

Result OK
array (size=2)
  0 => 
    object(f4c\IndexBundle\Entity\Entity2)[550]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[498]
         ...
      protected 'entity2_Text' => string 'TEXT2' (length=5)
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[499]
          protected 'entity3_Id' => int 1
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 1' (length=29)
  1 => 
    object(f4c\IndexBundle\Entity\Entity2)[494]
      protected 'entity1_id' => 
        object(Proxies\__CG__\f4c\IndexBundle\Entity\Entity1)[495]
          ...
      protected 'entity2_Text' => string 'TEXT1' (length=5)
      protected 'entity3' => 
        object(f4c\IndexBundle\Entity\Entity3)[496]
          protected 'entity3_Id' => int 2
          protected 'entity3_Text' => string 'TEXT OF ENTITY 3 - SPECIFIC 2' (length=29)

Is it normal ? Is this a kwon issue ?

Thanks for your help

Raphael P.






[DDC-3135] Unnecessary SELECT after updating of versioned table Created: 23/May/14  Updated: 23/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: ikti Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.5.9-1ubuntu4 (cli) (built: Apr 9 2014 17:11:57)



 Description   

When I update entity with version doctrine generates 2 SQLs:

INSERT INTO TableA (key, value) VALUES (1, 1);
SELECT version FROM TableA WHERE key = 1;

OR

UPDATE TableA SET value= 2, version = version + 1 WHERE key = 1 AND version = 1;
SELECT version FROM TableA WHERE key = 1;

Not only second query is unnecessary (version value is always 1 after persisting and is always prev version + 1 after successful update) but can also read incorrect value if row is updated between update and select statement. In this case entity manager will have outdated data, but most recent version.






[DDC-3134] Inconsistent defaults for onDelete when defining many-to-many relations Created: 23/May/14  Updated: 23/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Adria Lopez Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony 2.5.0-BETA2



 Description   

When defining a relation with the following annotation:

/**
 * @ORM\ManyToMany(targetEntity="A\B\C")
 */

The following SQL is generated for the foreign key constraints:

ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AA76ED395 FOREIGN KEY (something1) REFERENCES thing2 (id) ON DELETE CASCADE;
ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AF8BD700D FOREIGN KEY (something2) REFERENCES thing1 (id) ON DELETE CASCADE;

As it can be seen, the default seems to be to include ON DELETE CASCADE. This feels like a dangerous behaviour (and I couldn't find it documented), but fair enough. The inconsistency comes when adding:

/**
 * @ORM\ManyToMany(targetEntity="A\B\C")
 * @ORM\JoinTable(name="the_table",
 *      joinColumns={@ORM\JoinColumn()},
 *      inverseJoinColumns={@ORM\JoinColumn()}
 * )
 */

In this case, even if we are not providing any values for the join and inverse join columns, we get:

ALTER TABLE the_table ADD CONSTRAINT FK_A63A409AA76ED395 FOREIGN KEY (something1) REFERENCES something2 (id);
ALTER TABLE user_unit ADD CONSTRAINT FK_A63A409AF8BD700D FOREIGN KEY (something2) REFERENCES something1 (id);

As it can be seen, the ON DELETE CASCADE is gone.

I understand this is the case because, when giving empty JoinColumn annotations it's not the engine defaults that are processed, but the inferred values for the annotation. Still, this seems to be either a bug or an undocumented behaviour.

Am I doing anything wrong here? Should this be looked into?






[DDC-3130] [GH-1033] [WIP] Lazy criteria for ManyToMany collection Created: 18/May/14  Updated: 18/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of bakura10:

Url: https://github.com/doctrine/doctrine2/pull/1033

Message:

This continues my previous work on making Criteria most efficient.

Currently we are wrapping matching calls on repositories and matching calls on EXTRA_LAZY associations around a LazyCriteria. However, ManyToMany are still completely loaded: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/PersistentCollection.php#L874

This is still problematic from a performance point of view because count, contains... cannot be optimized. I think the solution is similar to previous one, hence creating a Lazy collection for that kind of associations.

However, this is really tricky to do because of the whole mess inside the persisters (can't wait for them to be completely refactored, it's getting really hard to maintain this mess ).






[DDC-3122] Querying entities with ResolveTargetEntity Created: 14/May/14  Updated: 15/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Heo Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello

The problem refers to a following situation:
You have 2 classes that use a quite simple inheritance and an interface:

interface CInterface { /* ... */ }
class AClass implements CInterface { /* ... */ }
class BClass extends class AClass { /* ... */ }

When we configure the ResolveTargetEntityListener the following way:

array(
  'CInterface' => 'BClass'
)

when using the entity manager to find an entity:

$entityManager->find('BClass', $id);

we'll get a following Doctrine\DBAL\DBALException:

An exception occurred while executing 'SELECT t1.id AS id2 FROM bclass_table_name t1 WHERE t0.id = ?' with params [1]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 't0.id' in 'where clause'

As you can see the column names are generated properly but the WHERE clause has an invalid refference to t0 table (should be t1).

Similar problem:

http://stackoverflow.com/questions/17588682/doctrine-inheritance-replacement



 Comments   
Comment by Marco Pivetta [ 14/May/14 ]

Is AClass a mapped superclass or the root of the inheritance?

Comment by Heo [ 15/May/14 ]

AClass is the root of the inheritance. I would like to add that the only problem is the "find" method. Database relations are created properly (with the SchemaTool), all keys refer to proper columns.

Comment by Marco Pivetta [ 15/May/14 ]

Heo can you abstract a test case for this?





[DDC-3117] [GH-1027] Support for Partial Indexes for PostgreSql and Sqlite Created: 07/May/14  Updated: 16/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, postgresql, sqlite

Issue Links:
Dependency
depends on DBAL-900 [GH-600] Support for Partial Indexes ... Open

 Description   

This issue is created automatically through a Github pull request on behalf of PowerKiKi:

Url: https://github.com/doctrine/doctrine2/pull/1027

Message:

Support for Partial Indexes was available in Doctrine 1 following
http://www.doctrine-project.org/jira/browse/DC-82. This commit
reintroduce support for Doctrine 2. We use the same syntax with an
optionnal "where" attribute for Index and UniqueConstraint.

It is unit-tests covered and documented in manual. This Pull Request depends on https://github.com/doctrine/dbal/pull/600. So they should both be merged or rejected together.

Thanks for your time !



 Comments   
Comment by Adrien Crivelli [ 07/May/14 ]

This patch depends on DBAL-900. So they should both be merged or rejected together.

Comment by Doctrine Bot [ 16/May/14 ]

A related Github Pull-Request [GH-600] was closed:
https://github.com/doctrine/dbal/pull/600





[DDC-3115] UnitOfWok can't access proxies protected property Created: 04/May/14  Updated: 04/May/14

Status: Reopened
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Machete Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

php5.5.11-1~dotdeb.1
debian 7.5 64bit
apache2
doctrine-orm-module 0.8.0


Attachments: PNG File doctrine-error.PNG    

 Description   

Running the code on different environments for a while now, I have never had any problems. Recently I installed the code onto a different server and I've been experiencing the following issue:

> Fatal error: Cannot access protected property DoctrineORMModule\Proxy_CG_\Page\Entity\PageRevision::$date in src/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 2596

I am absolutely clueless, why this happens. It seems to be affecting only specific data rows, as you might reproduce here: http://de.serlo.org/pages

The field is defined as followed:

    /**
     * @ORM\Column(type="datetime", options={"default"="CURRENT_TIMESTAMP"})
     */
    protected $date;

However, the exact same database snapshot works fine here: http://ptr.serlo.org/pages

Attached you will find a screenshot of the datarows. The yellow ones mark each one working and one not working row.

I have no idea what the problem is here.



 Comments   
Comment by Marco Pivetta [ 04/May/14 ]

Discussed this on IRC - very tricky, seems like one of the servers has the reflection property not set to "accessible"

Comment by Machete [ 04/May/14 ]

Adding `$class->reflFields[$field]->setAccessible(true)` before line 2596 resolved this issue. Even after removing it, everything worked fine.

note to self:
> [18:23] <@ocramius> machete_: can you find out where that particular property is instantiated?
> [18:23] <@ocramius> should be in `ClassMetadataInfo::wakeUpReflection()` or such
> [18:25] <@ocramius> if you find that again, consider looking at locations in the code where `new ReflectionClass()` is instantiated





[DDC-3113] Associated entity with "cascade" persist that is eagerly loaded doesn't get saved when its parent is flushed Created: 01/May/14  Updated: 01/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Juraj Seffer Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Address entity definition within User class
/**

  • Address
    *
  • @ORM\OneToOne(targetEntity="Address", fetch="EAGER", cascade="persist")
  • @var \Application\Entity\Address
    */
    protected $address;

When User gets loaded via Doctrine, the resulting Address object within the User is not a proxy object but the concrete class specified in targetEntity. When trying to persist the User:

$entityManager->persist($user);
$entityManager->flush($user);

User object gets saved and another associated entity that is lazy loaded does get saved. What doesn't get saved into the database is the Address object. No exceptions are thrown, the Address object is simply ignored.






[DDC-3110] paginator doesn't respect order by clause when using the fetchJoinCollection flag Created: 30/Apr/14  Updated: 30/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Greg Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

MariaDB 5.5



 Description   

I have a DQL query with a ORDER BY clause.
When I paginate the result with new Paginator($query, $fetchJoinCollection = true); the orderind isn't correct.
The order is lost in the second request (Perform a Limit Subquery with DISTINCT to find all ids of the entity in from on the current page)

It creates a SQL query like that :
SELECT
DISTINCT id0
FROM
(
SELECT
d0_.id AS id0,
d0_.name AS name1,
d0_.note AS note2,
FROM
data d0_
ORDER BY
d0_.note DESC
) dctrn_result
LIMIT
20 OFFSET 0

The external SELECT don't keep the order so it just fetch the 20 first elements from the whole table.






[DDC-3109] [Doctrine\ORM\Mapping\MappingException] Invalid field override named 'xxx' for class 'Entity\xxx' Created: 30/Apr/14  Updated: 26/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM, Tools
Affects Version/s: 2.3
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: david pichsenmeister Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

kubuntu 14.04, php 5.5.9, MySQL 5.5


Attachments: File Organization.php     File User.php    
Issue Links:
Duplicate
duplicates DDC-2693 Attribute/association overrides shoul... Open

 Description   

Subclass should override association, but on generating entities, error:

[Doctrine\ORM\Mapping\MappingException]
Invalid field override named 'settings' for class 'Entity\Organization'.

is thrown. also, when updating schema, the assocations in the subclass are ignored (means are not present in the database).



 Comments   
Comment by Alexandre PAIXAO [ 23/May/14 ]

I think it is a duplicate of this bug : http://www.doctrine-project.org/jira/browse/DDC-2693





[DDC-3108] Criteria cannot reference a joined tables' fields when used with an ORM QueryBuilder Created: 30/Apr/14  Updated: 30/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: DQL, ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Chris Rog Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: criteria, dql, orm, querybuilder


 Description   

This regression was introduced in 2.4.2 with the addition of the "rootAlias" stuff. Basically, the hard-coded addition of the rootAlias + "." prevents any Criteria object from referencing any field that isn't on the first table selected.

Example:
// Assume $repo is a valid EntityRepository and $value is some scalar value.
$qb = $repo->createQueryBuilder('T1')->join('T1.field', 'T2');

$criteria = new Comparison('T2.field2', Comparison::EQ, $value);

$qb->addCriteria($criteria);
$dql = $qb->getDQL();

$dql is now (roughly) equal to:
SELECT T1 FROM <entityclass> T1 JOIN T1.field T2 WHERE T1.T2.field2 = <value>

Evaluating this causes QueryExceptions to be thrown; usually something along the lines of "Expected Doctrine\ORM\Query\Lexer::<token>, got '.'"

There's a similar issue involving ordering by a related field for the same reason.






[DDC-3105] Doctrine Console Error (ORMPurger) Created: 29/Apr/14  Updated: 29/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Carlos Mendoza Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: Cli, schematool


 Description   

In symfony2 the command doctrine:fixtures:load Fails One-To-Many, Self-referencing using Doctrine\Common\DataFixtures\Purger\ORMPurger in example:

class DescriptionArea

{ //.. /** * @ORM\OneToMany(targetEntity="DescriptionArea", mappedBy="parent") */ protected $descriptionAreas; /** * @ORM\ManyToOne(targetEntity="DescriptionArea", inversedBy="descriptionAreas") */ protected $parent; //.. }

Throw error:
[Doctrine\DBAL\DBALException]

An exception occurred while executing 'DELETE FROM prefix_DescriptionArea':

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (sigtec_dev.prefix_DescriptionArea,

CONSTRAINT FK_7265873E727ACA70 FOREIGN KEY (parent_id) REFERENCES prefix_DescriptionArea (id))

Before running the query should delete the index when the table has self-reference.






[DDC-3104] Invalid count on EXTRA LAZY collection of SINGLE TABLE entities Created: 28/Apr/14  Updated: 20/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Oleg Namaka Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None

Issue Links:
Reference
relates to DDC-1595 Wrong count in relation with inheritance Resolved

 Description   
  • This issue relates to http://www.doctrine-project.org/jira/browse/DDC-1595
  • With the following entities
    • EntityPromotionAbstract entity:
      * @ORM\Entity
       * @ORM\InheritanceType("SINGLE_TABLE")
       * @ORM\Table(name="entity_promotion")
       * @ORM\DiscriminatorColumn(name="type", type="string")
       * @ORM\DiscriminatorMap({
       *     "brand"           = "BrandPromotion",
       *     "category"        = "CategoryPromotion",
       * })
       */
      abstract class EntityPromotionAbstract
      
    • CategoryPromotion entity:
       * @ORM\Entity
       */
      class CategoryPromotion extends EntityPromotionAbstract
      {
          /**
           * Category
           *
           * @var Category
           * @ORM\ManyToOne(targetEntity="Category", inversedBy="CategoryPromotions")
           * @ORM\JoinColumn(name="instance_id", referencedColumnName="category_id")
           */
          protected $Category;
      ...
      }
      
    • BrandPromotion entity:
       * @ORM\Entity
       */
      class BrandPromotion extends EntityPromotionAbstract
      {
          /**
           * Brand
           *
           * @var Brand
           * @ORM\ManyToOne(targetEntity="Brand", inversedBy="BrandPromotions")
           * @ORM\JoinColumn(name="instance_id", referencedColumnName="brand_id")
           */
          protected $Brand;
      }
      
    • Brand entity:
          /**
           * Associated BrandPromotions
           *
           * @var \Doctrine\Common\Collections\Collection
           *
           * @ORM\OneToMany(targetEntity="BrandPromotion", mappedBy="Brand", fetch="EXTRA_LAZY")
           */
          protected $BrandPromotions;
      
    • Category entity:
          /**
           * Associated CategoryPromotions
           *
           * @var \Doctrine\Common\Collections\ArrayCollection|\Doctrine\ORM\PersistentCollection
           *
           * @ORM\OneToMany(targetEntity="CategoryPromotion", mappedBy="Category", fetch="EXTRA_LAZY")
           */
          protected $CategoryPromotions;
      
  • When Brand::BrandPromotions collection is not initialized, calling count on it will return a count of BrandPromotion and CategoryPromotion elements, but calling isEmpty will return a count of BrandPromotion entities only.
  • \Doctrine\ORM\Persisters\OneToManyPersister::count does not take into account a discriminator value of 'brand':
            foreach ($targetClass->associationMappings[$mapping['mappedBy']]['joinColumns'] as $joinColumn) {
                $whereClauses[] = $joinColumn['name'] . ' = ?';
    
                $params[] = ($targetClass->containsForeignIdentifier)
                    ? $id[$sourceClass->getFieldForColumn($joinColumn['referencedColumnName'])]
                    : $id[$sourceClass->fieldNames[$joinColumn['referencedColumnName']]];
            }
    
    
  • This results in a query:
    SELECT count(*) FROM entity_promotion t WHERE instance_id = ?
    
  • The query should include a type condition:
    SELECT count(*) FROM entity_promotion t WHERE instance_id = ? AND (t.type in 'brand')
    


 Comments   
Comment by Marco Pivetta [ 29/Apr/14 ]

Why would the query include a type conditional? To me, it seems like the association was built between invalid data types instead.

Comment by Oleg Namaka [ 06/May/14 ]
  • Could you elaborate on what exactly you mean when you are saying, that the association was built between invalid data types?
  • Even if your statement is valid, then why calling on a initialized collection $collection->isEmpty() produces a correct result? Calling $collection->count() produces also a correct result on an initialized collection, wheres calling $collection->count() on an unitialized collection results in an invalid element count.
Comment by Marco Pivetta [ 06/May/14 ]

Ah, I see what you mean now. Sorry, I was confusing this with a joined table inheritance.

Comment by Vigintas Labakojis [ 20/May/14 ]

Exactly same behaviour just wasted me a few hours. Shame I'll have to switch fetch mode back to LAZY until this gets fixed.





[DDC-3098] [GH-1016] improved error handling for invalid association values Created: 23/Apr/14  Updated: 23/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of flip111:

Url: https://github.com/doctrine/doctrine2/pull/1016

Message:

Possibly to do:
1. Make custom Exception for line 713
2. Make custom Exception for line 817
3. Does the object check on line 816 slow down the code too much? Alternatively a try-catch could be put around line 1415 or higher up.






[DDC-3096] JoinColumn definition does not regard column type with value translation Created: 22/Apr/14  Updated: 22/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Volker Nauruhn Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: entityPersister, mapping, mysql, orm
Environment:

Symfony 2.4.3



 Description   

I made a custom column type for doctrine which converts values between MySQL and PHP.

When I use a field with this column type as JoinColumn in a ManyToOne relation plus the column has a different name than the field, the BasicEntityPersister gets always "null" when he is asking for type of the given column name because he is ascing for given column name and not field name.

Example
=====================

Make.php:

/**
 @ORM\Column(name="language_code", type="locale")
 */
private $locale;

Foobar.php

/**
 @ORM\ManyToOne(targetEntity="Make")
 @ORM\JoinColumn(name="make_locale", referencedColumnName="language_code")
 */
private $makes;

The localeType translates between long and short language codes. For exmaple "de" (PHP) to "de_DE" (MySQL).



 Comments   
Comment by Marco Pivetta [ 22/Apr/14 ]

This is not a blocker, as you're really going into custom implementations.

You should probably provide a failing test case to clarify what you are doing





[DDC-3091] Not set entity to results if use query with JOIN Created: 17/Apr/14  Updated: 17/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Vitaliy Zhuk Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hi.
I have a problem, if i can use query with JOIN without grouping (DISTINCT) by identifier entity. Problem: not set entities to result, if entity has cached in ObjectHydration.

For example:

SQL query:

SELECT 
  b0_.id AS id0,
  b0_.hash AS hash1, 
  b0_.mii AS mii2, 
  b0_.iin AS iin3, 
  b0_.last_digits AS last_digits4, 
  b0_.number AS number5, 
  b0_.holder AS holder6, 
  p1_.keyword AS keyword7, 
  t2_.client AS client8, 
  CONCAT(b0_.hash, CONCAT(p1_.keyword, t2_.client)) AS sclr9 

FROM bank_card b0_ 
  INNER JOIN transaction_bank_card t2_ ON (t2_.bank_card_id = b0_.id) 
  INNER JOIN projects p1_ ON (t2_.project_key = p1_.keyword) 

WHERE (p1_.keyword = 'project1' AND t2_.client = '123') OR (p1_.keyword = 'project2' AND t2_.client = '321') /* ... Other where */

GROUP BY sclr9

Mysql result:

id0 hash1 mii2 iin3 last_digits4 number5 holder6 keyword7 client8 sclr9
28 1d741fd06f3315dad28039926effc5d7 5 533330 2763 533330******2763 John Doe p6 78165 1d741fd06f3315dad28039926effc5d7p678165
34 58b021876f625e3000137cd835f5fe40 5 555456 5047 555456******5047 OLOLO OLOLO p6 78165 58b021876f625e3000137cd835f5fe40p678165
2 887d30e9b4d18676c6e0dc8e21e36d28 5 556458 4251 556458******4251 Monkey Testing p6 78165 887d30e9b4d18676c6e0dc8e21e36d28p678165
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 100673 bb14a77f2e363cd144b669f0b594d304p6100673
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 100922 bb14a77f2e363cd144b669f0b594d304p6100922
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 101441 bb14a77f2e363cd144b669f0b594d304p6101441
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 78165 bb14a77f2e363cd144b669f0b594d304p678165
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 85550 bb14a77f2e363cd144b669f0b594d304p685550
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 85566 bb14a77f2e363cd144b669f0b594d304p685566
1 bb14a77f2e363cd144b669f0b594d304 4 432114 1118 432114******1118 Monkey Testing p6 85768 bb14a77f2e363cd144b669f0b594d304p685768

And the PHP code (from custom entity repository):

$qb
            ->select('bc')
            ->addSelect('p.key AS project_key')
            ->addSelect('tbc.client AS client')
            ->addSelect('CONCAT(bc.hash, CONCAT(p.key, tbc.client)) AS unique_key')
            ->innerJoin('FooBundle:TransactionBankCard', 'tbc', 'WITH', 'tbc.bankCard = bc.id')
            ->innerJoin('BarBundle:Project', 'p', 'WITH', 'tbc.project = p.key')
            ->where($orX)
            ->groupBy('unique_key');

        $result = $qb->getQuery()->getResult();

And this code returned only unique entities by identifier (Identifier: id field), but must returned the all entities from query.

The Object Hyndration has cached created entities, and if the next row is entity (indicate as identifier and dql alias), then hydration not set this entity to result.
Problem code: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php#L569-L572

Thank.






[DDC-3088] EntityManager::clear doesn't working with inserting Created: 16/Apr/14  Updated: 16/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Adrian Ch Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.4.25-1+sury.org~precise+2 (cli) (built: Feb 12 2014 10:45:30)
Symfony version 2.4.2 - app/dev/debug



 Description   

It looks like EntityManager's clear() method doesn't remove objects that was persisted during script execution.

Bellows are two functions. First one insert 10.000 records and use clear after each flush that should remove objects from memory, but instead of that memory usage growths in each iteration. There isn't any other reference for this objects.

I've checked how it works for reading and with clearing it works perfectly - script uses only constant memory.

 
    private function testInserting($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        for ($i = 1; $i <= 10000; ++$i) {

            $item = new $entityClass();
            $item->setName($i);
            $item->setPresentation($i);
            $em->persist($item);

            if ($i % $batchSize == 0) {
                $em->flush();
                $em->clear();

                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }
        }
    }
    
    
private function testReading($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        $q = $em->createQuery("select i from $entityClass i");
        $iterableResult = $q->iterate();

        $i = 0;
        while (($row = $iterableResult->next()) !== false) {
            $em->clear();
            if ($i % $batchSize == 0) {
                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }

            $i++;
        }
    }
    

My results:

1) Reading without clearing ($em->clear(); removed)

0:
22.89 MB (2.63 MB)
1000:
33.41 MB (13.15 MB)
2000:
44.04 MB (23.78 MB)
3000:
53.50 MB (33.24 MB)
4000:
65.13 MB (44.86 MB)
5000:
74.81 MB (54.55 MB)
6000:
84.27 MB (64.01 MB)
7000:
97.96 MB (77.69 MB)
8000:
107.40 MB (87.14 MB)
9000:
117.17 MB (96.91 MB)
10000:
126.61 MB (106.35 MB)

2) Reading with using clear

0:
22.89 MB (2.63 MB)
1000:
26.25 MB (5.99 MB)
2000:
24.74 MB (4.48 MB)
3000:
26.72 MB (6.46 MB)
4000:
24.79 MB (4.52 MB)
5000:
26.76 MB (6.50 MB)
6000:
24.81 MB (4.55 MB)
7000:
26.77 MB (6.51 MB)
8000:
24.83 MB (4.57 MB)
9000:
26.81 MB (6.54 MB)
10000:
24.86 MB (4.60 MB)

3) Inserting without clearing

1000:
29.50 MB (9.24 MB)
2000:
37.76 MB (17.50 MB)
3000:
45.12 MB (24.86 MB)
4000:
54.34 MB (34.07 MB)
5000:
61.79 MB (41.53 MB)
6000:
69.09 MB (48.82 MB)
7000:
76.40 MB (56.13 MB)
8000:
83.75 MB (63.48 MB)
9000:
95.64 MB (75.37 MB)
10000:
102.98 MB (82.71 MB)

4) Inserting with using clear

1000:
27.90 MB (7.63 MB)
2000:
34.64 MB (14.37 MB)
3000:
40.43 MB (20.17 MB)
4000:
48.20 MB (27.93 MB)
5000:
54.12 MB (33.85 MB)
6000:
59.89 MB (39.63 MB)
7000:
65.67 MB (45.40 MB)
8000:
71.43 MB (51.16 MB)
9000:
81.51 MB (61.25 MB)
10000:
87.29 MB (67.02 MB)



 Comments   
Comment by Marco Pivetta [ 16/Apr/14 ]

Would be useful to see what the entity class looks like.

Additionally, the ORM version being affected is also needed.





[DDC-3083] Persist/Flush silently fails when CTI is applied on an existing table Created: 12/Apr/14  Updated: 13/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Frank Liepert Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Given an existing table (= parent table) the integration of a new parent-child relationship with Class Table Inheritance (CTI) leads to a update problem.

First of all a child table is created with a foreign key to the parent table. Next, the discriminator column is added to the parent table. The discriminator map will be auto-generated.

The problem arises when trying to perform persist() and flush() on a child entity. Initially the child table is logically empty. However, the UnitOfWork triggers updateTable() which will fail since there is nothing to update. Instead, an upsert should be performed.

Another sneaky thing is that the repository will return the child class with the updated data after calling flush() on the same request. On the next request the child class is returned with the data loaded from the persister. Of course, the updated data is missing.



 Comments   
Comment by Marco Pivetta [ 13/Apr/14 ]

Frank Liepert do I understand this correctly if I say that you are trying to (pseudo) upcast an entity to a more specific subtype? That is unsupported by the ORM. Could you make just an example snippet of what you described in the issue?

Comment by Frank Liepert [ 13/Apr/14 ]

Marco Pivetta: You have understood really well. If you say that's not supported by the ORM then this is the answer. Still I think that upsert could solve solve the "problem" and I know that there are/have been discussions about upsert.

Right now I will continue to manually insert the missing rows in the child table. After this necessary step the ORM works as expected.

Nevertheless the real bug is that after persist() and flush() the entity manager returns the child object with the "persisted" data of the child table although there are in fact no rows in the child table.

$parentRepository = $em->getRepository('Parent');

$child = $parentRepository ->find(1);
$child->setChildPropertyA('foo');

$em->persist($child);
$em->flush();

$child = $parentRepository ->find(1);
var_dump($child->getChildPropertyA());
// string(3) "foo"

// But: There is no 'foo' in the child table!


/** 
 * NEW REQUEST
 */

$parentRepository = $em->getRepository('Parent');

$child = $parentRepository ->find(1);
var_dump($child->getChildPropertyA());
// NULL

Comment by Marco Pivetta [ 13/Apr/14 ]

Frank Liepert why are $child in the first request and $child in the second request different here? Are you manually changing the data at SQL level?

Comment by Frank Liepert [ 13/Apr/14 ]

Marco Pivetta as I have explained the persist() and flush() in the first request trigger an UPDATE command (Because there is already a row in the parent table?). Given that the child table was manually created before there are no rows on that table at that time and therefore nothing can be updated. Nevertheless the ORM triggers no error and $child looks like having been persisted. In the second request you'll notice that there haven't been persisted any of the data belonging to the child table.





[DDC-3079] preUpdate in EntityListener not run in transaction Created: 10/Apr/14  Updated: 10/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Jiri Napravnik Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I have entity:

class Article{
	/**
	 * @ORM\OneToMany(targetEntity = "ArticleModule\Model\Entities\ArticlePhoto", mappedBy = "article", cascade = {"persist", "remove"}, orphanRemoval = TRUE)
	 * @ORM\OrderBy({"sequence" = "ASC"})
	 */
	protected $articlePhotos;
}

And Entity Listener with preRemove.

I call

$article->articlePhotos->clear();
...some changes with entity...
$em->flush();

preRemove in Entity Listener is called, BUT before Begin transaction...

I can do
$em->transactional(function(){}); then it's full in transaction..






[DDC-3070] [GH-1001] [DDC-3005] Defer invoking of postLoad event to the end of hydration cycle. Created: 04/Apr/14  Updated: 04/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of Strate:

Url: https://github.com/doctrine/doctrine2/pull/1001

Message:

This feature makes guarantee, that postLoad event fires after all associations are populated.
Test case also provided.






[DDC-3063] Unexpected behavior with 'WHERE NOT IN' and empty array Created: 01/Apr/14  Updated: 06/May/14

Status: Reopened
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Tim Stamp Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None
Environment:

CentOS, PHP 5.4, mysql



 Description   

I tried to set version to 2.4.0 but was prevented.

Assume the set 'n' contains 10 records, all with id > 0.

->andWhere('n.id NOT IN (:ids)')->setParameter('ids', [])
returns 0 records.

->andWhere('n.id NOT IN (:ids)')->setParameter('ids', [0])
returns 10 records.


 Comments   
Comment by Marco Pivetta [ 01/Apr/14 ]

This is a simple misunderstanding of how SQL IN() works

Comment by Tim Stamp [ 01/Apr/14 ]

You're right that its invalid SQL, but this is DQL. In SQL this would raise an error, in DQL it says nothing and returns nothing.

Isnt there a way to check if a statement has caused this error?

Comment by Marco Pivetta [ 01/Apr/14 ]

Tim Stamp yeah, when using IN() and NOT IN() you should actually check if the parameters are empty or not before adding the clause.

Comment by Steve Müller [ 01/Apr/14 ]

It's still weird that no error is raised by that. Tim Stamp can you check what SQL is generated by your query?

Comment by Steve Müller [ 01/Apr/14 ]

Hehe I think I got the problem. It might be DBAL related. See:

https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/SQLParserUtils.php#L140
https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/SQLParserUtils.php#L169

Looks like the implementing person did that by intention but don't ask me why.

Comment by Marco Pivetta [ 01/Apr/14 ]

Thats to avoid having an SQL statement like

SELECT * FROM foo WHERE bar IN()

, which is invalid.

Indeed, the NOT IN() case is not contemplated by that.

Comment by Steve Müller [ 01/Apr/14 ]

Just wondering if that kind of implementation isn't changing expectations because it looks like IN(NULL) will select all NULL rows then, even though this is not explicitly requested by the user. I don't care really TBH but this behaviour is not very transparent to the user. Personally I would like to see an error instead... Then at least I know what's going on and can fix that by additional checks instead.

Comment by Marco Pivetta [ 01/Apr/14 ]

Makes sense. Re-opening.

Comment by Steve Müller [ 01/Apr/14 ]

The question is if we can change this behaviour without breaking applications that rely on the current one. Because changing the code to throw an error breaks applications that insist on returning 0 rows for an empty array. I don't know what rules apply here concerning BC. What do you think Marco Pivetta?

Comment by Marco Pivetta [ 01/Apr/14 ]

Steve Müller existing apps should do following anyway:

if ($productIds) {
    $qb->andWhere('p.id IN (:productIds)')->setParameter('productIds', $productIds);
}

If they are not, that's most likely a bug in their codebase.

Comment by Steve Müller [ 01/Apr/14 ]

Agree. Was just wondering about what we can expect and what we can't expect.

Comment by Guilherme Blanco [ 21/Apr/14 ]

Steve Müller feel free to patch DBAL.
It's a bug, not a supported feature. If we have 2 tickets:
1- If I pass an empty array, I get nullable rows and I can't fix this
2- If I pass an empty array, it used to return nullable rows, now it returns nothing
Which one would you fix?

Comment by Tim Stamp [ 06/May/14 ]

Guilherme Blanco shouldn't both these use cases throw an exception, as both cases in MySQL would return an error?





[DDC-3056] Return value mismatch between code under HHVM and Zend Created: 28/Mar/14  Updated: 28/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Andy hunt Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: hhvm, orm, paginator
Environment:

Two environments:
LAMP stack with PHP 5.4.25 on Ubuntu 12.04
HHVM 3.0.0.-dev (rel) ob Ubuntu 12.04



 Description   

The following code produces differing results under Zend and HHVM runtimes.

// $all::build uses the query builder to select all entities of a type
/** @var \Doctrine\ORM\Query $query **/
$query = $all->build($qb);
$query->setMaxResults($pageSize)->setFirstResult($start);

$paginator = new Paginator($query);
$results = array_values((array)$paginator->getIterator());

Under Zend, $results is a 1-dimensional array containing N elements:
[1, 2, 3].

Under HHVM, $results is a 2-dimensional array containing a single array, containing N elements:
[ [1,3,3] ]



 Comments   
Comment by Christophe Coevoet [ 28/Mar/14 ]

I suggest reporting it to the HHVM team as a bug

Comment by Marco Pivetta [ 28/Mar/14 ]

Also: why are you using an array cast and not iterator_to_array?

Comment by Christophe Coevoet [ 28/Mar/14 ]

@Marco this should be equivalent. Casting a Traversable to array should traverse it. If HHVM does not do it, it is a bug.

Comment by Marco Pivetta [ 28/Mar/14 ]

Christophe Coevoet not really: http://3v4l.org/Z3t4t





[DDC-3055] table not escaped in orm:schema-tool:update if table already exists and needs to be altered Created: 27/Mar/14  Updated: 19/Jun/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.4.2, 2.4.3
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Hilz Simon Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

the schema tool had to alter a table which name needs to be escaped (and was properly configured to do so). this didnt work because the table name wasnt escaped. completely deleting the table in the db let the schema tool generate the correct querys with escaped table names.



 Comments   
Comment by Marco Pivetta [ 27/Mar/14 ]

Hilz Simon did you try this with master as well?

Comment by Jérôme Poskin [ 19/Jun/14 ]

Hi it seems to fail on version 2.4.3 too





[DDC-3046] The flushed data is not available immediately for querying Created: 25/Mar/14  Updated: 25/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: alex Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

ubuntu 13.10, mysql 5.5.35



 Description   

Doctrine's persisted data is not accessible by other queries immediately, for details see http://stackoverflow.com/questions/22618689/doctrines-persisted-data-is-not-accessible-by-other-queries-immediately






[DDC-3044] [GH-986] Add last modified time for metadata Created: 22/Mar/14  Updated: 22/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of c960657:

Url: https://github.com/doctrine/doctrine2/pull/986

Message:

This patch improves performance during development and does not affect production performance.

Currently, enabling the metadata cache during development gives a remarkable performance boost, but it requires that you manually flush the metadata cache when the metadata has been changed. When running console commands such as ``console orm:schema-tool:update`` (see #979).

With this change, metadata entries fetched from cache are checked for freshness using a quick last modified check. This is much faster than loading the actual metadata using the metadata driver. This allows you to enable the metadata cache during development without the need for manually flushing the metadata cache.

This PR is part 1 of 2. Part 2 is for the doctrine/common repository.

If this PR is accepted, it allows us to optimize the auto-generate proxy classes feature by comparing the last modified time for the metadata with the modified timestamp of the generated file.






[DDC-3029] DISTINCT , ORDER BY AND Limit in SQL Server Created: 14/Mar/14  Updated: 14/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Michał Banaś Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File SQLServerPlatform.php    

 Description   

I don't know if I should report it here , becouse error is in SQLServerPlatform.php file.
basicaly Distinct includes ROWNUM()
So if you add distinct in DQL it will be translated to "select distinct ...... , Rownum()" - which is always distinct offcource.

Here is original version
protected function doModifyLimitQuery($query, $limit, $offset = null)
{
if ($limit > 0) {
if ($offset == 0)

{ $query = preg_replace('/^(SELECT\s(DISTINCT\s)?)/i', '\1TOP ' . $limit . ' ', $query); }

else {
$orderby = stristr($query, 'ORDER BY');

if ( ! $orderby)

{ $over = 'ORDER BY (SELECT 0)'; }

else

{ $over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby); }

// Remove ORDER BY clause from $query
$query = preg_replace('/\s+ORDER BY(.*)/', '', $query);
$query = preg_replace('/^SELECT\s/', '', $query);

$start = $offset + 1;
$end = $offset + $limit;

$query = "SELECT * FROM (SELECT ROW_NUMBER() OVER ($over) AS doctrine_rownum, $query) AS doctrine_tbl WHERE doctrine_rownum BETWEEN $start AND $end";
}
}

return $query;
}
In Attachenment there is a fixed version of this file.






[DDC-3025] Schema tool UPDATE or CREATE not generate decimal precision and scale for ID element Created: 12/Mar/14  Updated: 12/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, Tools
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: huda salam Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

FYI. I don't use doctrine but with symfony2, and only use .yml or .xml mapping. Not yet try with annotation.

These commands :

php app\console doctrine:schema:update
php app\console doctrine:schema:create

Will not generate id's precision and scale for this kind of mapping :

<doctrine-mapping .....>
  <entity name="Namespace\MyBundle\Entity\MyData" table="my_data">
    <id name="id" type="decimal" column="id" precision="x" scale="y">
      <generator strategy="IDENTITY"/>
    </id>
    <field ... />
  </entity>
</ ....>

Suggested changes :

  • Doctrine\ORM\Mapping\Driver\YamlDriver.php
  • Doctrine\ORM\Mapping\Driver\XmlDriver.php





[DDC-3016] Criterias do not work with embeddables when matching in memory Created: 07/Mar/14  Updated: 22/May/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Matthieu Napoli Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When using criterias and doing the matching on a collection already loaded in memory, it will not work if filtering on embeddable objects.

Example:

    $criteria = new Criteria();
    $criteria->andWhere($criteria->expr()->eq('actions.view', true));

    $authorizations = $this->authorizations->matching($criteria);

Here the ClosureExpressionVisitor will try to get the property named >actions.view instead of >actions->view.

PHPUnit_Framework_Error_Notice : Undefined property: Tests\...\Model\ArticleAuthorization::$actions.view


 Comments   
Comment by Matthieu Napoli [ 22/May/14 ]

I have opened a PR with a potential fix: https://github.com/doctrine/collections/pull/27





[DDC-3007] ManyToMany does not respect all column attributes for the jointable Created: 03/Mar/14  Updated: 03/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Michael Kühn Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Given following 2 entities:

<?php
class Role {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @ORM\Column(name="id", type="guid", nullable=false, unique=true, length=36, options={"fixed"=true})
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roleList")
     */
    private $userList;
}
<?php
class User {
    /**
     * @ORM\Column(name="id", type="guid", nullable=false, unique=true, length=36, options={"fixed"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;

    /**     *
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="userList")
     * @ORM\JoinTable(name="user_role")
    protected $roleList;
}

It should create a table "user_role" with 2 columns which are CHAR(36).

But it ignores the Column-Attributes and creates a table "user_role" with 2 CHAR(255) columns.

This has various downsides:

  • It's unusable when using MyISAM, because of limited index size. (CREATE TABLE fails, see DBAL-423)
  • If using GUID-Type (see DBAL-423 with the changes from the linked ull request) and specify "length=36" and "fixed=true" on the Column-Annotation, no changes for the entity-tables itself are generated when running orm:schema-tool:update. However, there are still changes for the many-to-many-table generated (because internal "fixed" is false and length is unset) which represent the current state of the columns. These changes are always generated.





[DDC-3005] Events::postLoad fires without filled associations Created: 02/Mar/14  Updated: 10/Apr/14

Status: Reopened
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Artur Eshenbrener Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When we load entities throw one dql query like this:

SELECT e, joined_link FROM Entity LEFT JOIN e.link joined_link

In event subscriber, subscribed to postLoad event for instances of Entity property "link" of entity does not contains fetched in same query joined entity, and does not contains proxy object.

Tell me if failing test case needed.



 Comments   
Comment by Marco Pivetta [ 02/Mar/14 ]

The postLoad event is fired without warranty that association entities/proxies will be set:

http://docs.doctrine-project.org/en/latest/reference/events.html#lifecycle-events

Comment by Artur Eshenbrener [ 03/Mar/14 ]

But why? This shounds like involuntary restriction, and I think it can be fixed. Will my PR with fix accepted, or collaborators don't want to change this behaviour?

Comment by Marco Pivetta [ 03/Mar/14 ]

Artur Eshenbrener triggering `postLoad` in the correct moment in time (when all dependencies are loaded) requires a lot of additional complexity to be inserted in various locations of the ORM.

Since `postLoad` is supposed to be used like `__wakeup` and in general for simple tasks, this kind of refactoring/rewrite would be an overkill.

Comment by Artur Eshenbrener [ 04/Mar/14 ]

> requires a lot of additional complexity to be inserted in various locations of the ORM.
Sounds like "It is very hard to implement, and no one want to do this"

> and in general for simple tasks, this kind of refactoring/rewrite would be an overkill.
Disagree with this. Why only simple? I need to deal with associations in this event. Without this I should inject whole EntityManager to my entity, but I dont want to do this.

And I forced to repeat the question: will PR with fix accepted or not?

Comment by Marco Pivetta [ 04/Mar/14 ]

Sounds like "It is very hard to implement, and no one want to do this"

Not really, the main problem here is performance, since hydration would have to be completely redesigned.
Yes, "too hard" is a good reason for something that is an edge case.

And I forced to repeat the question: will PR with fix accepted or not?

Sure thing! Just needs to avoid a massive rewrite though.

Comment by Marco Pivetta [ 04/Mar/14 ]

To give you some hints, Doctrine\ORM\Events::postLoad is triggered in https://github.com/doctrine/doctrine2/blob/15432fc55f83c2d6ce8d9b86fd3139dd2a4fc328/lib/Doctrine/ORM/UnitOfWork.php#L2788, and Doctrine\ORM\UnitOfWork#createEntity() is used by all the various hydrators internally.

To ensure that Doctrine\ORM\Events::postLoad is triggered after an entity is fully loaded, the various hydrators must trigger the events after being sure that all data has been set, and that the entity is "ready" for use. That's some copy-paste work :\

Comment by Artur Eshenbrener [ 04/Mar/14 ]

I think the entry point is here: https://github.com/doctrine/doctrine2/blob/15432fc55f83c2d6ce8d9b86fd3139dd2a4fc328/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php#L140,
so, copy-paste work is not needed )

Comment by Artur Eshenbrener [ 05/Apr/14 ]

PR is ready: https://github.com/doctrine/doctrine2/pull/1001





[DDC-2995] Joined Inheritance Mapping and Filters Created: 22/Feb/14  Updated: 23/Mar/14

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Bojidar Hristov Assignee: Marco Pivetta
Resolution: Unresolved Votes: 0
Labels: orm


 Description   

Is there any reason why Inheritance Mapping IS LEFT JOINED not INNER JOINED?

When there is a filter and it's left joined it happens a record might not have parent table record. For example

Class B extends Class A.
Class A have column is_active | and filter activated with is_active = 1 condition.

Final query: LEFT JOIN parent_table s1_ ON p2_.id = s1_.id AND (s1_.is_active = '1')

Record 1 have is_active = false, so result set looks like this:

table_b | table_a
id | id is_active discriminatorColumn
1 | null null null

and occurs exception: The discriminator column ... is missing for ....



 Comments   
Comment by Marco Pivetta [ 22/Feb/14 ]

JTI MUST be left-joined, since not every subclass of the root of the inheritance causes inserts on all of the inheritance tables.

What is the DQL query that is causing the problem?

Comment by Bojidar Hristov [ 22/Feb/14 ]

Hello Marco, I don't query from parent table, but from child. No sense to be LEFT JOINED.

DQL is something like that:

SELECT class1, class2 FROM Class1 class1 JOIN class1.class2 class2;

(Class2 extends Class3)
Class3 have is_active column.

And following filter:

public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) {
if (!$targetEntity->reflClass->implementsInterface('ActivateableInterface'))

{ return ""; }

return $targetTableAlias . '.is_active = ' . $this->getParameter('isActive');
}

Filter condition is added in LEFT JOINED parent_table. Full example SQL:
SELECT ....
FROM class1 c1
INNER JOIN class2 c2 ON c1.c2_id = c2.id
LEFT JOIN table3 c3 ON c2.id = c3.id AND (c3.is_active = '1')

Comment by Marco Pivetta [ 26/Feb/14 ]

There are two possible solutions here:

  • verify if the selected entity is a leaf of a JTI, and use INNER JOIN on that if possible (probably not optimal, since the selection may be part of a LEFT JOIN itself)
  • add filtering on the discriminator column

Bojidar Hristov can you provide a failing test case to make it easier to work on this?

Comment by Bojidar Hristov [ 26/Feb/14 ]

Yes. Here is it sample failing test.

http://pastebin.com/xi8uUNX5 - Parent Class
http://pastebin.com/XRZLbyGX - Child Class
http://pastebin.com/HuPFb98u - Assoc Class
http://pastebin.com/hGqRk74e - TestCase

Here it should found 0 records because ot JOIN and is_active = true filter.

Comment by Benjamin Eberlei [ 23/Mar/14 ]

Since filters are only available on the root, i guess inner join is really necessary here.





[DDC-2990] [GH-956] Foreign association index names Created: 19/Feb/14  Updated: 23/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Issue Links:
Reference
relates to DDC-2989 ORM should allow custom index names f... Open

 Description   

This issue is created automatically through a Github pull request on behalf of jsuggs:

Url: https://github.com/doctrine/doctrine2/pull/956

Message:

See http://www.doctrine-project.org/jira/browse/DDC-2989






[DDC-2988] Notice: Undefined index: joinColumns in BasicEntityPersister.php Created: 19/Feb/14  Updated: 13/Jun/14

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.3.5, 2.4.2
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Dennis Væversted Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File undefined-joinColumn.patch    
Issue Links:
Duplicate
duplicates DDC-2808 Notice: Undefined index: joinColumns ... Resolved

 Description   

When trying to use findBy on a ManyToMany field i receive the error:

Notice: Undefined index: joinColumns in lib/Doctrine/ORM/Persisters/BasicEntityPersister.php

It seems to be caused internally by the code expecting 'joinColumns' to be directly on the association, however it is found under 'joinTable'.
I have attached a patch that atleast fixes my case, hopefully it can be used to pin-point what the error is.



 Comments   
Comment by Dennis Væversted [ 19/Feb/14 ]

Might be related to this one: http://www.doctrine-project.org/jira/browse/DDC-2808

Comment by Litz Ouille [ 28/May/14 ]

Doctrine ORM 2.4.2 Here.

Here are my annotations
https://gist.github.com/LitzOuille/3cf2e73e169c032147ea

The thing I'm trying to do is
$questionRepository->findBy(array('contacts' => $ids)); // $ids = array(1,2,3, ...)

Comment by Marco Pivetta [ 30/May/14 ]

Calin Pristavu did you validate your mappings?

Comment by Calin Pristavu [ 30/May/14 ]

I failed, sorry.
The error came from the many-to-many condition in the entity.
Sorry for generating confusion, comment deleted !

The many-to-one works just fine !

Comment by Litz Ouille [ 03/Jun/14 ]

A little feedback? Is this a bug? Can it be fixed?
Thanks

Comment by Marco Pivetta [ 03/Jun/14 ]

Litz Ouille that particular repository call cannot work. How are we supposed to find an entity from a list of associated IDs? It would have to be the exact match...

Assuming that API would work as I envision it, it looks like a missing feature.

Dennis Væversted in order to accept a patch, we first need a failing test case demonstrating the failing scenario.

Comment by Litz Ouille [ 03/Jun/14 ]

EDIT: Ok my bad.

I am using findBy(array('id', $arrayIds)) and it is working. I thought I was using on a ManyToOne relationship, but no.

EDIT2: @ocramius In fact I would like to find all questions for which the contacts' list contains at least one id. Something like
SELECT q.*
FROM Question q, QuestionContact qc //qc = jointable
WHERE q.id = qc.question_id
AND qc.contact_id IN ($ids)

EDIT3: Actually when I try to findBy('ManyToMany', $id), it does not work either. I think I will have to use a repository for every query using a ManyToMany relationship.

EDIT4: Ok, so, as said in the original post, findBy does not work with many-to-many.
Notice: Undefined index: joinColumns (BasicEntityPersister.php line 1666)
Dump($this->class->associationMappings[$field]): https://gist.github.com/LitzOuille/51929fdc3eda5576ed31

Comment by Xander ten Boden [ 13/Jun/14 ]

I've got the same issue, also running doctrine 2.4.2:

multiple users can have multiple departments:

/**
 * @ORM\ManyToMany(targetEntity="CartelAuthDepartment", inversedBy="users")
 * @ORM\JoinTable(name="cartel_auth_user_has_cartel_auth_department",
 *		joinColumns={@ORM\JoinColumn(name="cartel_auth_user_id", referencedColumnName="id")},
 *		inverseJoinColumns={@ORM\JoinColumn(name="cartel_auth_department_id", referencedColumnName="id")}
 * )
 */
private $departments;

/**
 * @ORM\ManyToMany(targetEntity="\Cartel\AuthBundle\Entity\CartelAuth\CartelAuthUser", mappedBy="departments")
 */
private $users;

Then I want to find all the users that are within the departments that the current user has:

$aAuthUsers = $oEm->getRepository('CartelAuthBundle:CartelAuth\CartelAuthUser')->findByDepartments($aAuthDepartments);

This results in this error:

Notice: Undefined index: joinColumns in .../vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1665





[DDC-2983] TCI association not getting hydrated into sql statement Created: 14/Feb/14  Updated: 23/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.5
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Machete Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

MySQL, using DoctrineORMModule (zf2 integration)



 Description   

/**
 * @ORM\Entity
 * @ORM\Table(name="base")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discriminator", type="string")
 * @ORM\DiscriminatorMap({
 * "a" = "A",
 * "b" = "B",
 * })
 */
class Base
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
}

/**
 * @ORM\Entity
**/
class A extends Base {
    /**
     * @ORM\ManyToOne(targetEntity="B", inversedBy="as")
     */
    protected $b;

    /**
     * @ORM\OneToMany(targetEntity="C", cascade={"persist"})
     */
    protected $cs;
}

/**
 * @ORM\Entity
**/
class B Extends Base {
    /**
     * @ORM\OneToMany(targetEntity="A", mappedBy="b")
     */
    protected $as;
}

/**
 * @ORM\Entity
**/
class C {
  // ...
}

Doing this:

$a = new A();
$b = new B();

$a->setB($b);
$b->addA($a);

var_dump($a->getB()); // outputs B (b not null!)
var_dump($b->getAs()) // outputs A (private $_elements => [0] class B)

$em->persist($a);
$em->persist($b);
$em->flush();

Leads to

integrity constraint violation, b_id can not be null

aka

INSERT INTO a (id, b_id), (123, null);

I have no idea why this happens. This works:

$a = new A();
$b = new B();

$a->setB($b);
$b->addA($a);

var_dump($a->getB()); // outputs B (b not null!)
var_dump($b->getAs()) // outputs A (private $_elements => [0] class B)

$em->persist($a);
$em->flush();
$em->persist($b);
$em->flush();


 Comments   
Comment by Benjamin Eberlei [ 23/Mar/14 ]

This most likely happens because the UnitOfWork tries to set the owner and reverse incorrectly due to an ordering issue.





[DDC-2982] [GH-954] Multi Get support for Second Level Cache Created: 14/Feb/14  Updated: 23/Mar/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of goetas:

Url: https://github.com/doctrine/doctrine2/pull/954

Message:

Hi!
As discussed [here](http://www.doctrine-project.org/jira/browse/DDC-2981) i have implemented some kind of multi-get for second level cache implementation.

I have also created a PR to doctrine/cache component (see https://github.com/doctrine/cache/pull/29) that enables this feature at driver cache level.






[DDC-2981] Multi get for second level cache (Doctrine Cache related) Created: 13/Feb/14  Updated: 13/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Asmir Mustafic Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hi every body!

I'm developing an application that is highly based on doctrine second-level cache feature.
Using memcache or redis as cache back-end, doctrine have to query thousand times for the cached values (especially on one-to-many and many-to-many associations).
This introduces a lot of latency (and network traffic)...

I'm thinking to add to Doctrine\Common\Cache\Cache interface a method fetchMulti(array $keys) that fetches multiple items in one call. In this way doctrine orm can ask for many items with just one call (for example, here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php#L84 this feature can be very useful).

I have made some real-world tests and it can reduce highly the number of total queries (my app runs 190 cache requests instead of 900 cache requests)

Many vendors (memcache, redis, apc ecc) already offer this functionality, but with doctrine-cache we can't use it...

I'm going to implement this feature. Can it be accepted as a pull request?

It may be BC breaking:

  • it can be implemented adding a method inside Doctrine\Common\Cache\Cache interface (more BC breaking but more clean and elegant)
  • it can be implemented adding an interface Doctrine\Common\Cache\MultiCache and later CacheProvider can implement it (less BC breaking)


 Comments   
Comment by Marco Pivetta [ 13/Feb/14 ]

Adding a method to Doctrine\Common\Cache\Cache is not viable because of BC - a new interface would be ok

Comment by Asmir Mustafic [ 13/Feb/14 ]

ok, i agree with you.
But this forces me to check always here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php#L95 if $this->cache is instance of MultiCache

Comment by Marco Pivetta [ 13/Feb/14 ]

Asmir Mustafic or you build a MultiCacheRegion

Comment by Asmir Mustafic [ 13/Feb/14 ]

It can be a good approach. I will try it.
I'm thinking to provide a default implementation of fetchMulti directly inside CacheProvider that internally loops over each key and call CacheProvider::fetch($id) to fetch its value.
Later i will overwrite this behavior inside vendor specific driver (ApcCache, RedisCache...)





[DDC-2973] [GH-949] Add a default lock mode to the EntityManager Created: 10/Feb/14  Updated: 10/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of BenMorel:

Url: https://github.com/doctrine/doctrine2/pull/949

Message:

Following [this discussion](https://groups.google.com/forum/#!topic/doctrine-dev/xKGzQcDkilE) on the mailing list, this is a first draft of a proposal to introduce a default lock mode for all entities loaded through an EntityManager.

At the moment, there is no way to set a lock mode for the following use cases:

  • Proxies obtained through `getReference()` and then initialized
  • Entities lazy-loaded through traversal of associations

This proposal introduces the idea of a default lock mode, which can be set at runtime when all reads in a transaction should be locking.

It works this way:

$em->beginTransaction();
$em->getConfiguration()->setDefaultLockMode(LockMode::PESSIMISTIC_WRITE);

// load entities from EntityManager, Repositories or DQL, traverse associations, etc.
// all these entities will be loaded with the given lock mode

$em->commit();
$em->getConfiguration()->setDefaultLockMode(null);

I have successfully tested it with the following use cases:

  • `EntityManager::find()`
  • `EntityRepository::findBy()`
  • DQL queries
  • Proxies
  • Lazy-loaded collections through OneToMany and ManyToMany associations

Before moving forward and writing proper unit tests, I'm looking for your feedback on this proposal. Is this a concept you would be happy to integrate in Doctrine?

If yes, I have a doubt as regards to where the default lock mode should be set: @Ocramius suggested to set it on the `Configuration`; this looked reasonable at first glance, and I have implemented it this way for now. It feels a tiny bit wrong though now that I see it, as I feel like the contents of the Configuration should should only be set during bootstrapping, rather than being set and reset in the controllers as in the example above. I might be wrong obviously.

My suggestion would be to move the default lock mode to the EntityManager, so that the code would become:

$em->beginTransaction();
$em->setDefaultLockMode(LockMode::PESSIMISTIC_WRITE);

Happily waiting for your feedback!






[DDC-2955] [GH-933] [WIP] DDC-2953 Created: 05/Feb/14  Updated: 05/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of Ocramius:

Url: https://github.com/doctrine/doctrine2/pull/933

Message:

This PR tries to fix DDC-2953 (http://www.doctrine-project.org/jira/browse/DDC-2953).

tl;dr: when the results are not sorted by root entity identifier, the array hydrator swallows some output.






[DDC-2954] Paginator loses items Created: 05/Feb/14  Updated: 12/Feb/14

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4, 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Mariusz Jaskółka Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: Pagination, Paginator
Environment:

Linux and Windows, PHP 5, Oracle(OCI8)


Attachments: File LimitSubqueryOutputWalker.php     File LimitSubqueryOutputWalker_bugfix.php    

 Description   

Sometimes when when I use Paginator (Doctrine\ORM\Tools\Pagination\Paginator)

  • with query contains orderBy
  • with $fetchJoinCollection = true
  • lot of joins with toMany associations

there are too few items in result (no, it is not the end of list). There two situations:
1. I have four items on page 1 and two items on page 2 (pageLimit is 5). It is no so bad
2. I have four items on page 1 and there is no page 2 (while there should be 5 all items). This is very bad because I lose one item.

------------------------------------------------------------------
EDIT:
In function Paginator::getIterator there is variable $ids. In my situation it contains five numbers [34,26,34,15,12]. There is duplicated value 34 but ids of top-level entities should be distinct (as far as we do not use CROSS JOIN, or maybe I am wrong).

The Paginator::count function works correctly, it does not count duplicated values twice.

Statement that gets $ids is like following:
SELECT a.* FROM (SELECT DISTINCT ID2, BEGINTIME70 FROM (...) dctrn_result ORDER BY BEGINTIME70 DESC) a WHERE ROWNUM <= 5

------------------------------------------------------------------
EDIT 2 - Bugfix description:
The result items of the query is not unique because of
"SELECT DISTINCT col_with_id, order_by_column (...) ORDER BY order_by_column".
If we had items like following:
(1,A)
(1,B)
(1,B)
(2,C)

After DISTINCT operation the result would be:
(1,A)
(1,B)
(2,C)

But we want to have unique firs column, not pairs. That's why we should do "ORDER BY" before "DISTINCT" - not in the same time.
Please confirm if the solution is correct.



 Comments   
Comment by Marco Pivetta [ 05/Feb/14 ]

Mariusz Jaskółka this needs more details

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

OK, I will try to find out where the problem is.

Comment by Mariusz Jaskółka [ 06/Feb/14 ]

I have edited description, maybe additional information will help.

Comment by Mariusz Jaskółka [ 07/Feb/14 ]

I send the bugfix in attachment. I will describe it soon.

Comment by Mariusz Jaskółka [ 07/Feb/14 ]

Bugfix version 2 - previously I did not notice that oracle loses order after DISTINCT operation. Thus I used GROUP BY.

Comment by Mariusz Jaskółka [ 11/Feb/14 ]

I do not know if I can change status of this issue from "Awaiting Feedback". I can not see such option





[DDC-2945] [GH-925] [DDC-2310] [DDC-2675] [2.4] Fix SQL generation on table lock hint capable platforms Created: 31/Jan/14  Updated: 31/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/doctrine2/pull/925

Message:

Backport of PR https://github.com/doctrine/doctrine2/pull/910 for 2.4 branch.






[DDC-2940] [GH-922] Two hooks for DoctrineBundle to allow ContainerFilterCollection Created: 29/Jan/14  Updated: 29/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of nicoschoenmaker:

Url: https://github.com/doctrine/doctrine2/pull/922

Message:

Allows the DoctrineBundle to inject a ```ContainerFilterCollection``` that creates filters through dependency injection. See doctrine/DoctrineBundle#245.

Would prefer to inject the ```FilterCollection``` into the constructor of the em, but since they have a cyclic dependency I chose setter injection.






[DDC-2930] Pessimistic locking using $em->find('Entity', $id, LockMode::PESSIMISTIC_WRITE) and $em->lock($entiy, LockMode::PESSIMISTIC_WRITE) differs in (not)refreshing entity state from DB Created: 23/Jan/14  Updated: 23/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Jiri Kavalik Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

ubuntu 12.04, mysql, zf2



 Description   

When using pessimistic locking on MySQL(InnoDB tables) there is difference which surprised me:

$em->find('Entity', $id, LockMode::PESSIMISTIC_WRITE);

will reload entity state from DB even when entity was already managed in cache (implemented in DDC-2929)
So I supposed that

$em->lock($entiy, LockMode::PESSIMISTIC_WRITE);

will work alike even when in this case entity is sure already loaded and managed
But it is not the case, actual query log showed only

SELECT 1 FROM table WHERE id FOR UPDATE

If this difference is intended it would be nice to mention it in http://docs.doctrine-project.org/en/latest/reference/transactions-and-concurrency.html

As a workaround I use

$em->refresh($entiy);





[DDC-2929] Pessimistic lock on Query does not update the entity with the DB values if it's already cached Created: 22/Jan/14  Updated: 22/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Renaud Drousies Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

PHP 5.4.13-1~dotdeb.1


Issue Links:
Reference
is referenced by DDC-1846 Pessimistic lock does not retreive la... Resolved

 Description   

When asking for a pessimistic lock through a Query object, the entities already in the cache are not refreshed with the latest values from the database (unless you set the Query::HINT_REFRESH hint)

Example:

        $em->beginTransaction();
        try {
            $bar = $em->createQuery('SELECT b FROM Foo:Bar b WHERE b.id = :id')
                        ->setParameter('id', 150)
                        ->getSingleResult();
            var_dump($bar->getAmount()); // Yields some positive value
            $bar->setAmount(0);
            $bar = $em->createQuery('SELECT b FROM Foo:Bar b WHERE b.id = :id')
                        ->setParameter('id', 150)
                        ->setLockMode(\Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE)
                        // ->setHint(\Doctrine\ORM\Query::HINT_REFRESH, true)
                        ->getSingleResult();
            var_dump($bar->getAmount()); // Yields 0

            $em->flush();
            $em->commit();
        } catch (\Exception $e) {
            $em->rollback();
        }

This is similar to DDC-1846

(Tested on 2.4.0 and 2.4.1)






[DDC-2922] Flushing new Entities reachable over several paths that do not all "cascade persist" Created: 17/Jan/14  Updated: 17/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Matthias Pigulla Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None


 Description   

Please consider the following associations:

  A <>--> B <-- C  

A is an "aggregate" type object w/ a OneToMany collection of Bs. This association is set to cascade persist operations.

C has a unidirectional OneToOne association to B as well.

Adding a new B to A's collection and flushing the EntityManager works - B is persisted (persistence by reachability).

However, when also creating a new C and pointing it to the new B, adding C to the EntityManager and then flushing leads to an exception because B is discovered as a new Entity through a relationship not set to cascade persist operations.

Obviously the problem here is that there are two paths through which we can discover new Entities. The UoW currently starts search from newly (explicitly) added Entities first before it walks through collections of already-managed entities.

I am unsure if it is just a documentation issue or a deeper problem?

If the UoW worked the other way round, the same problem would occur if the cascade persist was on the other association.

A solution would probably require the UoW to first collect all offending (new) Entities and the link they were discovered through, but later on remove Entities from this list if they are found through another association with the cascade persist option. The exception must not be thrown unless the whole reachability graph has been traversed.






[DDC-2918] get statements from ORM Created: 15/Jan/14  Updated: 15/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Flip Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When doing `persist()` and then `flush()` the statements are not accessible anymore after the operation is done.

The EntityManager uses an EntityPersister. When looking at the BasicEntityPersister->executeInserts() a new statement is created but it's not saved as part of another object.
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php#L260

Benefit:
When having access to the statements afterwards, all the following methods would be available:
http://www.php.net/manual/en/class.pdostatement.php

Most interesting are rowCount and error related methods.



 Comments   
Comment by Steve Müller [ 15/Jan/14 ]

Flip AFAIK you can use an SQL Logger for this which has to be set in the connection. The ORM testsuite makes use of this, too. See this example: https://github.com/doctrine/doctrine2/blob/master/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php#L155

Comment by Flip [ 15/Jan/14 ]

Yes sure, but using a logger will be a strange way to pipe it back into business logic.

For example it's possible to do remove() on a proxy so you don't know if the row was present or not.

or another situation ..

when dealing with concurrency .. somebody else might have deleted the row already ..





[DDC-2917] Inheritance using joins generates invalid SQL when used in SELECT queries with GROUP BY on Postgresql Created: 15/Jan/14  Updated: 15/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Tom Pryor Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None


 Description   

Say you have an entity with InheritanceType("JOINED"), some child entities defined in the DiscriminatorMap which include additional columns and are using PostgreSQL then try and execute a DQL query as below:

SELECT parententity FROM MyStuff\Entity\ParentEntity parententity GROUP BY parententity

Note: This is simplified for ease of reproduction, obviously the GROUP BY is pointless but in my actual query, which is significantly larger, the GROUP BY is actually useful.

PostgreSQL will give the following error:

SQLSTATE[42803]: Grouping error: 7 ERROR:  column "f2_.my_additional_column" must appear in the GROUP BY clause or be used in an aggregate function

Where f2_ is an alias in the actual SQL for one of the child entities.

This is because the SELECT in the actual SQL attempts to fetch the columns from the joined child entities but does not include them in the GROUP BY clause.

Bad SQL generated:

SELECT f0_.id AS id0, <f0_.* columns>, f2_.my_additional_column AS my_additional_column6
FROM parententitys f0_
LEFT JOIN childentity f2_ ON f0_.id = f2_.id
GROUP BY f0_.id, <f0_.* columns>

The SQL should be:

SELECT f0_.id AS id0, <f0_.* columns>, f2_.my_additional_column AS my_additional_column6
FROM parententitys f0_
LEFT JOIN childentity f2_ ON f0_.id = f2_.id
GROUP BY f0_.id, <f0_.* columns>, f2_.my_additional_column

N.b later versions of PostgreSQL don't require the GROUP BY on all the columns, just the primary key. Therefore the following would be sufficient:

SELECT f0_.id AS id0, <f0_.* columns>, f2_.my_additional_column AS my_additional_column6
FROM parententitys f0_
LEFT JOIN childentity f2_ ON f0_.id = f2_.id
GROUP BY f0_.id, f2_.id





[DDC-2914] [GH-910] [DDC-2310] Fix SQL generation on table lock hint capable platforms Created: 13/Jan/14  Updated: 31/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/doctrine2/pull/910

Message:

SQL Server and SQL Anywhere use table lock hints for locking. ORM generates wrong SQL when used in conjunction with joins, in a table inheritance scenario or in a subquery. It places the table lock hints after the `JOIN` clauses, which is wrong. The table lock hints have to be placed after each table alias in the `FROM` clause.

*Example (current)*
```sql
SELECT t0.id FROM users t0 INNER JOIN profiles t1 ON t0.id = t1.user_id WITH (NOLOCK)
```

*Example (expected)*
```sql
SELECT t0.id FROM users t0 WITH (NOLOCK) INNER JOIN profiles t1 ON t0.id = t1.user_id
```

The testsuites fail big time at the moment because of that and I suppose ORM is more or less unusable at the moment for those platforms without this patch.

I needed to adjust a lot of tests which compared compiled DQL, to make use of the platforms specific lock hint clauses.
Also I did not add new tests because there are already so many tests, where this fails without this patch that this is not necessary IMO.



 Comments   
Comment by Doctrine Bot [ 31/Jan/14 ]

A related Github Pull-Request [GH-910] was closed:
https://github.com/doctrine/doctrine2/pull/910





[DDC-2911] IndexBy doesn' work with arbitrary join Created: 13/Jan/14  Updated: 13/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Konstantin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   
        $statsQb = $em->createQueryBuilder()
            ->select('d AS date')
            ->from('MetalStatisticBundle:Day', 'd', 'd.date')
            ->leftJoin('MetalStatisticBundle:StatsDaily', 'sd', 'WITH', 'd.date = sd.date', 'sd.date')
            ->addSelect('sd AS stats')
            ->andWhere('sd.company = :company_id')
            ->setParameter('company_id', $company->getId())
            ->orderBy('sd.date', 'DESC')
            ->setMaxResults(10)

expected: array like

2012-10-10 => array(date => object, stats => object)
2012-10-09 => array(date => object)
2012-10-08 => array(date => object, stats => object)

got: exception Expected Literal, got 'BY'






[DDC-2901] entity-listeners are not propagated to children of mapped superclasses Created: 09/Jan/14  Updated: 09/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Stuart Carnie Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping


 Description   

If I have event-listeners set on the subclass and mapped superclass, event-listeners will not be propagated, per this code. Conversely, lifecycle events are, per this






[DDC-2891] Impossible to pass a limit to a subquery Created: 07/Jan/14  Updated: 08/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: 2.4.2
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: alex Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

It seems that passing the limit to a subquery is not working

 
$subquery = $em->createQueryBuilder()->from('...')->where('...')->setMaxResults(5);
$query = $em->createQueryBuilder()->from('...')->where(
   $qb->expr()->in('p.id', $subquery->getDQL())
);
$query->getQuery()->getResult();

The query works but the is no specified limit in the resulting SQL.
I am aware that DQL does not support the limits and offsets, so i guess there should be another way to get this working?



 Comments   
Comment by Steve Müller [ 08/Jan/14 ]

Can you please tell which database platform you are using? Because limiting results heavily depends on the platform used.

Comment by alex [ 08/Jan/14 ]

MySql

Comment by Steve Müller [ 08/Jan/14 ]

Hmmm I am not quite sure if the limit/offset is invoked for subqueries but I don't see why it shouldn't. Also I think this is not a DBAL issue because the limit/offset support for MySQL is the easiest we have on all platform. See: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php#L51-L63
The query doesn't have to be modified but instead only the limit clause is appended to the query. Can you maybe provide the generated SQL for that query?

Comment by alex [ 08/Jan/14 ]

I think if you try to build any query with QueryBuilder, set a limit to it with setMaxResults then call getDQL method, you should see that the output contains no info about limit.
So if you look at my code example , at $qb->expr()>in('p.id', $subquery>getDQL()), then you will see that the getDQL passes to the IN expression a query which already DOES NOT have limit. So this is the place where any info about limits and offsets gets lost.

So I fail to see what it has to do with any specific db engine,however I can provide the mysql resulting query if you want,though it looked perfectly normal to me,just lacks the LIMIT part.





[DDC-2888] [GH-899] Add travis build matrix for all built-in PostgreSQL versions Created: 06/Jan/14  Updated: 06/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/doctrine2/pull/899

Message:

[Travis now ships with PostgreSQL version 9.1, 9.2 and 9.3 built-in](http://about.travis-ci.org/blog/2013-11-29-postgresql-92-93-now-available/). We should extend our build matrix to test on all versions.






[DDC-2881] [GH-895] Fix for no dot on Class Names Created: 04/Jan/14  Updated: 04/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of sinner:

Url: https://github.com/doctrine/doctrine2/pull/895

Message:

If you work with PostgreSQL Schemas, You should filter the names of table to generate Correct name for PHP Classes. This way allow not write dots (.) as part of the Class Name.

Additionally, there is a variable ($schema) that must be contained in the class "Doctrine\DBAL\Schema\Table" on an $schema possible property but this is not available. (recomended)






[DDC-2879] Persisting collections with Composite Primary Keys composed of 2 Foreign Keys and one metadata field Created: 31/Dec/13  Updated: 07/Jan/14

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Dylan Johnson Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: composite, identity, mapping, orm, postgresql
Environment:

Ubuntu 13.04 and PostgresSQL 9.1.0 on Vagrant Virtual Machine running an application with Symfony2 backend and JavaScript client



 Description   

SYNOPSIS

Bug prevents persisting a collection of entities in a join table with a Composite Primary
Key made up of 2 Foreign Keys and one metadata field. From these mapping instructions:
http://docs.doctrine-project.org/en/latest/tutorials/composite-primary-keys.html#use-case-3-join-table-with-metadata

ISSUE DETAILS

SUCCESS: When FOREIGN KEY 1 is the same across items in a collection to be persisted, and FOREIGN KEY 2 is greater than FOREIGN KEY 2 in any existing PRIMARY KEY, the entity and collection are persisted correctly

    • Example: GPA "add val below" exists and has assessment value
      {"grade_point_average_id":1,"assessment_id":1,"value":4}

      We will try to add a new assessment value where assessment_id > that of any existing assessment value for GPA "add val below"

    • Request Payload:
      {"name":"Add Val Below","courses":[],"assessmentValues":[{"assessment":1,"value":4},{"assessment":3,"value":2}]}
    • Debug Log:
      [2014-01-07 11:48:01] app.INFO: START GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL BELOW] [] []
      [2014-01-07 11:48:01] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 4 [] []
      [2014-01-07 11:48:01] app.INFO:         MANAGED? 1 [] []
      [2014-01-07 11:48:01] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:48:01] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 1 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 3 [] []
      [2014-01-07 11:48:01] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 2 [] []
      [2014-01-07 11:48:01] app.INFO:         MANAGED?  [] []
      [2014-01-07 11:48:01] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Below - ASSESSMENT VALUE 3 [] []
      [2014-01-07 11:48:01] app.INFO: END GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL BELOW] [] []
      [2014-01-07 11:48:01] doctrine.DEBUG: "START TRANSACTION" [] []
      [2014-01-07 11:48:01] doctrine.DEBUG: INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?) {"1":2,"2":"1","3":"3"} []
      [2014-01-07 11:48:01] doctrine.DEBUG: UPDATE gpa_assessment_value SET point_value = ? WHERE grade_point_average_id = ? AND assessment_id = ? [4,1,1] []
      [2014-01-07 11:48:01] doctrine.DEBUG: "COMMIT" [] []

FAILURE: When FOREIGN KEY 1 is the same across items in a collection, and FOREIGN KEY 2 is less than any existing FOREIGN KEY 2, the unit of work tries to INSERT existing entity and does not operate on new entity. The EntityManager thinks it contains() the new entity, but not the old one

    • Example: GPA "add val above" exists and has assessment value
      {"assessment":3,"value":2}

      We will try to add a new assessment value where assessment_id < that of any existing assessment value for GPA "add val above"

    • Request Payload:
      {"name":"Add Val Above","courses":[],"assessmentValues":[{"assessment":1,"value":4},{"assessment":3,"value":2}]}
    • Debug log:
      [2014-01-07 11:47:09] app.INFO: START GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL ABOVE] [] []
      [2014-01-07 11:47:09] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 1 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 1 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 4 [] []
      [2014-01-07 11:47:09] app.INFO:         MANAGED? 1 [] []
      [2014-01-07 11:47:09] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:47:09] app.INFO:   BEGIN OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         GRADE_POINT_AVERAGE #GET_ID: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_ASSESSMENT #GET_ID: 3 [] []
      [2014-01-07 11:47:09] app.INFO:         ASSESSMENT_VALUE #GET_VALUE: 2 [] []
      [2014-01-07 11:47:09] app.INFO:         MANAGED?  [] []
      [2014-01-07 11:47:09] app.INFO:   END OUTPUT FOR GRADE POINT AVERAGE Add Val Above - ASSESSMENT VALUE 3 [] []
      [2014-01-07 11:47:09] app.INFO: END GRADE_POINT_AVERAGE_REPOSITORY #SAVE [GPA #GET_NAME =ADD VAL ABOVE] [] []
      [2014-01-07 11:47:09] doctrine.DEBUG: "START TRANSACTION" [] []
      [2014-01-07 11:47:09] doctrine.DEBUG: INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?) {"1":2,"2":"2","3":"3"} []
      [2014-01-07 11:47:09] doctrine.DEBUG: "ROLLBACK" [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException". [] []
      [2014-01-07 11:47:09] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException". [] []
      [2014-01-07 11:47:09] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\DBALException: "An exception occurred while executing 'INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?)' with params [2, "2", "3"]:
      
      SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint "gpa_assessment_value_pkey"
      DETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists." at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php line 47 {"exception":"[object] (Doctrine\\DBAL\\DBALException: An exception occurred while executing 'INSERT INTO gpa_assessment_value (point_value, grade_point_average_id, assessment_id) VALUES (?, ?, ?)' with params [2, \"2\", \"3\"]:\n\nSQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"gpa_assessment_value_pkey\"\nDETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists. at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:47, PDOException: SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"gpa_assessment_value_pkey\"\nDETAIL:  Key (grade_point_average_id, assessment_id)=(2, 3) already exists. at /vagrant/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:138)"} []
         

CODE

migration.sql
CREATE TABLE assessment
(
    id       bigserial NOT NULL,
    scale_id bigint    NOT NULL,
    title    varchar   NOT NULL,
    passing  boolean   NOT NULL,
    rank     int,

    PRIMARY KEY (id)
);

CREATE TABLE assessment_scale
(
    id   bigserial NOT NULL,
    name varchar   NOT NULL,

    PRIMARY KEY (id)
);

-- ...

CREATE TABLE grade_point_average
(
    id                         bigserial       NOT NULL,
    name                       varchar         NOT NULL,
    additional_credit_allowance numeric(4, 2),

    PRIMARY KEY (id)
);

-- ...

CREATE TABLE gpa_assessment_value
(
    grade_point_average_id bigint        NOT NULL,
    assessment_id          bigint        NOT NULL,
    point_value            numeric(4, 2) NOT NULL,

    PRIMARY KEY (assessment_id, grade_point_average_id),
    FOREIGN KEY (assessment_id) REFERENCES assessment,
    FOREIGN KEY (grade_point_average_id) REFERENCES grade_point_average
);
GradePointAverage.php
<?php
namespace LGSConnect\Model;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
//...
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use LGSConnect\Util\ConstructorArgs;
use LGSConnect\Model\GradePointAverage\AssessmentValue;
// ...

/**
 * @Entity("LGSConnect\Repository\GradePointAverageRepository")
 */
class GradePointAverage
{
    // GradePointAverage Model (owning side): a tool for evaluating a student's performance 
    // by dividing the total points earned by total credits attempted.

    use ConstructorArgs;

    /**
     * @Id
     * @GeneratedValue
     * @Column(type="bigint")
     *
     * @var int
     */
    private $id;

    // ...

    /**
     * @OneToMany(targetEntity="LGSConnect\Model\GradePointAverage\AssessmentValue", mappedBy="gradePointAverage", cascade="persist")
     *
     * @var Collection
     */
    private $assessmentValues;
    
    // ...

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->assessmentValues = new ArrayCollection;
        // ...
        $this->handleArgs($args);
    }
    
    // ...
    
    /**
     * @return Collection
     */
    public function getAssessmentValues()
    {
        return $this->assessmentValues;
    }

    /**
     * @param ArrayCollection $assessmentValues
     */
    public function setAssessmentValues(ArrayCollection $assessmentValues)
    {
        $this->assessmentValues = $assessmentValues;
    }

    /**
     * @param AssessmentValue $assessmentValue
     */
    public function addAssessmentValue(AssessmentValue $assessmentValue)
    {
        $this->assessmentValues->add($assessmentValue);
    }

    /**
     * @param AssessmentValue $assessmentValue
     */
    public function removeAssessmentValue(AssessmentValue $assessmentValue)
    {
        $this->assessmentValues->removeElement($assessmentValue);
    }
    
    // ...
}
AssessmentValue.php
<?php
namespace LGSConnect\Model\GradePointAverage;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\JoinColumn;
use LGSConnect\Model\GradePointAverage;
use LGSConnect\Model\Assessment;
use LGSConnect\Util\ConstructorArgs;

/**
 * @Entity("LGSConnect\Repository\GradePointAverage\AssessmentValueRepository")
 * @Table("gpa_assessment_value")
 */
class AssessmentValue
{
    // AssessmentValue Model (inverse side): a number of points assigned 
    // to an Assessment by a Grade Point Average

    use ConstructorArgs;

    /**
     * @Id
     * @ManyToOne(targetEntity="LGSConnect\Model\GradePointAverage")
     */
    private $gradePointAverage;

    /**
     * @Id
     * @ManyToOne(targetEntity="LGSConnect\Model\Assessment")
     */
    private $assessment;

    /**
     * @Column("point_value")
     *
     * @var float
     */
    private $value;

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->handleArgs($args);
    }

    /**
     * @return GradePointAverage
     */
    public function getGradePointAverage()
    {
        return $this->gradePointAverage;
    }

    /**
     * @param GradePointAverage $gradePointAverage
     */
    public function setGradePointAverage(GradePointAverage $gradePointAverage)
    {
        $this->gradePointAverage = $gradePointAverage;
    }

    /**
     * @return Assessment
     */
    public function getAssessment()
    {
        return $this->assessment;
    }

    /**
     * @param Assessment $assessment
     */
    public function setAssessment(Assessment $assessment)
    {
        $this->assessment = $assessment;
    }

    /**
     * @return float
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param float $value
     */
    public function setValue($value)
    {
        $this->value = $value;
    }

    /**
     * @return AssessmentScale
     */
    public function getAssessmentScale()
    {
        return $this->assessment->getScale();
    }
}
Assessment.php
<?php
namespace LGSConnect\Model;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\ManyToOne;
use LGSConnect\Model\Assessment\Scale;
use LGSConnect\Util\ConstructorArgs;

/**
 * @Entity("LGSConnect\Repository\AssessmentRepository")
 */
class Assessment
{
    // Assessment (related, but unmapped): A "grade" assigned to a student 
    // for attending a course section

    use ConstructorArgs;

    /**
     * @Id
     * @GeneratedValue
     * @Column(type="bigint")
     *
     * @var int
     */
    private $id;
    
    // ...

    /**
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->handleArgs($args);
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
    
    // ...
}
GradePointAverageRepository.php
<?php
namespace LGSConnect\Repository;

use Doctrine\ORM\EntityRepository;
// ...
use LGSConnect\Model\GradePointAverage;

class GradePointAverageRepository extends BaseRepository implements GradePointAverageRepositoryInterface
{
    // ...

    /**
     * @param GradePointAverage $gradePointAverage
     */
    public function save(GradePointAverage $gradePointAverage)
    {
        $this->getEntityManager()->persist($gradePointAverage);
        $this->getEntityManager()->flush();
    }
}
AssessmentValueRepository.php
<?php
namespace LGSConnect\Repository\GradePointAverage;

use Doctrine\ORM\EntityRepository;
use LGSConnect\Model\GradePointAverage\AssessmentValue;

class AssessmentValueRepository extends EntityRepository
{
    /**
     * @param AssessmentValue $assessmentValue
     */
    public function save(AssessmentValue $assessmentValue)
    {
        $this->getEntityManager()->persist($assessmentValue);
        $this->getEntityManager()->flush();
    }
}
GradePointAverageManager.php
<?php
namespace LGSConnect\Manager;

use InvalidArgumentException;
use Symfony\Component\Validator\ValidatorInterface;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use Knp\Component\Pager\Pagination\PaginationInterface;
use LGSConnect\Repository\GradePointAverageRepository;
use LGSConnect\PaginationFactory\GradePointAveragePaginationFactoryInterface;
use LGSConnect\Model\GradePointAverage;

/**
 * @Service("grade_point_average_manager")
 */
class GradePointAverageManager
{
    /**
     * @var GradePointAverageRepository
     */
    private $gradePointAverageRepository;

    /**
     * @var GradePointAveragePaginationFactoryInterface
     */
    private $gradePointAveragePaginationFactory;

    /**
     * @var ValidatorInterface
     */
    private $validator;

    /**
     * @InjectParams
     *
     * @param GradePointAverageRepository $gradePointAverageRepository
     * @param GradePointAveragePaginationFactoryInterface $gradePointAveragePaginationFactory
     * @param ValidatorInterface $validator
     */
    public function __construct(
        GradePointAverageRepository $gradePointAverageRepository,
        GradePointAveragePaginationFactoryInterface $gradePointAveragePaginationFactory,
        ValidatorInterface $validator
    )
    {
        $this->gradePointAverageRepository = $gradePointAverageRepository;
        $this->gradePointAveragePaginationFactory = $gradePointAveragePaginationFactory;
        $this->validator = $validator;
    }

    /**
     * @PreAuthorize("isAllowedToManageTheGradePointAverage(#gradePointAverage)")
     * @param GradePointAverage $gradePointAverage
     * @throws InvalidArgumentException
     */
    public function save(GradePointAverage $gradePointAverage)
    {
        $violationList = $this->validator->validate($gradePointAverage);
        if ($violationList->count()) {
            throw new InvalidArgumentException;
        }

        $this->gradePointAverageRepository->save($gradePointAverage);
    }
}
GradePointAverageController.php
<?php
namespace LGSConnect\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Doctrine\Common\Collections\ArrayCollection;
use FOS\RestBundle\View\View;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use Knp\Component\Pager\Pagination\PaginationInterface;
use LGSConnect\Manager\GradePointAverageManager;
use LGSConnect\Model\GradePointAverage;
use LGSConnect\Model\GradePointAverage\AssessmentValue;

/**
 * @Service("grade_point_average_controller", parent="lgs.controller.abstract")
 * @Route("/gpa", service="grade_point_average_controller")
 */
class GradePointAverageController extends BaseController
{
    /**
     * @var GradePointAverageManager
     */
    private $gradePointAverageManager;

    private $logger;

    /**
     * @InjectParams
     *
     * @param GradePointAverageManager $gradePointAverageManager
     * @param LoggerInterface $logger
     */
    public function __construct(GradePointAverageManager $gradePointAverageManager, LoggerInterface $logger)
    {
        $this->gradePointAverageManager = $gradePointAverageManager;
        $this->logger = $logger;
    }
    
    // ...

    /**
     * @Route("/{id}", name="gpa.edit", requirements={"id" = "\d+"})
     * @Method("PUT")
     *
     * @param Request $request
     * @param GradePointAverage $gpa
     * @return View
     */
    public function editAction(Request $request, GradePointAverage $gpa)
    {
        $form = $this->formFactory->createNamed(null, 'gpa', $gpa, [
            'method' => 'PUT',
        ]);
        $form->handleRequest($request);

        foreach ($gpa->getAssessmentValues() as $av) {
            $this->logger->info('GPA ID PREVALIDATE IN CONTROLLER:'.$gpa->getId());
            $this->logger->info('PREVALIDATE IN CONTROLLER ASSESSMENT VAL ASSESSMENT ID:'.$av->getAssessment()->getId());
            $this->logger->info('PREVALIDATE IN CONTROLLER ASSESSMENT VAL POINTS:'.$av->getValue());
        }

        /*
        // try reversing the order of the collection to see if that helps
        $assessmentVals = $gpa->getAssessmentValues()->toArray();
        $reversed = array_reverse($assessmentVals);
        $reversedColl = new ArrayCollection($reversed);
        $gpa->setAssessmentValues($reversedColl);
        */

        if ($form->isValid()) {
            foreach ($gpa->getAssessmentValues() as $av) {
                $this->logger->info('GPA ID PRESAVE IN CONTROLLER:'.$gpa->getId());
                $this->logger->info('PRESAVE IN CONTROLLER ASSESSMENT VAL ASSESSMENT ID:'.$av->getAssessment()->getId());
                $this->logger->info('PRESAVE IN CONTROLLER ASSESSMENT VAL POINTS:'.$av->getValue());
            }
            $this->gradePointAverageManager->save($gpa);

            return new View($gpa, 204);
        }

        return new View($form);
    }

    // ...
}
GradePointAverageType.php
<?php
namespace LGSConnect\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use JMS\DiExtraBundle\Annotation\FormType;

/**
 * @FormType
 */
class GradePointAverageType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('courses', 'entity', [
                'class' => 'Model:Course',
                'multiple' => true
            ])
            ->add('assessmentValues', 'collection', [
                'type' => 'gpa_assessment_value',
                'allow_add' => true,
                'by_reference' => false,
            ])
        ;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gpa';
    }
}
AssessmentValueType.php
<?php
namespace LGSConnect\Form\Type\GradePointAverage;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use JMS\DiExtraBundle\Annotation\FormType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @FormType("gpa_assessment_value")
 */
class AssessmentValueType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('assessment', 'entity', [
                'class' => 'Model:Assessment',
            ])
            ->add('value', 'number', [
                'precision' => 2,
            ])
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'LGSConnect\Model\GradePointAverage\AssessmentValue',
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gpa_assessment_value';
    }
}





[DDC-2875] [GH-890] [DBAL-563] Add general IDENTITY generator type support for sequence emulating platforms Created: 29/Dec/13  Updated: 31/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/doctrine2/pull/890

Message:

This is a follow-up PR for https://github.com/doctrine/dbal/pull/428 as discussed in DBAL-563(http://www.doctrine-project.org/jira/browse/DBAL-563) which adds IDENTITY generator type support for platforms that do not natively support identity columns but can emulate them via sequences.
This replaces the current workaround for PostgreSQL `SERIAL` columns in favour of a more general approach. With this patch now IDENTITY generator can also be used with Oracle which did not work before. Future platforms can also make use of this approach if necessary.



 Comments   
Comment by Doctrine Bot [ 31/Dec/13 ]

A related Github Pull-Request [GH-890] was closed:
https://github.com/doctrine/doctrine2/pull/890





[DDC-2870] Doctrine error when using SUM(a.id=1) as `ìdentifier`: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '=' Created: 22/Dec/13  Updated: 06/Jan/14

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Maxim Geerinck Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: dql
Environment:

Symfony2 bundle



 Description   

Doctrine error when using SUM(a.id=1) as `ìdentifier`: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '='

I am trying to execute a query in doctrine that contains something like this

SUM(a.id = 1) as `1`
for some reasons it always gives me the following error:

[Syntax Error] line 0, col 15: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '='
This is the code i am using

$result = $em->getRepository('MyBundle:PlayerAction')
->createQueryBuilder('pa')
->select(array(
'SUM(a.id=1) as `1`,
SUM(a.id=2) as `2`,
SUM(a.id=3) as `3`,
p.playerName,
pa.timestamp'
))
->innerJoin('pa.action', 'a')
->innerJoin('pa.player', 'p')
->where('pa.timestamp > ?1')
->groupBy('p')
->setParameter(1, time() - $time)
->orderBy('p.playerName', 'ASC');






[DDC-2869] [GH-886] [DDC-1256] Fix applying ON/WITH conditions to first join in Class Table Inheritance Created: 22/Dec/13  Updated: 17/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of Strate:

Url: https://github.com/doctrine/doctrine2/pull/886

Message:

Some related issues:
http://www.doctrine-project.org/jira/browse/DDC-1256
http://www.doctrine-project.org/jira/browse/DDC-2131

I think that applying custom user joins conditions to last join in CTI is ok because only in last join DB will know about all joined table aliases. And I can't see any other probles with this.

Tests are not passed, because, I think, problem in tests.

To be discussed, of course



 Comments   
Comment by Doctrine Bot [ 17/Feb/14 ]

A related Github Pull-Request [GH-886] was closed:
https://github.com/doctrine/doctrine2/pull/886





[DDC-2861] [GH-881] Fix persistence exception on a table with a schema on a platform without schema support Created: 18/Dec/13  Updated: 18/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of michaelperrin:

Url: https://github.com/doctrine/doctrine2/pull/881

Message:

This PR solves two related issues with the use of a database schema on platforms (such as SQLite) that don't support schemas.

I discovered the issues when I generated the schema from my Doctrine entities on SQLite (for unit test purposes of my application) whereas my main application uses PostgreSQL.

This is one of my first PR on Doctrine, so sorry if I made some things in the wrong way and I'm open to discussion.

*First problem: table names dots are not converted in the ORM*

On a platform like SQLite, DBAL converts table names with dots (ie. a schema is declared) to double underscores.
However, the ORM doesn't do it, and persisting leads to an exception.

Example:

```
MyNamespace\Mytable:
type: entity
table: myschema.mytable

  1. ...
    ```

And then somewhere in the code:

```
$myTable = new MyNamespace\Mytable();
$entityManager->persist($myTable);
$entityManager->flush();
```

This doesn't work in the current version of Doctrine. The table is created as `myschema__mytable` but entities are unsuccessfully saved in `myschema.mytable`.

*Second problem: table names with reserved keywords in a database schema are not correctly escaped*

When a table name is declared as `myschema.order` (or any other reserved keyword), only the reserved keyword part is escaped when creating the table, leading to the creation of a table name like myschema__\`order\`, which is invalid and therefore fails.

*How this PR solves the problem*

The classmetadata now stores in 2 separated properties the name of the table and the name of the schema. The schema property was partially implemented but I now make a full use of it.

When metadata is read (from Annotations, YAML, ...), if the table name has a dot (`myschema.mytable`), it's splitted into 2 parts, and `myschema` is saved in the `schema` table property, and `mytable` is saved in the `name` table property, instead of storing the whole `myschema.mytable` in the `name` table property.

This allows to do specific things about schemas everywhere in Doctrine, and not splitting again parts everywhere it's needed.

By the way, the `schema` property can now fully be used.

For instance, these 2 YAML configurations are valid and do the same thing:

```
MyNamespace\Mytable:
type: entity
table: myschema.mytable
```

and:

```
MyNamespace\Mytable:
type: entity
table: mytable
schema: myschema
```

This was something which was not finished to be implented since Doctrine 2.0.

The Default quote strategy now converts back the schema and table names to a unique table name, depending on the platform (e.g. `myschema.mytable` if the platform supports schemas, and `myschema__mytable` otherwise).

As a result, there is no problem anymore and entities can be persisted without getting any exception.
I added some unit tests for this (the same unit tests failed before of course).

There's however a slight tradeoff on performance, as the `getTableName` of the `DefaultQuoteStrategy` class adds some tests to return the correct table name.

This solved these Doctrine issues: DDC-2825(http://www.doctrine-project.org/jira/browse/DDC-2825) and DDC-2636(http://www.doctrine-project.org/jira/browse/DDC-2636).

Again, this is one of my first PRs on Doctrine, so if there's anything wrong or if you have any question, feel free to comment this PR.

@Ocramius This PR is about what we talked about in DDC-2825(http://www.doctrine-project.org/jira/browse/DDC-2825)






[DDC-2852] Enclose subquery with parenthesis in from clause (QueryBuilder) Created: 12/Dec/13  Updated: 12/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Matthieu Pécro Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: from, orm, parenthesis, querybuilder,, subquery


 Description   

Hi

In QueryBuilder from clause, when argument is a QueryBuilder (not a string like a table), there are not parenthesis enclosure on the subquery.

Ex:
$subqb->select('myfield')->from('mytable');
$qb->from($sub, 'myalias)

DQL is : SELECT myfield FROM SELECT myField FROM mytable myalias. This is not working on MySQL.

It should be : SELECT myfield FROM (SELECT myField FROM mytable) myalias.



 Comments   
Comment by Christophe Coevoet [ 12/Dec/13 ]

I don't understand your statement This is not working on MySQL. after giving a DQL statement. MySQL does not support any DQL. It runs SQL.

And DQL does not support using a subselect in the FROM clause





[DDC-2851] Allow set custom collection initializer at runtime Created: 12/Dec/13  Updated: 12/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.1
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Konstantin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Use case: Company, Category, CompanyCategory entities. We are loading set of companies and should initialize Company.companyCategories collection with joined categories, which ordered by Company.title.

I cann't do it via Criteria API, it doesn't supports joins. + I should return same PersistentCollection instance (Company.companyCategories used in Symfony2 forms).

Current workaround:

    public function loadCompanyCategoriesCollectionForCompany(Company $company)
    {
        $companyCategories = $this->_em->createQueryBuilder()
            ->select('cc')
            ->from('OloloCompaniesBundle:CompanyCategory', 'cc')
            ->join('cc.category', 'c')
            ->addSelect('c')
            ->orderBy('c.title')
            ->where('cc.company = :company')
            ->setParameter('company', $company)
            ->getQuery()
            ->getResult()
        ;

        $coll = $company->getCompanyCategories();
        foreach ($companyCategories as $companyCategory) { /* @var $coll \Doctrine\ORM\PersistentCollection */
            $coll->hydrateAdd($companyCategory);
        }
        $coll->setInitialized(true);
    }

What would be nice: native API for setting custom initializers.






[DDC-2841] Preload data for association Created: 06/Dec/13  Updated: 06/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Przemyslaw Wrobel Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Consider two classes User and Address with one-to-many association.
I would like to preload addresses for given user object so that it will be accessible via getter method like this:

1. $user = $userRepository->find($userId);
2. load some of the addresses but not all
3. $user->getAddresses() should return those loaded in step 2

Currently the only solution for step 2 I found working is to write a DQL like this:
SELECT u, a
FROM User
INNER JOIN u.addresses a
WHERE u = :user AND a.foo = 1

When the data is hydrated it is assigned to the user object and thus accessible with $user->getAddresses (which normally would return all the addresess not only those with foo set)

The only problem is that the query in step 2 unnecessarily fetches all user data that was already fetched in step 1






[DDC-2839] [GH-869] Detach objects in original object data Created: 04/Dec/13  Updated: 05/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of tomphp:

Url: https://github.com/doctrine/doctrine2/pull/869

Message:

The PR makes Doctrine ORM update the database when you execute something like this:

```php
// MyEntity.php

/**

  • @Entity
    */
    class MyEntity
    {
    // ...

/**

  • @Column(type="datetime")
    */
    private $created;

// ...

public function setCreated(\DateTime $created)

{ $this->created = $created; }

public function getCreated()

{ return $this->created; }

// ...
}
```

```php
// Current problem

$entity = $entityManager->find('MyEntity', 1);

$entity->getCreated()->setDate('2001-01-01');

$entityManager->persist($entity);

$entityManager->flush();

// At this point no changes have been made to the database!
```

The reason this doesn't work currently is because the array of original data stored in the UnitOfWork contains the actual DateTime object which is in the entity. When you update the object in the entity the original data is updated also so the entity are the original value are still equal and therefore the object is not seen as changed.

I have chosen to clone all objects rather than just DateTime object include more types are included in the future.



 Comments   
Comment by Doctrine Bot [ 05/Dec/13 ]

A related Github Pull-Request [GH-869] was closed:
https://github.com/doctrine/doctrine2/pull/869





[DDC-2838] Leaky abstraction when applying Criteria to hydrated/non-hydrated PersistentCollection Created: 03/Dec/13  Updated: 03/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: brian ridley Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When applying a Criteria to a PersistentCollection that has been hydrated the field names must be camel case, if the collection has not yet been hydrated the field names must be underscore separated.

The github repo linked here contains a simplified testcase for the matrix of hydrated/non-hydrated entities and camel case/underscore separated fields.

https://github.com/ptlis/DoctrineTestcase






[DDC-2835] No Lock Hint on Joins Created: 03/Dec/13  Updated: 03/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Paul Mansell Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Microsoft SQL Server 2008/2012



 Description   

There seems to be no lock hits added to the joins on a query. For example, take the following query :

SELECT w0_.name AS name0, w1_.name AS name1, c2_.name AS name2, count(w3_.id) AS sclr3 FROM workflow_request w3_ WITH (NOLOCK) INNER JOIN workflow_request_status w1_ ON w3_.status_id = w1_.id INNER JOIN workflow_action w0_ ON w3_.action_id = w0_.id LEFT JOIN workflow_transition w4_ ON w3_.transition_id = w4_.id INNER JOIN core_mno_account c5_ ON w4_.mno_account_id = c5_.id INNER JOIN core_mno c2_ ON c5_.mno_id = c2_.id LEFT JOIN workflow_state w6_ ON w3_.current_state_id = w6_.id WHERE w1_.ident IN GROUP BY w0_.name, w1_.name, c2_.name ORDER BY w0_.name ASC, w1_.name ASC, c2_.name ASC [["waiting"]]

the "with(nolock)" is only added to the FROM clause .... it should be added after each join too






[DDC-2834] [GH-868] Added documentation section for Memcached Created: 02/Dec/13  Updated: 02/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of mnapoli:

Url: https://github.com/doctrine/doctrine2/pull/868

Message:

The documentation only talked about Memcache, an old PHP extension that can now be safely replaced by Memcached.

I've add a section of documentation about Memcached because the code to have it working is not the same.



 Comments   
Comment by Doctrine Bot [ 02/Dec/13 ]

A related Github Pull-Request [GH-868] was closed:
https://github.com/doctrine/doctrine2/pull/868





[DDC-2826] Add support for mapping collections of embeddable objects Created: 28/Nov/13  Updated: 08/Feb/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: songoko songowan Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: collection, orm, value-objects


 Description   

In Hibernate we can do something like this:

    @Entity
    public class User {
       [...]
       public String getLastname() { ...}
    
       @ElementCollection
       @CollectionTable(name="Addresses", joinColumns=@JoinColumn(name="user_id"))
       @AttributeOverrides({
          @AttributeOverride(name="street1", column=@Column(name="fld_street"))
       })
       public Set<Address> getAddresses() { ... } 
    }
    
    @Embeddable
    public class Address {
       public String getStreet1() {...}
       [...]
    }

Basically a collection of value objects is mapped to a new table. Currently Doctrine2 is on its way to support value objects

However, this implementation won't support mapping a collection of objects to a new table and the only way to circumvent this issue is to treat the address an an entity and use an one-to-many unidirectional relationship through a many-to-many join table



 Comments   
Comment by Doctrine Bot [ 08/Feb/14 ]

A related Github Pull-Request [GH-835] was closed:
https://github.com/doctrine/doctrine2/pull/835





[DDC-2819] [GH-860] Mention SQL Anywhere in basic mapping documentation Created: 25/Nov/13  Updated: 25/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of deeky666:

Url: https://github.com/doctrine/doctrine2/pull/860

Message:

Just for documentation completion of the new SQL Anywhere platform.



 Comments   
Comment by Doctrine Bot [ 25/Nov/13 ]

A related Github Pull-Request [GH-860] was closed:
https://github.com/doctrine/doctrine2/pull/860





[DDC-2816] New event: pre-execute query Created: 25/Nov/13  Updated: 25/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Artur Eshenbrener Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

It would be useful to fire event just before each query executes. Listeners can set hints to query, for instance.






[DDC-2813] [GH-857] free more resources Created: 22/Nov/13  Updated: 23/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of Gladhon:

Url: https://github.com/doctrine/doctrine2/pull/857

Message:

use unset to free resources better



 Comments   
Comment by Doctrine Bot [ 23/Nov/13 ]

A related Github Pull-Request [GH-857] was closed:
https://github.com/doctrine/doctrine2/pull/857





[DDC-2811] [GH-854] fix relative path to doctrine/common Created: 22/Nov/13  Updated: 23/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of ptarjan:

Url: https://github.com/doctrine/doctrine2/pull/854

Message:

While testing your framework on HHVM I found this test doesn't pass because the path doesn't find what composer was installing into



 Comments   
Comment by Doctrine Bot [ 23/Nov/13 ]

A related Github Pull-Request [GH-854] was closed:
https://github.com/doctrine/doctrine2/pull/854





[DDC-2809] [GH-853] Fix for PHP entity default values generated by EntityGenerator Created: 21/Nov/13  Updated: 21/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of patrickkostjens:

Url: https://github.com/doctrine/doctrine2/pull/853

Message:

When specifying a default value for a column in the YAML, this value should be set in the entities that are generated by the EntityGenerator. The EntityGenerator looked for the default value in the wrong place of the field mapping and therefore defaults were never set. This issue has been fixed in this branch.



 Comments   
Comment by Doctrine Bot [ 21/Nov/13 ]

A related Github Pull-Request [GH-853] was closed:
https://github.com/doctrine/doctrine2/pull/853





[DDC-2799] [GH-850] Event listener to programmatically attach entity listeners. Created: 18/Nov/13  Updated: 25/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of FabioBatSilva:

Url: https://github.com/doctrine/doctrine2/pull/850

Message:

This patch adds a event listener to programmatically attach entity listeners.

Especially useful to attach listeners to external bundles/modules..



 Comments   
Comment by Doctrine Bot [ 25/Nov/13 ]

A related Github Pull-Request [GH-850] was closed:
https://github.com/doctrine/doctrine2/pull/850





[DDC-2797] [GH-848] eliminate duplicate placeholders in "walkComparison" function within Que... Created: 18/Nov/13  Updated: 18/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of bsahlhof:

Url: https://github.com/doctrine/doctrine2/pull/848

Message:

...ryExpressionVisitor

I've run into an issue when using Criteria with QueryBuilder when Criteria uses multiple checks on same variable in different context, example:
field1 = value OR (field1 in values AND field2 = true)... what happens is field 1 placeholder is duplicated, and an error occures in code complaining about invalid # of parameters. The fix eliminates this issue, making sure parametername is unique.

I have not had time to check any other possible issues this may cause, but a review of the code doesn't appear to impact any other function.



 Comments   
Comment by Doctrine Bot [ 18/Nov/13 ]

A related Github Pull-Request [GH-848] was closed:
https://github.com/doctrine/doctrine2/pull/848





[DDC-2795] the queryBuider Expr\Join class has a ON type but unsupported by the parser Created: 14/Nov/13  Updated: 14/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Documentation, DQL
Affects Version/s: 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Christophe Coevoet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: documentation, dql, querybuilder,


 Description   

The Doctrine\ORM\Query\Expr\Join class has 2 cosntants for the condition types: WITH and ON.

None of them are documented. The only place where WITH appear is the EBNF, which is outdated in the doc as it does not show arbitrary joins (added in 2.3) but only association joins.

and when looking at the EBNF in the code, I find 2 different ones (none of them matching the one given in the doc):

  • in Doctrine\ORM\query\Parser::Join:
Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN"
         (JoinAssociationDeclaration | RangeVariableDeclaration)
         ["WITH" ConditionalExpression]

This is matching the implementation and ON is not supported.

  • in Doctrine\ORM\Query\AST\Join:
Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" JoinAssociationPathExpression
         ["AS"] AliasIdentificationVariable [("ON" | "WITH") ConditionalExpression]

This one is missing 2 features also missing in the doc (INDEX BY for associations, and arbitrary joins) and adds the support of ON which is not implemented.

What is the reason to have this ON constant in the query builder ? It is confusing to get a DQL parse exception when using it if it is there.

On a side note, what is the canonical source for the EBNF ? There is 2 different locations in the code (the phpdoc of parser methods and the phpdoc of AST nodes created by the parser), plus the doc. Shouldn't we try to limit the duplication and have a way to check the consistency of the doc ?






[DDC-2794] the Paginator does not support arbitrary join Created: 14/Nov/13  Updated: 23/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: Git Master, 2.3.4, 2.4.1
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Christophe Coevoet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 2
Labels: paginator


 Description   

Using the following query with the paginator fails:

SELECT u
FROM User u
JOIN Message m WITH m.author = u
WHERE m.status = 'draft' -- a condition justifying the join

The CountWalker and the CountOutputWalker both throw a exception saying "Cannot count query which selects two FROM components, cannot make distinction"

This message is wrong (I can make distinction here. Only User is selected in the result set) and confusing (I spent some time finding the second FROM before figuring it was related to the use of an arbitrary join instead of an association join).



 Comments   
Comment by Pierre-Antoine Pinel [ 23/Dec/13 ]

Hi,

I have the same issue.
My query is : SELECT entity FROM W\XBundle\Entity\X entity LEFT JOIN Z\YBundle\Entity\Y y WITH y.x = entity LEFT JOIN y.v v WHERE v.name LIKE :like

Is there a way to fix this issue ? I really need this to work with the Paginator.

Best,

Comment by Christophe Coevoet [ 23/Dec/13 ]

Why changing the status to "Awaiting feedback" ? It is not waiting for a feedback of the reporter to check the fix. It is an open ticket which does not have a fix yet





[DDC-2791] Constant value in JoinColumn Created: 13/Nov/13  Updated: 13/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Pavel S. Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: joins, mapping, orm

Attachments: JPEG File realty_reference.jpeg    

 Description   

My situation:
I have realty entities (flat, house, ...) they have hundreds parameters, wich title places in REFERENCE table. For example House has a few floor materials (stone, wood, etc.) and I want to get them. But each parameter type defined by type_id field in REFERENCE table, for example for floor material is's 115. My raw SQL:
SELECT h.id,... FROM HOUSE h
LEFT JOIN object_detail mf /material_floor/ ON mf.realty_id = h.id AND mf.data_class = h.data_class AND mf.type_id = 115
LEFT JOIN Reference mfr ON mfr.city_id = h.city_id AND mfr.id = mf.detail_id

And its not possible to set type_id directly in join table






[DDC-2787] COALESCE() doesn't work with NOT IN() Created: 09/Nov/13  Updated: 09/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: flack Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When I try running the following query:

SELECT count(c.id) FROM my\model c WHERE COALESCE(c.up, 0) NOT IN( :parent_ids)

I get

Doctrine\ORM\Query\QueryException: [Semantical Error] line 0, col 118 near 'up, 0) NOT IN(': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

When I run the query as straight SQL against the database, it works as expected. Is this something that can be fixed in Doctrine or is this syntax unsupported?






[DDC-2786] [GH-843] Add failing test for DDC-2785 Created: 08/Nov/13  Updated: 08/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of flack:

Url: https://github.com/doctrine/doctrine2/pull/843

Message:

Add a failing test for

http://www.doctrine-project.org/jira/browse/DDC-2785






[DDC-2785] spl_object_hash_collisions Created: 08/Nov/13  Updated: 08/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: flack Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Ubuntu 12.04



 Description   

After reading DDC-1896 and DDC-136, I'm not exactly sure if this qualifies as a bug, but anyways, here's my code to reproduce:

    public function test_hash_collision()
    {
        $counter = 0;
        do
        {
            $object = $this->create_object();
            $counter++;
            if ($counter > 1000)
            {
                //mark as skipped ? (I never hit this on PHP 5.3 at least)
                break;
            }
        }
        while ($object === false);

        // This fails with "Failed asserting that 1 matches expected 2."
        $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($object));
    }

    private function create_object()
    {
        static $hashes = array();
        $phone = new CmsPhonenumber();
        $phone->phonenumber = "1234";
        $hash = spl_object_hash($phone);
        $this->_em->persist($phone);

        if (!array_key_exists($hash, $hashes))
        {
            $hashes[$hash] = true;
            $this->_em->flush($phone);
            $this->_em->remove($phone);
            $this->_em->flush($phone);
            return false;
        }
        // Bingo! We have a new object with a recycled hash
        return $phone;
    }


 Comments   
Comment by Marco Pivetta [ 08/Nov/13 ]

Are you able to reproduce the test also without statics?

Comment by flack [ 08/Nov/13 ]

Yes, if I switch to $this->hashes (private $hashes = array()), the result is the same

Comment by flack [ 08/Nov/13 ]

Here's the complete test without statics & according to Doctrine CS (AFAICT):

<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Tests\Models\CMS\CmsPhonenumber;

require_once __DIR__ . '/../../../TestInit.php';

/**
 * @group DDC-2785
 */
class DDC2785Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    public function setUp()
    {
        $this->useModelSet('cms');
        parent::setUp();
    }

    private $hashes = array();

    public function testIssue()
    {
        $counter = 0;
        do
        {
            $object = $this->createObject();
            $counter++;
            if ($counter > 1000)
            {
                //mark as skipped ? (I never hit this on PHP 5.3 at least)
                break;
            }
        }
        while ($object === false);

        $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($object));
    }

    private function createObject()
    {
        $phone = new CmsPhonenumber();
        $phone->phonenumber = "1234";
        $hash = spl_object_hash($phone);
        $this->_em->persist($phone);

        if (!array_key_exists($hash, $this->hashes))
        {
            $this->hashes[$hash] = true;
            $this->_em->flush();
            $this->_em->remove($phone);
            $this->_em->flush();
            return false;
        }

        return $phone;
    }
}

I can try and send this as a pull request, if it helps





[DDC-2783] EntityManager::transactional empty values as true Created: 07/Nov/13  Updated: 18/Apr/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Kirill chEbba Chebunin Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: entitymanager, transactional


 Description   

The problem:
Any response from transactional callback which is evaluated to false (empty array, empty string, 0, null, etc) becomes true

$return = call_user_func($func, $this);

$this->flush();
$this->conn->commit();

return $return ?: true;

There is the old resolved issue DDC-1336, which describes this behavior.
@return tag is clear now.

@return mixed Returns the non-empty value returned from the closure or true instead

But this logic is blowing mind and leading to unexpectable results. The expected behavior is just return callback result, i don't see any good use cases for current implementation.

It requires a BC break. Can the deprecation process be started to change this behaviour in few major releases?



 Comments   
Comment by Christophe Coevoet [ 07/Nov/13 ]

I agree that this makes the method hard to use. And I don't undertstand why it would replace the return value.

What was the intention for this Benjamin ?

Comment by Guilherme Blanco [ 18/Apr/14 ]

Christophe Coevoet Benjamin Eberlei I'm considering to remove the ternary and always return the callback result.
What do you think? It seems like a minor BC break, but would like to get more feedback around this.

Comment by Marco Pivetta [ 18/Apr/14 ]

Guilherme Blanco this was already refused before because of the BC break.





[DDC-2771] [GH-834] Add example use of repositoryClass in YAML Created: 01/Nov/13  Updated: 04/Nov/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of carlosbuenosvinos:

Url: https://github.com/doctrine/doctrine2/pull/834

Message:



 Comments   
Comment by Doctrine Bot [ 04/Nov/13 ]

A related Github Pull-Request [GH-834] was closed:
https://github.com/doctrine/doctrine2/pull/834





[DDC-2767] ID property of MayToOne association has wrong type Created: 30/Oct/13  Updated: 14/Jul/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: flack Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I'm seeing the following behaviour in some Doctrine code I'm writing:

$entity = array_pop($qb->getQuery()->getResult());
echo gettype($entity->getId()) . ' ' . $entity->getId();
// prints: integer 123

$association = $entity->getAssociation(); // unidirectional ManyToOne link to some other entity
echo gettype($association->getId()) . ' ' . $association->getId();
// prints: string 345

When I load the associated entity directly (via find() f.x.), it's ID has the integer type as expected, and the database structure looks correct, too.

I'm not entirely sure if this is a problem in my code or some issue in QueryBuilder or some other Doctrine component, but if someone could point me into the right direction, that would really be helpful.

I guess normally the type of the ID is not so important because you're not supposed to access it directly anyways, but I need to provide backward compatibility for a lot of code written against a different ORM API that provided exactly this behaviour.



 Comments   
Comment by flack [ 07/Nov/13 ]

After some research, the problem sounds kind of similar to

http://www.doctrine-project.org/jira/browse/DDC-2494

only that in my case, it's not a custom type, but a builtin one that is not working. But AFAICT, in both cases it's getting the ID from a proxy that is problematic

Comment by Doctrine Bot [ 14/Jul/14 ]

A related Github Pull-Request [GH-1073] was closed:
https://github.com/doctrine/doctrine2/pull/1073





[DDC-2763] Inheritance. CTI & STI. Improve lazy load associated entity, when target entity in association mapping is not last leaf in class hierarchy. Created: 27/Oct/13  Updated: 27/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Artur Eshenbrener Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: inheritance


 Description   

If we look inside documentation, we can see this:

There is a general performance consideration with Class Table Inheritance: If the target-entity of a many-to-one or one-to-one association is a CTI entity, it is preferable for performance reasons that it be a leaf entity in the inheritance hierarchy, (ie. have no subclasses). Otherwise Doctrine CANNOT create proxy instances of this entity and will ALWAYS load the entity eagerly.

I think it can be improved, if we will load only discriminator column value for resolve target class name, instead of loading whole entity. When we perform query from root entity, dicriminator value is already present in fetched database row.
What do you think?



 Comments   
Comment by Marco Pivetta [ 27/Oct/13 ]

Queries to fetch the discriminator column cannot be avoided (that's a limitation we can't workaround as far as I know).

What can be improved is avoiding instantiation of the joined results, and instead keep a proxy and a copy of the data for deferred hydration. That would allow avoiding recursive queries which are seen quite often when referencing the root of a STI/JTI

Comment by Artur Eshenbrener [ 27/Oct/13 ]

Queries to fetch the discriminator column cannot be avoided (that's a limitation we can't workaround as far as I know).

Of course, but fetching the discriminator value will produce less overhead than loading whole entity (with recursive loading joined entities). And, when you querying from root entity (with mapped sicriminator column), discriminator value already present in db result row (no need to extra query for dicriminator value).

What can be improved is avoiding instantiation of the joined results, and instead keep a proxy and a copy of the data for deferred hydration. That would allow avoiding recursive queries which are seen quite often when referencing the root of a STI/JTI

The result of my proposal will ability to get proxy class without loading whole entity.





[DDC-2751] [GH-823] Elaborate description of the classIsNotAValidEntityOrMappedSuperClass ex... Created: 20/Oct/13  Updated: 02/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Doctrine Bot Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This issue is created automatically through a Github pull request on behalf of spolischook:

Url: https://github.com/doctrine/doctrine2/pull/823

Message:

...ception



 Comments   
Comment by Doctrine Bot [ 02/Jan/14 ]

A related Github Pull-Request [GH-823] was closed:
https://github.com/doctrine/doctrine2/pull/823





[DDC-2746] When generating DQL query entities with "Class Table Inheritance" is a SQL generated inconsistent Created: 16/Oct/13  Updated: 18/Oct/13

Status: Awaiting Feedback
Project: Doctrine 2 - ORM
Component/s: DQL
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Hugo Henrique Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File DDC2746Test.php     File DDC2746Test_original.php    

 Description   

When I run the query DQL involving entities "Class Table Inheritance" is a SQL generated inconsistent see this gist: https://gist.github.com/hugohenrique/b322e8d998c870265177



 Comments   
Comment by Hugo Henrique [ 17/Oct/13 ]

An example of incoherent generation of SQL:
https://gist.github.com/hugohenrique/b322e8d998c870265177





[DDC-2744] Inheritance - Empty value for discriminatorColumn in query Created: 16/Oct/13  Updated: 16/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Daniel Dos Prazeres Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hello, I have an inheritance problem with the following classes

<?php

namespace Proj\Bundle\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ClassTop
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Proj\Bundle\MyBundle\Repository\ClassTopRepository")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="aVal", type="string")
 * @ORM\DiscriminatorMap({ "ValOne" = "ClassSubOne", "ValTwo" = "ClassSubTwo", "ValThree" = "ClassSubThree" })
 * 
 */
class ClassTop
{
    .....
}

class ClassSubOne extends ClassTop
{
    ....
}

class ClassSubTwo extends ClassTop
{
    ....
}

class ClassSubThree extends ClassTop
{
    ....
}

When i call findAll method my query is not correct

$entityManager->getRepository('ProjMyBundle:ClassSubOne')->findAll()

the query builded

SELECT field, field2 FROM CLASSTOP WHERE AVAL IN () 

The value for the discriminator column is not passed

Thanks for your help






[DDC-2742] 2 ManyToMany relations to the same target entity make the schema update fail by default Created: 15/Oct/13  Updated: 15/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, Tools
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Christophe Coevoet Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: mapping, schematool


 Description   

At some point in the Doctrine releases (I don't remember which version it was), the default naming of the join table of a ManyToMany relation changed from using the property name to using the name of the target entity.

This makes it impossible to use multiple ManyToMany relations to the same target entity in a class without naming join tables explicitly. A SchemaException is thrown by the SchemaTool when trying to update the schema.

Note that this issue is not caught by the SchemaValidator. It will display us that the mapping files are correct (before throwing the above exception in the second step when trying to compare it to the existing database)






[DDC-2733] DefaultQuoteStrategy BUG on Oracle Created: 10/Oct/13  Updated: 26/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers, ORM
Affects Version/s: 2.3.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Pablo Santiago Sánchez Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony on all platforms (Windows, Linux and Mac)
Oracle 11g



 Description   

There's a bug on the DefaultQuoteStrategy when used with Oracle. The getColumnAlias created an invalid alias.

The name of the column had 31 chars, with _ being the 3rd. Column was 101 on the query. Resulting name of the alias started with _, which is invalid name for Oracle.

Example:
CO_SEQ_NOMEGIGANTEPRAKCTMEUDEUS

Alias formed was
_SEQ_NOMEGIGANTEPRAKCTMEUDEUS101

HOW TO FIX:
replace the regex on line 135:
original:
$columnName = preg_replace('/[^A-Za-z0-9_]/', '', $columnName);
fixed:
$columnName = preg_replace('/[^A-Za-z0-9]/', '', $columnName);



 Comments   
Comment by Rudi Uhrig Neto [ 16/Oct/13 ]

Hi there!

I would like to do a contribuition for this issue! I'm not safe with my sugestion, but someone can be helped!

I'm working with 2.4.0 Doctrine Version and I'm facing the same problem, "invalid character" due the function that make a cut off from the begining from alias.

My sugestion to solve this problem is maintain the separator '_' between alias name, but cutting off from the ending alias and reserv the lenght to the counter.

See bellow my modification code at DefaultQuoteStrategy::getColumnAlias() line 130, just replace all lines from function by these below:

DefaultQuoteStrategy.php
public function getColumnAlias($columnName, $counter, AbstractPlatform $platform, ClassMetadata $class = null)
{
    // 1 ) Trim the column alias to the maximum identifier length of the platform.
    //     If the alias is to long, characters are cut off from the ending subtracting the chars reserved to counter.
    // 2 ) Concatenate column name and counter
    // 3 ) Strip non alphanumeric characters
    // 4 ) Prefix with "_" if the result its numeric
    $columnName = substr($columnName, 0, $platform->getMaxIdentifierLength() - strlen($counter));
    $columnName = $columnName . $counter;
    $columnName = preg_replace('/[^A-Za-z0-9_]/', '', $columnName);
    $columnName = is_numeric($columnName) ? '_' . $columnName : $columnName;
      
    return $platform->getSQLResultCasing($columnName);
}

What do you guys think?

Comment by Pablo Santiago Sánchez [ 16/Oct/13 ]

Rudi, prefixing it with _ would keep the problem on Oracle. Since that name is for aliasing pourposes only, the _ char is useless.

I just remembered another possible situation: fields should not start with numbers!

Comment by Rudi Uhrig Neto [ 16/Oct/13 ]

Pablo,

The changes in my sugestion code don't consider the prefix '_', indepedent of the characteres in alias column name, the function will remove the last characteres from alias... see an example with column name DT_VERIFICACAO_SITUACAO_ACESSO.

The current code create a sql:
DT_VERIFICACAO_SITUACAO_ACESSO AS _VERIFICACAO_SITUACAO_ACESSO23,

My sugestion will produce:
DT_VERIFICACAO_SITUACAO_ACESSO AS DT_VERIFICACAO_SITUACAO_ACES23,

Comment by Pablo Santiago Sánchez [ 18/Oct/13 ]

Oh, sorry, my mistake. Your solution sounds better.

Since there's still no solution from the Doctrine Team, I'm iusing my own QuoteStrategy. Hope this bug gets fixed soon.

Comment by Benjamin Eberlei [ 26/Oct/13 ]

Fabio B. Silva Can you comment on Rudi Uhrig Neto solution? Its easily changed, but I am wondering if this is backwards compatible. I would want to merge the fix back to 2.3 and 2.4. Branch is ready to be committed for me locally.





pager produces wrong results on postgresql (DDC-1958)

[DDC-2729] Same bug affects SQLServer2008Platform Created: 07/Oct/13  Updated: 07/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: Tools
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Sub-task Priority: Major
Reporter: Rafi Adnan Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: paginator
Environment:

SQL Server 10.50.1617
unixODBC 2.2.14
PHP 5.4.19



 Description   

If the class is patched with the following:

if ($this->platform instanceof SQLServer2008Platform)

{ $this->preserveSqlOrdering($AST, $sqlIdentifier, $innerSql, $sql); }

It fixes the issue.






[DDC-2727] "Expression" or "Update" API, similar to the Criteria API Created: 07/Oct/13  Updated: 07/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Matthieu Napoli Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I created a discussion in the mailing list (https://groups.google.com/forum/#!topic/doctrine-dev/7HfEqOwhkDk) but no answer, so I'm moving the discussion here.


The Criteria API provides an abstraction to filter collections/repositories, may they be in memory (filtering in PHP) or in a database (filtering using a SQL query).

I was thinking about an "Expression" API which would work like array_map to apply changes in bulk to entities.

For example, if you have a collection where entities have a $position field, if I insert an item in the list, I have to increment the position of all the following items. For this, I have 2 options:

  • PHP: loading the entities in memory, iterate over them and increment $position
  • SQL: run a UPDATE position=position + 1 WHERE …

The second option is much more efficient, but it breaks the abstraction of the model because I have some behavior written explicitely in SQL. Furthermore, the objects loaded in memory will note be updated with the SQL query.

So the "Expression" API would work like the Criteria API:

interface Updatable {
    public function apply(Expression $e);
}

$expression = new Expression();

// For each item after position "10"
$expression->criteria->where(Criteria::expr()->gt('position', 10));
// Increment the position
$expression->set('position', 'position + 1');

$collection->map($expression);

The expression here would be applied:

  • in memory if the collection is already loaded
  • else in database using SQL

The expression could be applied to a Collection and to a Repository (like the Criteria).


About the API offered by the Expression class, there are several options:

// Option 1
// More powerful, but needs to parse and evaluate the string
class Expression
{
    public $criteria;
    public function set($field, $value);
}
 
$expression->set('position', 'position + 1');
 
// Option 2
// Easier to implement, more limited
class Expression
{
    public $criteria;
    public function setValue($field, $value);
    public function setValueFromField($targetField, $sourceField);
    public function add($field, $number);
    public function multiply($field, $number);
    public function divide($field, $number);
}
 
// Option 3
// Like option 2 but more extensible
class Expression
{
    public $criteria;
    public function set($field, Operation $operation);
}

I think I like the third one better because we have full control over the supported operations, and adding support to new kinds of operation is easy. The first one would require defining a whole language of allowed expressions...


What do you think of all that?



 Comments   
Comment by Matthieu Napoli [ 07/Oct/13 ]

Added option 3 after trying to write a POC

Comment by Matthieu Napoli [ 07/Oct/13 ]

Here is a POC on the doctrine/collections side: https://github.com/mnapoli/collections/compare/master...feature;Updatable works with ArrayCollection

I'm looking at the ORM side.

Feedback welcome, especially with the class/namespace/method names.





[DDC-2726] EventSubscriber PreUpdate Error Bug? Created: 06/Oct/13  Updated: 17/Oct/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Nelson Ford Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: orm


 Description   

Should this:

public function preUpdate(PreUpdateEventArgs $eventArgs)
{
    $entity = $eventArgs->getEntity();
    $em = $eventArgs->getEntityManager();
    $uow = $em->getUnitOfWork();

    if ($entity instanceof User) {
        if ($eventArgs->hasChangedField('finalStatus')) {
            $entity->setFinalStatusDate(new \DateTime('now'));
            $uow->recomputeSingleEntityChangeSet(
                $em->getClassMetadata("MyAdminBundle:User"),
                $entity
            );
        }
        if ($eventArgs->hasChangedField('membershipCode')) {
            $entity->setMembershipCodeDate(new \DateTime('now'));
            $uow->recomputeSingleEntityChangeSet(
                $em->getClassMetadata("MyAdminBundle:User"),
                $entity
            );
        }
    }
}

...result in this?

Catchable Fatal Error: Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::__construct() must be an array, null given, called in /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 995 and defined in /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Event/PreUpdateEventArgs.php line 47

I'm just setting a time stamp for two updated values. Dumping the 3rd argument in PreUpdateEventArgs.php on line 47 reveals an array of changes. I'm not sure if this is a bug or if I'm performing this simple operation incorrectly.



 Comments   
Comment by Marco Pivetta [ 17/Oct/13 ]

Can you write an integration test around it? Looks like the changeset is removed in a particular edge case, but it's hard to figure it out without a test.





[DDC-2709] Defining Columns as "Updatable" or "Insertable" Created: 27/Sep/13  Updated: 27/Sep/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Martin Prebio Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

With Hibernate I can define a column as Updatable/Insertable or non-Updatable/non-Insertable so that this field is considered read-only and is not part of any update/insert statement. I'd like to have the same possibility in Doctrine.

In my use case a value is generated and maintained by database triggers. In my application I only want to read this value but the application should never try to insert or update the column.

Updatable/Insertable in the Hibernate documentation: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-property-column






[DDC-2704] When using Discriminator EntityManager#merge fails Created: 25/Sep/13  Updated: 25/Sep/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Vladyslav Petrovych Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I have the following hierarchy:

  • AgentConfig has relation ManyToOne with AgentTask.
  • AgentTask has DiscriminatorColumn & DiscriminatorMap assigned to it.
  • AgentTask has relation ManyToOne with AgentTaskConfig.

I believe the problem is because of the following:

UnitOfWork#doMerge has the tries to get properties the following way:

// Merge state of $entity into existing (managed) entity
foreach ($class->reflClass->getProperties() as $prop) {

This obviously doesn't get the parent class (AgentTask) properties.

Later on UnitOfWork fails on line:

$prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);

because $prevManagedCopy doesn't have properties set from entity.

My proposal is to get the properties the following way:

$properties = $class->reflClass->getProperties();
$parent = $class->reflClass;
while (($parent = $parent->getParentClass()) != null) {
    $properties = array_merge($parent->getProperties(), $properties);
}

// Merge state of $entity into existing (managed) entity
foreach ($properties as $prop) {





[DDC-2701] Collections in originalEntityData gets over written Created: 23/Sep/13  Updated: 23/Sep/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: None
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Thomas Klein Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I was trying to use the UnitOfWork::getOriginalEntityData method and i noticed that if there is a collection in that object, it changes in the uow original datas when i change it on my original object

In my case the collection is ManyToMany unidirectional

I think this happens because both the uow and the object work with the same reference to the collection
maybe adding a clone of the collection instead of the real one, i don't know if it is possible

Thank you for taking a look and for Doctrine!

Tom






[DDC-2697] ObjectHydrator::hydrateRowData fails to hydrate first fetch joined entity Created: 20/Sep/13  Updated: 06/Dec/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3, 2.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Austin Morris Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: orm
Environment:

All



 Description   

Let's say I have accounts, contacts, and contact types. Any given contact can have be any kind of contact type to any account. This is all managed through an account_contacts table with a 3-way composite PK of the contact_id, account_id, and type_id.

All of this translates to 4 entities, the account, contact, type, and accountContact entity. The id of the accountContact entity is the three other entities which is holds.

When I use query builder to retrieve the accountContacts based on some condition, and also fetch join contacts, accounts, and types so that they are eagerly loaded, the ObjectHydrator fails to load the first accountContact returned.

This is because the first time through hydrateRowData, the fetch joined entities are hydrated first. The problem is $this->_rsm->parentAliasMap[$dqlAlias] does not contain an entry for the accountContact (root entity). Not until an accountContact is hydrated does that get set. In the mean time, the other three entities were set to null because there is no parent alias yet (in version 2.4, this is line 405.

Subsequent loops through hydrateRowData work because by this time the parent alias is set. But that first row returned is always an accountContact containing three null objects.



 Comments   
Comment by Benjamin Eberlei [ 26/Oct/13 ]

Austin Morris Can you show the QueryBuilder select clause you are using? Have you tried sorting the accountContacts first?

$qb->select('accountContacts, contact, account, type')

This way it should definately work, and then there is also some attempts to resort this way if you dont have that, but its not always working.

Comment by Austin Morris [ 06/Dec/13 ]

Sorry, I don't have the original select clause. I ended up doing something different and can't seem to find my original code.

Comment by Benjamin Eberlei [ 06/Dec/13 ]

I have another person that reported a simliiar bug with reproducable test case. I hope to investigate this very soon.





[DDC-2695] Order by clause left in subquery when using MSSQL and Paginator Created: 20/Sep/13  Updated: 20/Sep/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.3.4
Fix Version/s: None
Security Level: All

Type: Bug Priority: Major
Reporter: Paul Mansell Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows, Microsoft SQL Server



 Description   

When using the Doctrine paginator and Fetch Join Collections = true and when the original query has an "ORDER BY" clause in it - the subquery created is something like "SELECT DISTINCT FROM (.... ORDER BY ....) as dctrn_result" - when using Microsoft SQL server having the "ORDER BY" clause in a subquery throws an error. This is a similar problem to http://doctrine-project.org/jira/browse/DDC-2282 but that was for the Count Walker - this is for the LimitSubqueryOutputWalker. The fix is the same.



 Comments   
Comment by Paul Mansell [ 20/Sep/13 ]

Problem still occurs in 2.4 - but different error message,

Query :

SELECT * FROM (SELECT DISTINCT id0, ROW_NUMBER() OVER (ORDER BY c1_.iccid ASC) AS doctrine_rownum FROM (SELECT w0_.id AS id0, w0_.batch_id AS batch_id1, c1_.id AS id2, c1_.iccid AS iccid3, c2_.id AS id4, c2_.msisdn AS msisdn5, c3_.id AS id6, c3_.name AS name7, c4_.id AS id8, c5_.id AS id9, c5_.name AS name10, w6_.id AS id11, w6_.created AS created12, w7_.id AS id13, w7_.ident AS ident14, w8_.id AS id15, w8_.ident AS ident16, c9_.id AS id17, c10_.id AS id18, c10_.contract_length AS contract_length19, c10_.rental AS rental20, w11_.id AS id21, w11_.ident AS ident22 FROM workflow_request w0_ WITH (NOLOCK) INNER JOIN core_sim c1_ ON w0_.sim = c1_.id LEFT JOIN core_connection c2_ ON c1_.active_connection_id = c2_.id INNER JOIN core_billing_account c3_ ON c1_.billing_account_id = c3_.id INNER JOIN core_mno_account c4_ ON c1_.mno_account_id = c4_.id INNER JOIN core_mno c5_ ON c4_.mno_id = c5_.id INNER JOIN workflow_request_log w6_ ON w0_.id = w6_.request INNER JOIN workflow_action w7_ ON w0_.action = w7_.id INNER JOIN workflow_request_status w8_ ON w0_.status = w8_.id INNER JOIN core_customer_solution c9_ ON w0_.customer_solution = c9_.id INNER JOIN core_customer_tariff c10_ ON c9_.customer_tariff_id = c10_.id INNER JOIN workflow_request_action w11_ ON w6_.request_action = w11_.id WHERE w7_.ident IN AND w8_.ident = ? AND w11_.ident = ?) dctrn_result) AS doctrine_tbl WHERE doctrine_rownum BETWEEN 1 AND 25' with params ["activate", "network", "approved"]

Error :

SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]The multi-part identifier "c1_.iccid" could not be bound.





[DDC-2694] Hydrating with entities with the NEW operator Created: 19/Sep/13  Updated: 21/Jan/14

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: New Feature Priority: Major
Reporter: Flip Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None

Issue Links:
Duplicate
is duplicated by DDC-2899 Allow the NEW operator to construct o... Resolved

 Description   

It would be nice if the new function accepted objects as parameters, like this:

new Country(country, some_extra_stuff)

Alternatively another keyword could be introduced that constructs the object with the parameter and afterwards hydrates it.






[DDC-2691] Test Suite: Drop other connections before dropping database PostgreSQL Created: 19/Sep/13  Updated: 19/Sep/13

Status: Open
Project: Doctrine 2 - ORM
Component/s: None
Affects Version/s: Git Master
Fix Version/s: None
Security Level: All

Type: Improvement Priority: Major
Reporter: Flip Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 Professional 64 bits
PHP 5.4.11 (cli) (built: Jan 16 2013 20:26:26)
Doctrine dev-master from 18-9-2013
PostgreSQL 9.2.4 build 1600, 64-bits



 Description   

The test suite is trying to run the command

DROP DATABASE doctrine_tests

This fails, together with lots of tests when another user is connected (for example through the pgAdmin program). It would be nice if the test suite had an option to drop existing connections, which can be done with the following command:

SELECT pg_terminate_ba